4 * Copyright (C) 1997-2014 Adam Williams <broadcast at earthling dot net>
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 #include "bcsignals.h"
23 #include "bcwindowbase.h"
24 #include "bccmodels.h"
25 #include "bckeyboard.h"
26 #include "bcresources.h"
39 #include <sys/ioctl.h>
40 #include <sys/prctl.h>
41 #include <sys/types.h>
43 BC_Signals* BC_Signals::global_signals = 0;
44 static int signal_done = 0;
46 static struct sigaction old_segv = {0, }, old_intr = {0, };
47 static void handle_dump(int n, siginfo_t * info, void *sc);
49 const char *BC_Signals::trap_path = 0;
50 void *BC_Signals::trap_data = 0;
51 void (*BC_Signals::trap_hook)(FILE *fp, void *data) = 0;
52 bool BC_Signals::trap_sigsegv = false;
53 bool BC_Signals::trap_sigintr = false;
55 static void uncatch_sig(int sig, struct sigaction &old)
58 sigaction(sig, &old, &act);
62 static void catch_sig(int sig, struct sigaction &old)
65 memset(&act, 0, sizeof(act));
66 act.sa_sigaction = handle_dump;
67 act.sa_flags = SA_SIGINFO;
68 sigaction(sig, &act, (!old.sa_handler ? &old : 0));
71 static void uncatch_intr() { uncatch_sig(SIGINT, old_intr); }
72 static void catch_intr() { catch_sig(SIGINT, old_intr); }
73 static void uncatch_segv() { uncatch_sig(SIGSEGV, old_segv); }
74 static void catch_segv() { catch_sig(SIGSEGV, old_segv); }
76 void BC_Signals::set_trap_path(const char *path)
81 void BC_Signals::set_trap_hook(void (*hook)(FILE *fp, void *vp), void *data)
87 void BC_Signals::set_catch_segv(bool v) {
88 if( v == trap_sigsegv ) return;
94 void BC_Signals::set_catch_intr(bool v) {
95 if( v == trap_sigintr ) return;
101 static void bc_copy_textfile(int lines, FILE *ofp, const char *fmt,...)
103 va_list ap; va_start(ap, fmt);
104 char bfr[BCTEXTLEN]; vsnprintf(bfr, sizeof(bfr), fmt, ap);
106 FILE *ifp = fopen(bfr,"r");
108 while( --lines >= 0 && fgets(bfr,sizeof(bfr),ifp) ) fputs(bfr,ofp);
112 static void bc_list_openfiles(int lines, FILE *ofp, const char *fmt,...)
114 va_list ap; va_start(ap, fmt);
115 char bfr[BCTEXTLEN]; vsnprintf(bfr, sizeof(bfr), fmt, ap);
117 DIR *dir = opendir(bfr);
119 struct dirent64 *dent;
120 while( --lines >= 0 && (dent = readdir64(dir)) ) {
121 const char *fn = dent->d_name;
122 fprintf(ofp, "%s", fn);
123 char path[BCTEXTLEN], link[BCTEXTLEN];
125 snprintf(path, sizeof(path), "%s/%s", bfr, fn);
126 if( !stat(path,&st) ) {
128 if( S_ISREG(st.st_mode) ) typ = ' ';
129 else if( S_ISDIR(st.st_mode) ) typ = 'd';
130 else if( S_ISBLK(st.st_mode) ) typ = 'b';
131 else if( S_ISCHR(st.st_mode) ) typ = 'c';
132 else if( S_ISFIFO(st.st_mode) ) typ = 'f';
133 else if( S_ISLNK(st.st_mode) ) typ = 'l';
134 else if( S_ISSOCK(st.st_mode) ) typ = 's';
135 if( typ ) fprintf(ofp, "\t%c", typ);
136 fprintf(ofp, "\tsize %jd", st.st_size);
137 int len = readlink(path, link, sizeof(link)-1);
140 fprintf(ofp, "\t-> %s", link);
143 snprintf(path, sizeof(path), "%sinfo/%s", bfr, fn);
144 FILE *fp = fopen(path,"r"); int64_t pos;
146 while( fgets(link, sizeof(link), fp) ) {
147 if( sscanf(link, "pos:%jd", &pos) == 1 ) {
148 fprintf(ofp, "\tpos: %jd", pos);
159 // Can't use Mutex because it would be recursive
160 static pthread_mutex_t *handler_lock = 0;
163 static const char* signal_titles[] =
183 void BC_Signals::dump_stack(FILE *fp)
186 int total = backtrace (buffer, 256);
187 char **result = backtrace_symbols (buffer, total);
188 fprintf(fp, "BC_Signals::dump_stack\n");
189 for(int i = 0; i < total; i++)
191 fprintf(fp, "%s\n", result[i]);
196 void BC_Signals::kill_subs()
198 // List /proc directory
199 struct dirent64 *new_filename;
201 char path[BCTEXTLEN], string[BCTEXTLEN];
202 DIR *dirstream = opendir("/proc");
203 if( !dirstream ) return;
204 pid_t ppid = getpid();
206 while( (new_filename = readdir64(dirstream)) != 0 ) {
207 char *ptr = new_filename->d_name;
208 while( *ptr && *ptr != '.' && !isalpha(*ptr) ) ++ptr;
209 // All digits are numbers
212 // Must be a directory
213 sprintf(path, "/proc/%s", new_filename->d_name);
214 if( stat(path, &ostat) ) continue;
215 if( !S_ISDIR(ostat.st_mode) ) continue;
216 strcat(path, "/stat");
217 FILE *fd = fopen(path, "r");
219 while( !feof(fd) && fgetc(fd)!=')' );
220 //printf("kill_subs %d %d\n", __LINE__, c);
221 for( int sp=2; !feof(fd) && sp>0; )
222 if( fgetc(fd) == ' ' ) --sp;
223 // Read in parent process
224 for( ptr=string; !feof(fd) && (*ptr=fgetc(fd))!=' '; ++ptr );
225 if( (*ptr=fgetc(fd)) == ' ' ) break;
228 // printf("kill_subs %d process=%d getpid=%d parent_process=%d\n",
229 // __LINE__, atoi(new_filename->d_name), getpid(), atoi(string));
230 int parent_process = atoi(string);
231 // Kill if we're the parent
232 if( ppid == parent_process ) {
233 int child_process = atoi(new_filename->d_name);
234 //printf("kill_subs %d: process=%d\n", __LINE__, atoi(new_filename->d_name));
235 kill(child_process, SIGKILL);
241 static void signal_entry(int signum)
243 signal(signum, SIG_DFL);
245 pthread_mutex_lock(handler_lock);
246 int done = signal_done;
248 pthread_mutex_unlock(handler_lock);
251 printf("signal_entry: got %s my pid=%d execution table size=%d:\n",
252 signal_titles[signum], getpid(), execution_table.size);
254 BC_Signals::kill_subs();
255 BC_Trace::dump_traces();
256 BC_Trace::dump_locks();
257 BC_Trace::dump_buffers();
258 BC_Trace::delete_temps();
260 // Call user defined signal handler
261 BC_Signals::global_signals->signal_handler(signum);
266 static void signal_entry_recoverable(int signum)
268 printf("signal_entry_recoverable: got %s my pid=%d\n",
269 signal_titles[signum],
273 // used to terminate child processes when program terminates
274 static void handle_exit(int signum)
276 //printf("child %d exit\n", getpid());
280 void BC_Signals::set_sighup_exit(int enable)
283 // causes SIGHUP to be generated when parent dies
284 signal(SIGHUP, handle_exit);
285 prctl(PR_SET_PDEATHSIG, SIGHUP, 0,0,0);
286 // prevents ^C from signalling child when attached to gdb
288 if( isatty(0) ) ioctl(0, TIOCNOTTY, 0);
291 signal(SIGHUP, signal_entry);
292 prctl(PR_SET_PDEATHSIG, 0,0,0,0);
296 BC_Signals::BC_Signals()
299 BC_Signals::~BC_Signals()
301 BC_CModels::bcxfer_stop_slicers();
305 int BC_Signals::x_error_handler(Display *display, XErrorEvent *event)
308 XGetErrorText(event->display, event->error_code, string, 1024);
309 fprintf(stderr, "BC_Signals::x_error_handler: error_code=%d opcode=%d,%d id=0x%jx %s\n",
310 event->error_code, event->request_code, event->minor_code,
311 (int64_t)event->resourceid, string);
316 void BC_Signals::initialize(const char *trap_path)
318 BC_Signals::global_signals = this;
319 BC_Trace::global_trace = this;
320 set_trap_path(trap_path);
321 handler_lock = (pthread_mutex_t*)calloc(1, sizeof(pthread_mutex_t));
322 pthread_mutex_init(handler_lock, 0);
323 old_err_handler = XSetErrorHandler(x_error_handler);
327 void BC_Signals::terminate()
329 BC_Signals::global_signals = 0;
330 BC_Trace::global_trace = 0;
331 uncatch_segv(); uncatch_intr();
332 signal(SIGHUP, SIG_DFL);
333 signal(SIGINT, SIG_DFL);
334 signal(SIGQUIT, SIG_DFL);
335 signal(SIGTERM, SIG_DFL);
336 signal(SIGFPE, SIG_DFL);
337 signal(SIGPIPE, SIG_DFL);
338 signal(SIGUSR2, SIG_DFL);
339 XSetErrorHandler(old_err_handler);
343 void BC_Signals::signal_dump(int signum)
345 BC_KeyboardHandler::kill_grabs();
347 signal(SIGUSR2, signal_dump);
355 void BC_Signals::initialize2()
357 signal(SIGHUP, signal_entry);
358 signal(SIGINT, signal_entry);
359 signal(SIGQUIT, signal_entry);
360 // SIGKILL cannot be stopped
361 // signal(SIGKILL, signal_entry);
363 signal(SIGTERM, signal_entry);
364 signal(SIGFPE, signal_entry);
365 signal(SIGPIPE, signal_entry_recoverable);
366 signal(SIGUSR2, signal_dump);
370 void BC_Signals::signal_handler(int signum)
372 printf("BC_Signals::signal_handler\n");
376 const char* BC_Signals::sig_to_str(int number)
378 return signal_titles[number];
382 #include <ucontext.h>
383 #include <sys/wait.h>
388 #define sigregs_t sigcontext
393 #define sigregs_t sigcontext
396 #if __powerpc__ || __powerpc64__ || __powerpc64le__
397 #include <asm/ptrace.h>
399 #define sigregs_t pt_regs
407 static void handle_dump(int n, siginfo_t * info, void *sc)
409 uncatch_segv(); uncatch_intr();
410 signal(SIGSEGV, SIG_DFL);
411 signal(SIGINT, SIG_DFL);
412 // gotta be root, or the dump is worthless
414 // it is not necessary to be root if ptrace is allowed via:
415 // echo 0 > /proc/sys/kernel/yama/ptrace_scope (usually set to 1)
416 // if( uid != 0 ) return;
417 ucontext_t *uc = (ucontext_t *)sc;
418 int pid = getpid(), tid = gettid();
419 struct sigregs_t *c = (struct sigregs_t *)&uc->uc_mcontext;
420 uint8_t *ip = (uint8_t *)c->IP;
421 fprintf(stderr,"** %s at %p in pid %d, tid %d\n",
422 n==SIGSEGV? "segv" : n==SIGINT? "intr" : "trap",
423 (void*)ip, pid, tid);
426 if( BC_Signals::trap_path ) {
427 snprintf(fn, sizeof(fn), BC_Signals::trap_path, pid);
431 fprintf(stderr,"writing debug data to %s\n", fn);
432 fprintf(fp,"** %s at %p in pid %d, tid %d\n",
433 n==SIGSEGV? "segv" : n==SIGINT? "intr" : "trap",
434 (void*)c->IP, pid, tid);
437 strcpy(fn, "stdout");
441 fprintf(fp,"created on %s", ctime(&t));
442 struct passwd *pw = getpwuid(uid);
444 fprintf(fp," by %d:%d %s(%s)\n",
445 pw->pw_uid, pw->pw_gid, pw->pw_name, pw->pw_gecos);
447 fprintf(fp,"\nCPUS: %d\n", BC_Resources::get_machine_cpus());
448 fprintf(fp,"\nCPUINFO:\n"); bc_copy_textfile(32, fp,"/proc/cpuinfo");
449 fprintf(fp,"\nTHREADS:\n"); BC_Trace::dump_threads(fp);
450 fprintf(fp,"\nTRACES:\n"); BC_Trace::dump_traces(fp);
451 fprintf(fp,"\nLOCKS:\n"); BC_Trace::dump_locks(fp);
452 fprintf(fp,"\nBUFFERS:\n"); BC_Trace::dump_buffers(fp);
453 fprintf(fp,"\nSHMMEM:\n"); BC_Trace::dump_shm_stats(fp);
454 if( BC_Signals::trap_hook ) {
455 fprintf(fp,"\nMAIN HOOK:\n");
456 BC_Signals::trap_hook(fp, BC_Signals::trap_data);
458 fprintf(fp,"\nVERSION:\n"); bc_copy_textfile(INT_MAX, fp,"/proc/version");
459 fprintf(fp,"\nMEMINFO:\n"); bc_copy_textfile(INT_MAX, fp,"/proc/meminfo");
460 fprintf(fp,"\nSTATUS:\n"); bc_copy_textfile(INT_MAX, fp,"/proc/%d/status",pid);
461 fprintf(fp,"\nFD:\n"); bc_list_openfiles(INT_MAX, fp,"/proc/%d/fd", pid);
462 fprintf(fp,"\nMAPS:\n"); bc_copy_textfile(INT_MAX, fp,"/proc/%d/maps",pid);
464 if( tid > 0 && tid != pid )
465 sprintf(proc_mem,"/proc/%d/task/%d/mem",pid,tid);
467 sprintf(proc_mem,"/proc/%d/mem",pid);
468 int pfd = open(proc_mem,O_RDONLY);
470 fprintf(fp,"\nCODE:\n");
471 for( int i=-32; i<32; ) {
472 uint8_t v; void *vp = (void *)(ip + i);
473 if( !(i & 7) ) fprintf(fp,"%p: ", vp);
474 if( pread(pfd,&v,sizeof(v),(off_t)vp) != sizeof(v) ) break;
475 fprintf(fp,"%c%02x", !i ? '>' : ' ', v);
476 if( !(++i & 7) ) fprintf(fp,"\n");
482 fprintf(fp,"err opening: %s, %m\n", proc_mem);
485 if( fp != stdout ) fclose(fp);
486 char cmd[1024], *cp = cmd;
487 cp += sprintf(cp, "exec gdb /proc/%d/exe -p %d --batch --quiet "
488 "-ex \"thread apply all info registers\" "
489 "-ex \"thread apply all bt full\" "
490 "-ex \"quit\"", pid, pid);
492 cp += sprintf(cp," >> \"%s\"", fn);
493 cp += sprintf(cp," 2>&1");
494 //printf("handle_dump:: pid=%d, cmd='%s' fn='%s'\n",pid,cmd,fn);
497 fprintf(stderr,"** can't start gdb, dump abondoned\n");
502 fprintf(stderr,"** dump complete\n");
505 char *const argv[4] = { (char*) "/bin/sh", (char*) "-c", cmd, 0 };
506 execvp(argv[0], &argv[0]);