summaryrefslogtreecommitdiff
path: root/indra/mac_crash_logger/mac_crash_logger.cpp
blob: 5e6d9ba2f0b719b6878d6bf2ca32d56413aef7b8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
/** 
 * @file mac_crash_logger.cpp
 * @brief Mac OSX crash logger implementation
 *
 * Copyright (c) 2003-$CurrentYear$, Linden Research, Inc.
 * $License$
 */

#include "linden_common.h"

#include <stdio.h>
#include <stdlib.h>
//#include <direct.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#include <curl/curl.h>

#include "llerror.h"
#include "lltimer.h"
#include "lldir.h"

#include "llstring.h"

class LLFileEncoder
{
public:
	LLFileEncoder(const char *formname, const char *filename, bool isCrashLog = false);

	BOOL isValid() const { return mIsValid; }
	LLString encodeURL(const S32 max_length = 0);
public:
	BOOL mIsValid;
	LLString mFilename;
	LLString mFormname;
	LLString mBuf;
};

LLString encode_string(const char *formname, const LLString &str);

#include <Carbon/Carbon.h>

LLString gServerResponse;
BOOL gSendReport = FALSE;
LLString gUserserver;
LLString gUserText;
WindowRef gWindow = NULL;
EventHandlerRef gEventHandler = NULL;
BOOL gCrashInPreviousExec = FALSE;
time_t gLaunchTime;

size_t curl_download_callback(void *data, size_t size, size_t nmemb,
										  void *user_data)
{
	S32 bytes = size * nmemb;
	char *cdata = (char *) data;
	for (int i =0; i < bytes; i += 1)
	{
		gServerResponse += (cdata[i]);
	}
	return bytes;
}

OSStatus dialogHandler(EventHandlerCallRef handler, EventRef event, void *userdata)
{
	OSStatus result = eventNotHandledErr;
	OSStatus err;
	UInt32 evtClass = GetEventClass(event);
	UInt32 evtKind = GetEventKind(event);
	
	if((evtClass == kEventClassCommand) && (evtKind == kEventCommandProcess))
	{
		HICommand cmd;
		err = GetEventParameter(event, kEventParamDirectObject, typeHICommand, NULL, sizeof(cmd), NULL, &cmd);
		
		if(err == noErr)
		{
			switch(cmd.commandID)
			{
				case kHICommandOK:
				{
					char buffer[65535];
					Size size = sizeof(buffer) - 1;
					ControlRef textField = NULL;
					ControlID id;

					id.signature = 'text';
					id.id = 0;

					err = GetControlByID(gWindow, &id, &textField);
					if(err == noErr)
					{
						// Get the user response text
						err = GetControlData(textField, kControlNoPart, kControlEditTextTextTag, size, (Ptr)buffer, &size);
					}
					if(err == noErr)
					{
						// Make sure the string is terminated.
						buffer[size] = 0;
						gUserText = buffer;
						llinfos << buffer << llendl;
					}
					
					// Send the report.
					gSendReport = TRUE;

					QuitAppModalLoopForWindow(gWindow);
					result = noErr;
				}
				break;
				
				case kHICommandCancel:
					QuitAppModalLoopForWindow(gWindow);
					result = noErr;
				break;
			}
		}
	}
	
	return(result);
}

