1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <sys/types.h>
5 #include <sys/stat.h>
6 #include <sys/wait.h>
7 #include <sys/param.h>
8 #include <sys/ucontext.h>
9 #include <string.h>
10 #include <errno.h>
11 #include <limits.h>
12 
13 #ifdef __linux__
14 #include <sys/prctl.h>
15 #ifndef PR_SET_PTRACER
16 #define PR_SET_PTRACER 0x59616d61
17 #endif
18 #elif defined (__APPLE__) || defined (__FreeBSD__)
19 #include <signal.h>
20 #endif
21 
22 
23 static const char crash_switch[] = "--cc-handle-crash";
24 
25 static const char fatal_err[] = "\n\n*** Fatal Error ***\n";
26 static const char pipe_err[] = "!!! Failed to create pipe\n";
27 static const char fork_err[] = "!!! Failed to fork debug process\n";
28 static const char exec_err[] = "!!! Failed to exec debug process\n";
29 
30 static char argv0[PATH_MAX];
31 
32 static char altstack[SIGSTKSZ];
33 
34 
35 static struct {
36 	int signum;
37 	pid_t pid;
38 	int has_siginfo;
39 	siginfo_t siginfo;
40 	char buf[4096];
41 } crash_info;
42 
43 
44 static const struct {
45 	const char *name;
46 	int signum;
47 } signals[] = {
48 	{ "Segmentation fault", SIGSEGV },
49 	{ "Illegal instruction", SIGILL },
50 	{ "FPU exception", SIGFPE },
51 	{ "System BUS error", SIGBUS },
52 	{ NULL, 0 }
53 };
54 
55 static const struct {
56 	int code;
57 	const char *name;
58 } sigill_codes[] = {
59 #ifndef __FreeBSD__
60 	{ ILL_ILLOPC, "Illegal opcode" },
61 	{ ILL_ILLOPN, "Illegal operand" },
62 	{ ILL_ILLADR, "Illegal addressing mode" },
63 	{ ILL_ILLTRP, "Illegal trap" },
64 	{ ILL_PRVOPC, "Privileged opcode" },
65 	{ ILL_PRVREG, "Privileged register" },
66 	{ ILL_COPROC, "Coprocessor error" },
67 	{ ILL_BADSTK, "Internal stack error" },
68 #endif
69 	{ 0, NULL }
70 };
71 
72 static const struct {
73 	int code;
74 	const char *name;
75 } sigfpe_codes[] = {
76 	{ FPE_INTDIV, "Integer divide by zero" },
77 	{ FPE_INTOVF, "Integer overflow" },
78 	{ FPE_FLTDIV, "Floating point divide by zero" },
79 	{ FPE_FLTOVF, "Floating point overflow" },
80 	{ FPE_FLTUND, "Floating point underflow" },
81 	{ FPE_FLTRES, "Floating point inexact result" },
82 	{ FPE_FLTINV, "Floating point invalid operation" },
83 	{ FPE_FLTSUB, "Subscript out of range" },
84 	{ 0, NULL }
85 };
86 
87 static const struct {
88 	int code;
89 	const char *name;
90 } sigsegv_codes[] = {
91 #ifndef __FreeBSD__
92 	{ SEGV_MAPERR, "Address not mapped to object" },
93 	{ SEGV_ACCERR, "Invalid permissions for mapped object" },
94 #endif
95 	{ 0, NULL }
96 };
97 
98 static const struct {
99 	int code;
100 	const char *name;
101 } sigbus_codes[] = {
102 #ifndef __FreeBSD__
103 	{ BUS_ADRALN, "Invalid address alignment" },
104 	{ BUS_ADRERR, "Non-existent physical address" },
105 	{ BUS_OBJERR, "Object specific hardware error" },
106 #endif
107 	{ 0, NULL }
108 };
109 
110 static int (*cc_user_info)(char*, char*);
111 
112 
gdb_info(pid_t pid)113 static void gdb_info(pid_t pid)
114 {
115 	char respfile[64];
116 	char cmd_buf[128];
117 	FILE *f;
118 	int fd;
119 
120 	/* Create a temp file to put gdb commands into */
121 	strcpy(respfile, "gdb-respfile-XXXXXX");
122 	if((fd=mkstemp(respfile)) >= 0 && (f=fdopen(fd, "w")) != NULL)
123 	{
124 		fprintf(f, "attach %d\n"
125 		           "shell echo \"\"\n"
126 		           "shell echo \"* Loaded Libraries\"\n"
127 		           "info sharedlibrary\n"
128 		           "shell echo \"\"\n"
129 		           "shell echo \"* Threads\"\n"
130 		           "info threads\n"
131 		           "shell echo \"\"\n"
132 		           "shell echo \"* FPU Status\"\n"
133 		           "info float\n"
134 		           "shell echo \"\"\n"
135 		           "shell echo \"* Registers\"\n"
136 		           "info registers\n"
137 		           "shell echo \"\"\n"
138 		           "shell echo \"* Backtrace\"\n"
139 		           "thread apply all backtrace full\n"
140 		           "detach\n"
141 		           "quit\n", pid);
142 		fclose(f);
143 
144 		/* Run gdb and print process info. */
145 		snprintf(cmd_buf, sizeof(cmd_buf), "gdb --quiet --batch --command=%s", respfile);
146 		printf("Executing: %s\n", cmd_buf);
147 		fflush(stdout);
148 
149 		system(cmd_buf);
150 		/* Clean up */
151 		remove(respfile);
152 	}
153 	else
154 	{
155 		/* Error creating temp file */
156 		if(fd >= 0)
157 		{
158 			close(fd);
159 			remove(respfile);
160 		}
161 		printf("!!! Could not create gdb command file\n");
162 	}
163 	fflush(stdout);
164 }
165 
sys_info(void)166 static void sys_info(void)
167 {
168 #ifdef __unix__
169 	system("echo \"System: `uname -a`\"");
170 	putchar('\n');
171 	fflush(stdout);
172 #endif
173 }
174 
175 
safe_write(int fd,const void * buf,size_t len)176 static size_t safe_write(int fd, const void *buf, size_t len)
177 {
178 	size_t ret = 0;
179 	while(ret < len)
180 	{
181 		ssize_t rem;
182 		if((rem=write(fd, (const char*)buf+ret, len-ret)) == -1)
183 		{
184 			if(errno == EINTR)
185 				continue;
186 			break;
187 		}
188 		ret += rem;
189 	}
190 	return ret;
191 }
192 
crash_catcher(int signum,siginfo_t * siginfo,void * context)193 static void crash_catcher(int signum, siginfo_t *siginfo, void *context)
194 {
195 	//ucontext_t *ucontext = (ucontext_t*)context;
196 	pid_t dbg_pid;
197 	int fd[2];
198 
199 	/* Make sure the effective uid is the real uid */
200 	if(getuid() != geteuid())
201 	{
202 		raise(signum);
203 		return;
204 	}
205 
206 	safe_write(STDERR_FILENO, fatal_err, sizeof(fatal_err)-1);
207 	if(pipe(fd) == -1)
208 	{
209 		safe_write(STDERR_FILENO, pipe_err, sizeof(pipe_err)-1);
210 		raise(signum);
211 		return;
212 	}
213 
214 	crash_info.signum = signum;
215 	crash_info.pid = getpid();
216 	crash_info.has_siginfo = !!siginfo;
217 	if(siginfo)
218 		crash_info.siginfo = *siginfo;
219 	if(cc_user_info)
220 		cc_user_info(crash_info.buf, crash_info.buf+sizeof(crash_info.buf));
221 
222 	/* Fork off to start a crash handler */
223 	switch((dbg_pid=fork()))
224 	{
225 		/* Error */
226 		case -1:
227 			safe_write(STDERR_FILENO, fork_err, sizeof(fork_err)-1);
228 			raise(signum);
229 			return;
230 
231 		case 0:
232 			dup2(fd[0], STDIN_FILENO);
233 			close(fd[0]);
234 			close(fd[1]);
235 
236 			execl(argv0, argv0, crash_switch, NULL);
237 
238 			safe_write(STDERR_FILENO, exec_err, sizeof(exec_err)-1);
239 			_exit(1);
240 
241 		default:
242 #ifdef __linux__
243 			prctl(PR_SET_PTRACER, dbg_pid, 0, 0, 0);
244 #endif
245 			safe_write(fd[1], &crash_info, sizeof(crash_info));
246 			close(fd[0]);
247 			close(fd[1]);
248 
249 			/* Wait; we'll be killed when gdb is done */
250 			do {
251 				int status;
252 				if(waitpid(dbg_pid, &status, 0) == dbg_pid &&
253 				   (WIFEXITED(status) || WIFSIGNALED(status)))
254 				{
255 					/* The debug process died before it could kill us */
256 					raise(signum);
257 					break;
258 				}
259 			} while(1);
260 	}
261 }
262 
crash_handler(const char * logfile)263 static void crash_handler(const char *logfile)
264 {
265 	const char *sigdesc = "";
266 	int i;
267 
268 	if(fread(&crash_info, sizeof(crash_info), 1, stdin) != 1)
269 	{
270 		fprintf(stderr, "!!! Failed to retrieve info from crashed process\n");
271 		exit(1);
272 	}
273 
274 	/* Get the signal description */
275 	for(i = 0;signals[i].name;++i)
276 	{
277 		if(signals[i].signum == crash_info.signum)
278 		{
279 			sigdesc = signals[i].name;
280 			break;
281 		}
282 	}
283 
284 	if(crash_info.has_siginfo)
285 	{
286 		switch(crash_info.signum)
287 		{
288 			case SIGSEGV:
289 				for(i = 0;sigsegv_codes[i].name;++i)
290 				{
291 					if(sigsegv_codes[i].code == crash_info.siginfo.si_code)
292 					{
293 						sigdesc = sigsegv_codes[i].name;
294 						break;
295 					}
296 				}
297 				break;
298 
299 			case SIGFPE:
300 				for(i = 0;sigfpe_codes[i].name;++i)
301 				{
302 					if(sigfpe_codes[i].code == crash_info.siginfo.si_code)
303 					{
304 						sigdesc = sigfpe_codes[i].name;
305 						break;
306 					}
307 				}
308 				break;
309 
310 			case SIGILL:
311 				for(i = 0;sigill_codes[i].name;++i)
312 				{
313 					if(sigill_codes[i].code == crash_info.siginfo.si_code)
314 					{
315 						sigdesc = sigill_codes[i].name;
316 						break;
317 					}
318 				}
319 				break;
320 
321 			case SIGBUS:
322 				for(i = 0;sigbus_codes[i].name;++i)
323 				{
324 					if(sigbus_codes[i].code == crash_info.siginfo.si_code)
325 					{
326 						sigdesc = sigbus_codes[i].name;
327 						break;
328 					}
329 				}
330 				break;
331 		}
332 	}
333 	fprintf(stderr, "%s (signal %i)\n", sigdesc, crash_info.signum);
334 	if(crash_info.has_siginfo)
335 		fprintf(stderr, "Address: %p\n", crash_info.siginfo.si_addr);
336 	fputc('\n', stderr);
337 
338 	if(logfile)
339 	{
340 		/* Create crash log file and redirect shell output to it */
341 		if(freopen(logfile, "wa", stdout) != stdout)
342 		{
343 			fprintf(stderr, "!!! Could not create %s following signal\n", logfile);
344 			exit(1);
345 		}
346 		fprintf(stderr, "Generating %s and killing process %d, please wait... ", logfile, crash_info.pid);
347 
348 		printf("*** Fatal Error ***\n"
349 		       "%s (signal %i)\n", sigdesc, crash_info.signum);
350 		if(crash_info.has_siginfo)
351 			printf("Address: %p\n", crash_info.siginfo.si_addr);
352 		fputc('\n', stdout);
353 		fflush(stdout);
354 	}
355 
356 	sys_info();
357 
358 	crash_info.buf[sizeof(crash_info.buf)-1] = '\0';
359 	printf("%s\n", crash_info.buf);
360 	fflush(stdout);
361 
362 	if(crash_info.pid > 0)
363 	{
364 		gdb_info(crash_info.pid);
365 		kill(crash_info.pid, SIGKILL);
366 	}
367 
368 	if(logfile)
369 	{
370 		const char *str;
371 		char buf[512];
372 
373 		if((str=getenv("KDE_FULL_SESSION")) && strcmp(str, "true") == 0)
374 			snprintf(buf, sizeof(buf), "kdialog --title \"Very Fatal Error\" --textbox \"%s\" 800 600", logfile);
375 		else if((str=getenv("GNOME_DESKTOP_SESSION_ID")) && str[0] != '\0')
376 			snprintf(buf, sizeof(buf), "gxmessage -buttons \"Okay:0\" -geometry 800x600 -title \"Very Fatal Error\" -center -file \"%s\"", logfile);
377 		else
378 			snprintf(buf, sizeof(buf), "xmessage -buttons \"Okay:0\" -center -file \"%s\"", logfile);
379 
380 		system(buf);
381 	}
382 	exit(0);
383 }
384 
cc_install_handlers(int argc,char ** argv,int num_signals,int * signals,const char * logfile,int (* user_info)(char *,char *))385 int cc_install_handlers(int argc, char **argv, int num_signals, int *signals, const char *logfile, int (*user_info)(char*, char*))
386 {
387 	struct sigaction sa;
388 	stack_t altss;
389 	int retval;
390 
391 	if(argc == 2 && strcmp(argv[1], crash_switch) == 0)
392 		crash_handler(logfile);
393 
394 	cc_user_info = user_info;
395 
396 	if(argv[0][0] == '/')
397 		snprintf(argv0, sizeof(argv0), "%s", argv[0]);
398 	else
399 	{
400 		getcwd(argv0, sizeof(argv0));
401 		retval = strlen(argv0);
402 		snprintf(argv0+retval, sizeof(argv0)-retval, "/%s", argv[0]);
403 	}
404 
405 	/* Set an alternate signal stack so SIGSEGVs caused by stack overflows
406 	 * still run */
407 	altss.ss_sp = altstack;
408 	altss.ss_flags = 0;
409 	altss.ss_size = sizeof(altstack);
410 	sigaltstack(&altss, NULL);
411 
412 	memset(&sa, 0, sizeof(sa));
413 	sa.sa_sigaction = crash_catcher;
414 	sa.sa_flags = SA_RESETHAND | SA_NODEFER | SA_SIGINFO | SA_ONSTACK;
415 	sigemptyset(&sa.sa_mask);
416 
417 	retval = 0;
418 	while(num_signals--)
419 	{
420 		if((*signals != SIGSEGV && *signals != SIGILL && *signals != SIGFPE &&
421 		    *signals != SIGBUS) || sigaction(*signals, &sa, NULL) == -1)
422 		{
423 			*signals = 0;
424 			retval = -1;
425 		}
426 		++signals;
427 	}
428 	return retval;
429 }
430