int main(int argc, char **argv)
{
	const S32 DW_MAX_SIZE = 100000;			// Maximum size to transmit of the Dr. Watson log file
	const S32 SL_MAX_SIZE = 100000;			// Maximum size of the Second Life log file.
	int i;
	
	time(&gLaunchTime);
	
	llinfos << "Starting Second Life Viewer Crash Reporter" << llendl;
	
	for(i=1; i<argc; i++)
	{
		if(!strcmp(argv[i], "-previous"))
		{
			gCrashInPreviousExec = TRUE;
		}
		if(!strcmp(argv[i], "-user"))
		{
			if ((i + 1) < argc)
			{
				i++;
				gUserserver = argv[i];
				llinfos << "Got userserver " << gUserserver << llendl;
			}
		}
	}
	
	if( gCrashInPreviousExec )
	{
		llinfos << "Previous execution did not remove SecondLife.exec_marker" << llendl;
	}
	
	if(!gCrashInPreviousExec)
	{
		// Delay five seconds to let CrashReporter do its thing.
		sleep(5);
	}
		
#if 1
	// Real UI...
	OSStatus err;
	IBNibRef nib = NULL;
	
	err = CreateNibReference(CFSTR("CrashReporter"), &nib);
	
	if(err == noErr)
	{
		if(gCrashInPreviousExec)
		{
			err = CreateWindowFromNib(nib, CFSTR("CrashReporterDelayed"), &gWindow);
		}
		else
		{
			err = CreateWindowFromNib(nib, CFSTR("CrashReporter"), &gWindow);
		}
	}

	if(err == noErr)
	{
		// Set focus to the edit text area
		ControlRef textField = NULL;
		ControlID id;

		id.signature = 'text';
		id.id = 0;
		
		// Don't set err if any of this fails, since it's non-critical.
		if(GetControlByID(gWindow, &id, &textField) == noErr)
		{
			SetKeyboardFocus(gWindow, textField, kControlFocusNextPart);
		}
	}
	
	if(err == noErr)
	{
		ShowWindow(gWindow);
	}
	
	if(err == noErr)
	{
		// Set up an event handler for the window.
		EventTypeSpec handlerEvents[] = 
		{
			{ kEventClassCommand, kEventCommandProcess }
		};

		InstallWindowEventHandler(
				gWindow, 
				NewEventHandlerUPP(dialogHandler), 
				GetEventTypeCount (handlerEvents), 
				handlerEvents, 
				0, 
				&gEventHandler);
	}
			
	if(err == noErr)
	{
		RunAppModalLoopForWindow(gWindow);
	}
			
	if(gWindow != NULL)
	{
		DisposeWindow(gWindow);
	}
	
	if(nib != NULL)
	{
		DisposeNibReference(nib);
	}
#else
	// Cheap version -- just use the standard system alert.
	SInt16 itemHit = 0;
	AlertStdCFStringAlertParamRec params;
	OSStatus err = noErr;
	DialogRef alert = NULL;

	params.version = kStdCFStringAlertVersionOne;
	params.movable = false;
	params.helpButton = false;
	params.defaultText = CFSTR("Send Report");
	params.cancelText = CFSTR("Don't Send Report");
	params.otherText = 0;
	params.defaultButton = kAlertStdAlertOKButton;
	params.cancelButton = kAlertStdAlertCancelButton;
	params.position = kWindowDefaultPosition;
	params.flags = 0;

	err = CreateStandardAlert(
			kAlertCautionAlert,
			CFSTR("Second Life appears to have crashed."),
			CFSTR(
			"To help us debug the problem, you can send a crash report to Linden Lab.  "
			"The report contains information about your microprocessor type, graphics card, "
			"memory, things that happened during the last run of the program, and the Crash Log "
			"of where the crash occurred.\r"
			"\r"
			"You may also report crashes in the forums, or by sending e-mail to peter@lindenlab.com"),
			&params,
			&alert);
	
	if(err == noErr)
	{
		err = RunStandardAlert(
				alert,
				NULL,
				&itemHit);
  	}
	
	if(itemHit == kAlertStdAlertOKButton)
		gSendReport = TRUE;
#endif
	
	if(!gSendReport)
	{
		// Only send the report if the user agreed to it.
		llinfos << "User cancelled, not sending report" << llendl;

		return(0);
	}

	// We assume that all the logs we're looking for reside on the current drive
	gDirUtilp->initAppDirs("SecondLife");

	int res;

	// Lots of silly variable, replicated for each log file.
	LLString db_file_name;
	LLString sl_file_name;
	LLString dw_file_name; // DW file name is a hack for now...
	LLString st_file_name; // stats.log file
	LLString si_file_name; // settings.ini file

	LLFileEncoder *db_filep = NULL;
	LLFileEncoder *sl_filep = NULL;
	LLFileEncoder *st_filep = NULL;
	LLFileEncoder *dw_filep = NULL;
	LLFileEncoder *si_filep = NULL;

	///////////////////////////////////
	//
	// We do the parsing for the debug_info file first, as that will
	// give us the location of the SecondLife.log file.
	//

	// Figure out the filename of the debug log
	db_file_name = gDirUtilp->getExpandedFilename(LL_PATH_LOGS,"debug_info.log").c_str();
	db_filep = new LLFileEncoder("DB", db_file_name.c_str());

	// Get the filename of the SecondLife.log file
	char tmp_sl_name[MAX_PATH];
	tmp_sl_name[0] = '\0';
	char tmp_space[256];
	tmp_space[0] = '\0';

	// Look for it in the debug_info.log file
	if (db_filep->isValid())
	{
		// This was originally scanning for "SL Log: %[^\r\n]", which happily skipped to the next line
		// on debug logs (which don't have anything after "SL Log:" and tried to open a nonsensical filename.
		sscanf(db_filep->mBuf.c_str(), "SL Log:%[ ]%[^\r\n]", tmp_space, tmp_sl_name);
	}
	else
	{
		delete db_filep;
		db_filep = NULL;
	}

	// If we actually have a legitimate file name, use it.
	if (tmp_sl_name[0])
	{
		sl_file_name = tmp_sl_name;
		llinfos << "Using log file from debug log " << sl_file_name << llendl;
	}
	else
	{
		// Figure out the filename of the second life log
		sl_file_name = gDirUtilp->getExpandedFilename(LL_PATH_LOGS,"SecondLife.log").c_str();
	}

	// Now we get the SecondLife.log file if it's there, and recent enough...
	sl_filep = new LLFileEncoder("SL", sl_file_name.c_str());
	if (!sl_filep->isValid())
	{
		delete sl_filep;
		sl_filep = NULL;
	}

	st_file_name = gDirUtilp->getExpandedFilename(LL_PATH_LOGS,"stats.log").c_str();
	st_filep = new LLFileEncoder("ST", st_file_name.c_str());
	if (!st_filep->isValid())
	{
		delete st_filep;
		st_filep = NULL;
	}

	si_file_name = gDirUtilp->getExpandedFilename(LL_PATH_USER_SETTINGS,"settings.ini").c_str();
	si_filep = new LLFileEncoder("SI", si_file_name.c_str());
	if (!si_filep->isValid())
	{
		delete si_filep;
		si_filep = NULL;
	}

	// MBW -- This needs to go find "~/Library/Logs/CrashReporter/Second Life.crash.log" on 10.3
	// or "~/Library/Logs/Second Life.crash.log" on 10.2.
	{
		char path[MAX_PATH];
		FSRef folder;
		
		if(FSFindFolder(kUserDomain, kLogsFolderType, false, &folder) == noErr)
		{
			// folder is an FSRef to ~/Library/Logs/
			if(FSRefMakePath(&folder, (UInt8*)&path, sizeof(path)) == noErr)
			{
				struct stat dw_stat;
//				printf("path is %s\n", path);
				
				// Try the 10.3 path first...
				dw_file_name = LLString(path) + LLString("/CrashReporter/Second Life.crash.log");
				res = stat(dw_file_name.c_str(), &dw_stat);

				if (res)
				{
					// Try the 10.2 one next...
					dw_file_name = LLString(path) + LLString("/Second Life.crash.log");
					res = stat(dw_file_name.c_str(), &dw_stat);
				}
				
				if (!res)
				{
					dw_filep = new LLFileEncoder("DW", dw_file_name.c_str(), true);
					if (!dw_filep->isValid())
					{
						delete dw_filep;
						dw_filep = NULL;
					}
				}
				else
				{
					llwarns << "Couldn't find any CrashReporter files..." << llendl;
				}
			}
		}
	}

	LLString post_data;
	LLString tmp_url_buf;

	// Append the userserver
	tmp_url_buf = encode_string("USER", gUserserver);
	post_data += tmp_url_buf;
	llinfos << "PostData:" << post_data << llendl;

	if (gCrashInPreviousExec)
	{
		post_data.append("&");
		tmp_url_buf = encode_string("EF", "Y");
		post_data += tmp_url_buf;
	}

	if (db_filep)
	{
		post_data.append("&");
		tmp_url_buf = db_filep->encodeURL();
		post_data += tmp_url_buf;
		llinfos << "Sending DB log file" << llendl;
	}
	else
	{
		llinfos << "Not sending DB log file" << llendl;
	}

	if (sl_filep)
	{
		post_data.append("&");
		tmp_url_buf = sl_filep->encodeURL(SL_MAX_SIZE);
		post_data += tmp_url_buf;
		llinfos << "Sending SL log file" << llendl;
	}
	else
	{
		llinfos << "Not sending SL log file" << llendl;
	}

	if (st_filep)
	{
		post_data.append("&");
		tmp_url_buf = st_filep->encodeURL(SL_MAX_SIZE);
		post_data += tmp_url_buf;
		llinfos << "Sending stats log file" << llendl;
	}
	else
	{
		llinfos << "Not sending stats log file" << llendl;
	}

	if (dw_filep)
	{
		post_data.append("&");
		tmp_url_buf = dw_filep->encodeURL(DW_MAX_SIZE);
		post_data += tmp_url_buf;
	}
	else
	{
		llinfos << "Not sending crash log file" << llendl;
	}

	if (si_filep)
	{
		post_data.append("&");
		tmp_url_buf = si_filep->encodeURL();
		post_data += tmp_url_buf;
		llinfos << "Sending settings log file" << llendl;
	}
	else
	{
		llinfos << "Not sending settings.ini file" << llendl;
	}

	if (gUserText.size())
	{
		post_data.append("&");
		tmp_url_buf = encode_string("UN", gUserText);
		post_data += tmp_url_buf;
	}

	delete db_filep;
	db_filep = NULL;
	delete sl_filep;
	sl_filep = NULL;
	delete dw_filep;
	dw_filep = NULL;

	// Debugging spam
#if 0
	printf("Crash report post data:\n--------\n");
	printf("%s", post_data.getString());
	printf("\n--------\n");
#endif
	
	// Send the report.  Yes, it's this easy.
	{
		CURL *curl = curl_easy_init();

		curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &curl_download_callback);
		curl_easy_setopt(curl, CURLOPT_POST, 1); 
		curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_data.c_str()); 
		curl_easy_setopt(curl, CURLOPT_URL,	"http://secondlife.com/cgi-bin/viewer_crash_reporter2");
		
		llinfos << "Connecting to crash report server" << llendl;
		CURLcode result = curl_easy_perform(curl);
		
		curl_easy_cleanup(curl);
		
		if(result != CURLE_OK)
		{
			llinfos << "Couldn't talk to crash report server" << llendl;
		}
		else
		{
			llinfos << "Response from crash report server:" << llendl;
			llinfos << gServerResponse << llendl;			
		}
	}
	
	return 0;
}

LLFileEncoder::LLFileEncoder(const char *form_name, const char *filename, bool isCrashLog)
{
	mFormname = form_name;
	mFilename = filename;
	mIsValid = FALSE;

	int res;
	
	struct stat stat_data;
	res = stat(mFilename.c_str(), &stat_data);
	if (res)
	{
		llwarns << "File " << mFilename << " is missing!" << llendl;
		return;
	}
	else
	{
		// Debugging spam
//		llinfos << "File " << mFilename << " is present..." << llendl;

		if(!gCrashInPreviousExec && isCrashLog)
		{
			// Make sure the file isn't too old.
			double age = difftime(gLaunchTime, stat_data.st_mtimespec.tv_sec);

//			llinfos << "age is " << age << llendl;

			if(age > 60.0)
			{
				// The file was last modified more than 60 seconds before the crash reporter was launched.  Assume it's stale.
				llwarns << "File " << mFilename << " is too old!" << llendl;
				return;
			}
		}

	}

	S32 buf_size = stat_data.st_size;
	FILE *fp = fopen(mFilename.c_str(), "rb");
	U8 *buf = new U8[buf_size + 1];
	fread(buf, 1, buf_size, fp);
	fclose(fp);
	buf[buf_size] = 0;

	mBuf = (char *)buf;
	
	if(isCrashLog)
	{
		// Crash logs consist of a number of entries, one per crash.
		// Each entry is preceeded by "**********" on a line by itself.
		// We want only the most recent (i.e. last) one.
		const char *sep = "**********";
		const char *start = mBuf.c_str();
		const char *cur = start;
		const char *temp = strstr(cur, sep);
		
		while(temp != NULL)
		{
			// Skip past the marker we just found
			cur = temp + strlen(sep);
			
			// and try to find another
			temp = strstr(cur, sep);
		}
		
		// If there's more than one entry in the log file, strip all but the last one.
		if(cur != start)
		{
			mBuf.erase(0, cur - start);
		}
	}

	mIsValid = TRUE;
	delete[] buf;
}

LLString LLFileEncoder::encodeURL(const S32 max_length)
{
	LLString result = mFormname;
	result.append("=");

	S32 i = 0;

	if (max_length)
	{
		if (mBuf.size() > max_length)
		{
			i = mBuf.size() - max_length;
		}
	}

#if 0
	// Plain text version for debugging
	result.append(mBuf);
#else
	// Not using LLString because of bad performance issues
	S32 buf_size = mBuf.size();
	S32 url_buf_size = 3*mBuf.size() + 1;
	char *url_buf = new char[url_buf_size];

	S32 cur_pos = 0;
	for (; i < buf_size; i++)
	{
		sprintf(url_buf + cur_pos, "%%%02x", mBuf[i]);
		cur_pos += 3;
	}
	url_buf[i*3] = 0;

	result.append(url_buf);
	delete[] url_buf;
#endif
	return result;
}

LLString encode_string(const char *formname, const LLString &str)
{
	LLString result = formname;
	result.append("=");
	// Not using LLString because of bad performance issues
	S32 buf_size = str.size();
	S32 url_buf_size = 3*str.size() + 1;
	char *url_buf = new char[url_buf_size];

	S32 cur_pos = 0;
	S32 i;
	for (i = 0; i < buf_size; i++)
	{
		sprintf(url_buf + cur_pos, "%%%02x", str[i]);
		cur_pos += 3;
	}
	url_buf[i*3] = 0;

	result.append(url_buf);
	delete[] url_buf;
	return result;
}