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 "bckeyboard.h"
35 #include <sys/ioctl.h>
36 #include <sys/prctl.h>
37 #include <sys/types.h>
39 BC_Signals* BC_Signals::global_signals = 0;
40 static int signal_done = 0;
41 static int table_id = 0;
43 static bc_locktrace_t* new_bc_locktrace(void *ptr,
47 bc_locktrace_t *result = (bc_locktrace_t*)malloc(sizeof(bc_locktrace_t));
49 result->title = title;
50 result->location = location;
52 result->id = table_id++;
53 result->tid = pthread_self();
58 static struct sigaction old_segv = {0, }, old_intr = {0, };
59 static void handle_dump(int n, siginfo_t * info, void *sc);
61 const char *BC_Signals::trap_path = 0;
62 void *BC_Signals::trap_data = 0;
63 void (*BC_Signals::trap_hook)(FILE *fp, void *data) = 0;
64 bool BC_Signals::trap_sigsegv = false;
65 bool BC_Signals::trap_sigintr = false;
67 static void uncatch_sig(int sig, struct sigaction &old)
70 sigaction(sig, &old, &act);
74 static void catch_sig(int sig, struct sigaction &old)
77 memset(&act, 0, sizeof(act));
78 act.sa_sigaction = handle_dump;
79 act.sa_flags = SA_SIGINFO;
80 sigaction(sig, &act, (!old.sa_handler ? &old : 0));
83 static void uncatch_intr() { uncatch_sig(SIGINT, old_intr); }
84 static void catch_intr() { catch_sig(SIGINT, old_intr); }
85 static void uncatch_segv() { uncatch_sig(SIGSEGV, old_segv); }
86 static void catch_segv() { catch_sig(SIGSEGV, old_segv); }
88 void BC_Signals::set_trap_path(const char *path)
93 void BC_Signals::set_trap_hook(void (*hook)(FILE *fp, void *vp), void *data)
99 void BC_Signals::set_catch_segv(bool v) {
100 if( v == trap_sigsegv ) return;
101 if( v ) catch_segv();
106 void BC_Signals::set_catch_intr(bool v) {
107 if( v == trap_sigintr ) return;
108 if( v ) catch_intr();
117 const char *location;
120 static bc_buffertrace_t* new_bc_buffertrace(int size, void *ptr, const char *location)
122 bc_buffertrace_t *result = (bc_buffertrace_t*)malloc(sizeof(bc_buffertrace_t));
125 result->location = location;
129 static void bc_copy_textfile(FILE *ofp, const char *fmt,...)
131 va_list ap; va_start(ap, fmt);
132 char bfr[BCTEXTLEN]; vsnprintf(bfr, sizeof(bfr), fmt, ap);
134 FILE *ifp = fopen(bfr,"r");
136 while( fgets(bfr,sizeof(bfr),ifp) ) fputs(bfr,ofp);
141 // Need our own table to avoid recursion with the memory manager
147 // This points to the next value to replace if the table wraps around
151 static void* append_table(bc_table_t *table, void *ptr)
153 if(table->allocation <= table->size)
155 if(table->allocation)
157 int new_allocation = table->allocation * 2;
158 void **new_values = (void**)calloc(new_allocation, sizeof(void*));
159 memcpy(new_values, table->values, sizeof(void*) * table->size);
161 table->values = new_values;
162 table->allocation = new_allocation;
166 table->allocation = 4096;
167 table->values = (void**)calloc(table->allocation, sizeof(void*));
171 table->values[table->size++] = ptr;
175 // Replace item in table pointed to by current_value and advance
177 static void* overwrite_table(bc_table_t *table, void *ptr)
179 free(table->values[table->current_value]);
180 table->values[table->current_value++] = ptr;
181 if(table->current_value >= table->size) table->current_value = 0;
185 static void clear_table(bc_table_t *table, int delete_objects)
189 for(int i = 0; i < table->size; i++)
191 free(table->values[i]);
197 static void clear_table_entry(bc_table_t *table, int number, int delete_object)
199 if(delete_object) free(table->values[number]);
200 for(int i = number; i < table->size - 1; i++)
202 table->values[i] = table->values[i + 1];
207 // Table of functions currently running.
208 static bc_table_t execution_table = { 0, 0, 0, 0 };
210 // Table of locked positions
211 static bc_table_t lock_table = { 0, 0, 0, 0 };
214 static bc_table_t memory_table = { 0, 0, 0, 0 };
216 static bc_table_t temp_files = { 0, 0, 0, 0 };
218 // Can't use Mutex because it would be recursive
219 static pthread_mutex_t *lock = 0;
220 static pthread_mutex_t *handler_lock = 0;
221 // incase lock set after task ends
222 static pthread_t last_lock_thread = 0;
223 static const char *last_lock_title = 0;
224 static const char *last_lock_location = 0;
225 // Don't trace memory until this is true to avoid initialization
226 static int trace_memory = 0;
229 static const char* signal_titles[] =
249 void BC_Signals::dump_stack(FILE *fp)
252 int total = backtrace (buffer, 256);
253 char **result = backtrace_symbols (buffer, total);
254 fprintf(fp, "BC_Signals::dump_stack\n");
255 for(int i = 0; i < total; i++)
257 fprintf(fp, "%s\n", result[i]);
262 void BC_Signals::kill_subs()
264 // List /proc directory
266 struct dirent64 *new_filename;
268 char path[BCTEXTLEN];
269 char string[BCTEXTLEN];
271 dirstream = opendir("/proc");
272 if(!dirstream) return;
274 while( (new_filename = readdir64(dirstream)) != 0 )
276 // All digits are numbers
277 char *ptr = new_filename->d_name;
281 if(*ptr == '.' || isalpha(*ptr++))
288 if(got_alpha) continue;
290 // Must be a directory
291 sprintf(path, "/proc/%s", new_filename->d_name);
292 if(!stat(path, &ostat))
294 if(S_ISDIR(ostat.st_mode))
297 strcat(path, "/stat");
298 //printf("kill_subs %d %s\n", __LINE__, path);
299 FILE *fd = fopen(path, "r");
301 // Must search forwards because the file is 0 length
307 //printf("kill_subs %d %d\n", __LINE__, c);
310 // Search for 2 spaces
312 while(!feof(fd) && spaces < 2)
319 // Read in parent process
332 // printf("kill_subs %d process=%d getpid=%d parent_process=%d\n",
334 // atoi(new_filename->d_name),
337 int parent_process = atoi(string);
338 int child_process = atoi(new_filename->d_name);
340 // Kill if we're the parent
341 if(getpid() == parent_process)
343 //printf("kill_subs %d: process=%d\n", __LINE__, atoi(new_filename->d_name));
344 kill(child_process, SIGKILL);
356 static void signal_entry(int signum)
358 signal(signum, SIG_DFL);
360 pthread_mutex_lock(handler_lock);
363 pthread_mutex_unlock(handler_lock);
368 pthread_mutex_unlock(handler_lock);
371 printf("signal_entry: got %s my pid=%d execution table size=%d:\n",
372 signal_titles[signum],
374 execution_table.size);
376 BC_Signals::kill_subs();
377 BC_Signals::dump_traces();
378 BC_Signals::dump_locks();
379 BC_Signals::dump_buffers();
380 BC_Signals::delete_temps();
382 // Call user defined signal handler
383 BC_Signals::global_signals->signal_handler(signum);
388 static void signal_entry_recoverable(int signum)
390 printf("signal_entry_recoverable: got %s my pid=%d\n",
391 signal_titles[signum],
395 // used to terminate child processes when program terminates
396 static void handle_exit(int signum)
398 //printf("child %d exit\n", getpid());
402 void BC_Signals::set_sighup_exit(int enable)
405 // causes SIGHUP to be generated when parent dies
406 signal(SIGHUP, handle_exit);
407 prctl(PR_SET_PDEATHSIG, SIGHUP, 0,0,0);
408 // prevents ^C from signalling child when attached to gdb
410 if( isatty(0) ) ioctl(0, TIOCNOTTY, 0);
413 signal(SIGHUP, signal_entry);
414 prctl(PR_SET_PDEATHSIG, 0,0,0,0);
418 BC_Signals::BC_Signals()
422 void BC_Signals::dump_traces(FILE *fp)
425 if(execution_table.size)
427 for(int i = execution_table.current_value; i < execution_table.size; i++)
428 fprintf(fp," %s\n", (char*)execution_table.values[i]);
429 for(int i = 0; i < execution_table.current_value; i++)
430 fprintf(fp," %s\n", (char*)execution_table.values[i]);
435 void BC_Signals::dump_locks(FILE *fp)
439 fprintf(fp,"signal_entry: lock table size=%d\n", lock_table.size);
440 for(int i = 0; i < lock_table.size; i++)
442 bc_locktrace_t *table = (bc_locktrace_t*)lock_table.values[i];
443 fprintf(fp," %p %s %s %p%s\n", table->ptr,
444 table->title, table->location, (void*)table->tid,
445 table->is_owner ? " *" : "");
450 void BC_Signals::dump_buffers(FILE *fp)
453 pthread_mutex_lock(lock);
455 fprintf(fp,"BC_Signals::dump_buffers: buffer table size=%d\n", memory_table.size);
456 for(int i = 0; i < memory_table.size; i++)
458 bc_buffertrace_t *entry = (bc_buffertrace_t*)memory_table.values[i];
459 fprintf(fp," %d %p %s\n", entry->size, entry->ptr, entry->location);
461 pthread_mutex_unlock(lock);
465 void BC_Signals::delete_temps()
467 pthread_mutex_lock(lock);
468 if(temp_files.size) printf("BC_Signals::delete_temps: deleting %d temp files\n", temp_files.size);
469 for(int i = 0; i < temp_files.size; i++)
471 printf(" %s\n", (char*)temp_files.values[i]);
472 remove((char*)temp_files.values[i]);
474 pthread_mutex_unlock(lock);
477 void BC_Signals::reset_locks()
479 pthread_mutex_unlock(lock);
482 void BC_Signals::set_temp(char *string)
484 char *new_string = strdup(string);
485 append_table(&temp_files, new_string);
488 void BC_Signals::unset_temp(char *string)
490 for(int i = 0; i < temp_files.size; i++)
492 if(!strcmp((char*)temp_files.values[i], string))
494 clear_table_entry(&temp_files, i, 1);
501 int BC_Signals::x_error_handler(Display *display, XErrorEvent *event)
504 XGetErrorText(event->display, event->error_code, string, 1024);
505 fprintf(stderr, "BC_Signals::x_error_handler: error_code=%d opcode=%d,%d %s\n",
506 event->error_code, event->request_code, event->minor_code, string);
511 void BC_Signals::initialize()
513 BC_Signals::global_signals = this;
514 lock = (pthread_mutex_t*)calloc(1, sizeof(pthread_mutex_t));
515 handler_lock = (pthread_mutex_t*)calloc(1, sizeof(pthread_mutex_t));
516 pthread_mutex_init(lock, 0);
517 pthread_mutex_init(handler_lock, 0);
518 old_err_handler = XSetErrorHandler(x_error_handler);
522 void BC_Signals::terminate()
524 BC_Signals::global_signals = 0;
525 uncatch_segv(); uncatch_intr();
526 signal(SIGHUP, SIG_DFL);
527 signal(SIGINT, SIG_DFL);
528 signal(SIGQUIT, SIG_DFL);
529 signal(SIGTERM, SIG_DFL);
530 signal(SIGFPE, SIG_DFL);
531 signal(SIGPIPE, SIG_DFL);
532 signal(SIGUSR2, SIG_DFL);
533 XSetErrorHandler(old_err_handler);
536 // callable from debugger
540 BC_Signals::dump_traces();
541 BC_Signals::dump_locks();
542 BC_Signals::dump_buffers();
546 void BC_Signals::signal_dump(int signum)
548 BC_KeyboardHandler::kill_grabs();
550 signal(SIGUSR2, signal_dump);
558 void BC_Signals::initialize2()
560 signal(SIGHUP, signal_entry);
561 signal(SIGINT, signal_entry);
562 signal(SIGQUIT, signal_entry);
563 // SIGKILL cannot be stopped
564 // signal(SIGKILL, signal_entry);
566 signal(SIGTERM, signal_entry);
567 signal(SIGFPE, signal_entry);
568 signal(SIGPIPE, signal_entry_recoverable);
569 signal(SIGUSR2, signal_dump);
573 void BC_Signals::signal_handler(int signum)
575 printf("BC_Signals::signal_handler\n");
579 const char* BC_Signals::sig_to_str(int number)
581 return signal_titles[number];
584 #define TOTAL_TRACES 16
586 void BC_Signals::new_trace(const char *text)
588 if(!global_signals) return;
589 pthread_mutex_lock(lock);
592 if(execution_table.size >= TOTAL_TRACES)
594 overwrite_table(&execution_table, strdup(text));
595 // clear_table(&execution_table, 1);
599 append_table(&execution_table, strdup(text));
601 pthread_mutex_unlock(lock);
604 void BC_Signals::new_trace(const char *file, const char *function, int line)
606 char string[BCTEXTLEN];
607 snprintf(string, BCTEXTLEN, "%s: %s: %d", file, function, line);
611 void BC_Signals::delete_traces()
613 if(!global_signals) return;
614 pthread_mutex_lock(lock);
615 clear_table(&execution_table, 0);
616 pthread_mutex_unlock(lock);
619 // no canceling with lock held
620 void BC_Signals::lock_locks(const char *s)
622 pthread_mutex_lock(lock);
623 last_lock_thread = pthread_self();
625 last_lock_location = 0;
628 void BC_Signals::unlock_locks()
630 pthread_mutex_unlock(lock);
633 #define TOTAL_LOCKS 256
635 int BC_Signals::set_lock(void *ptr,
637 const char *location)
639 if(!global_signals) return 0;
640 bc_locktrace_t *table = 0;
643 pthread_mutex_lock(lock);
644 last_lock_thread = pthread_self();
645 last_lock_title = title;
646 last_lock_location = location;
647 if(lock_table.size >= TOTAL_LOCKS)
648 clear_table(&lock_table, 0);
650 // Put new lock entry
651 table = new_bc_locktrace(ptr, title, location);
652 append_table(&lock_table, table);
653 id_return = table->id;
655 pthread_mutex_unlock(lock);
659 void BC_Signals::set_lock2(int table_id)
661 if(!global_signals) return;
663 bc_locktrace_t *table = 0;
664 pthread_mutex_lock(lock);
665 for(int i = lock_table.size - 1; i >= 0; i--)
667 table = (bc_locktrace_t*)lock_table.values[i];
668 // Got it. Hasn't been unlocked/deleted yet.
669 if(table->id == table_id)
672 table->tid = pthread_self();
673 pthread_mutex_unlock(lock);
677 pthread_mutex_unlock(lock);
680 void BC_Signals::unset_lock2(int table_id)
682 if(!global_signals) return;
684 bc_locktrace_t *table = 0;
685 pthread_mutex_lock(lock);
686 for(int i = lock_table.size - 1; i >= 0; i--)
688 table = (bc_locktrace_t*)lock_table.values[i];
689 if(table->id == table_id)
691 clear_table_entry(&lock_table, i, 1);
695 pthread_mutex_unlock(lock);
698 void BC_Signals::unset_lock(void *ptr)
700 if(!global_signals) return;
702 bc_locktrace_t *table = 0;
703 pthread_mutex_lock(lock);
705 // Take off currently held entry
706 for(int i = 0; i < lock_table.size; i++)
708 table = (bc_locktrace_t*)lock_table.values[i];
709 if(table->ptr == ptr)
713 clear_table_entry(&lock_table, i, 1);
719 pthread_mutex_unlock(lock);
723 void BC_Signals::unset_all_locks(void *ptr)
725 if(!global_signals) return;
726 pthread_mutex_lock(lock);
727 // Take off previous lock entry
728 for(int i = 0; i < lock_table.size; )
730 bc_locktrace_t *table = (bc_locktrace_t*)lock_table.values[i];
731 if(table->ptr == ptr)
733 clear_table_entry(&lock_table, i, 1);
738 pthread_mutex_unlock(lock);
741 void BC_Signals::clear_locks_tid(pthread_t tid)
743 if(!global_signals) return;
744 pthread_mutex_lock(lock);
745 // Take off previous lock entry
746 for(int i = 0; i < lock_table.size; )
748 bc_locktrace_t *table = (bc_locktrace_t*)lock_table.values[i];
749 if(table->tid == tid)
751 clear_table_entry(&lock_table, i, 1);
756 pthread_mutex_unlock(lock);
760 void BC_Signals::enable_memory()
765 void BC_Signals::disable_memory()
771 void BC_Signals::set_buffer(int size, void *ptr, const char* location)
773 if(!global_signals) return;
774 if(!trace_memory) return;
776 //printf("BC_Signals::set_buffer %p %s\n", ptr, location);
777 pthread_mutex_lock(lock);
778 append_table(&memory_table, new_bc_buffertrace(size, ptr, location));
779 pthread_mutex_unlock(lock);
782 int BC_Signals::unset_buffer(void *ptr)
784 if(!global_signals) return 0;
785 if(!trace_memory) return 0;
788 pthread_mutex_lock(lock);
789 for(int i = 0; i < memory_table.size; i++)
791 if(((bc_buffertrace_t*)memory_table.values[i])->ptr == ptr)
793 //printf("BC_Signals::unset_buffer %p\n", ptr);
794 clear_table_entry(&memory_table, i, 1);
800 pthread_mutex_unlock(lock);
801 // fprintf(stderr, "BC_Signals::unset_buffer buffer %p not found.\n", ptr);
806 #include <ucontext.h>
807 #include <sys/wait.h>
821 static void handle_dump(int n, siginfo_t * info, void *sc)
823 uncatch_segv(); uncatch_intr();
824 signal(SIGSEGV, SIG_DFL);
825 signal(SIGINT, SIG_DFL);
826 // gotta be root, or the dump is worthless
828 if( uid != 0 ) return;
829 ucontext_t *uc = (ucontext_t *)sc;
830 int pid = getpid(), tid = gettid();
831 struct sigcontext *c = (struct sigcontext *)&uc->uc_mcontext;
832 fprintf(stderr,"** %s at %p in pid %d, tid %d\n",
833 n==SIGSEGV? "segv" : n==SIGINT? "intr" : "trap",
834 (void*)c->IP, pid, tid);
837 if( BC_Signals::trap_path ) {
838 snprintf(fn, sizeof(fn), BC_Signals::trap_path, pid);
842 fprintf(stderr,"writing debug data to %s\n", fn);
843 fprintf(fp,"** %s at %p in pid %d, tid %d\n",
844 n==SIGSEGV? "segv" : n==SIGINT? "intr" : "trap",
845 (void*)c->IP, pid, tid);
848 strcpy(fn, "stdout");
852 fprintf(fp,"created on %s", ctime(&t));
853 struct passwd *pw = getpwuid(uid);
855 fprintf(fp," by %d:%d %s(%s)\n",
856 pw->pw_uid, pw->pw_gid, pw->pw_name, pw->pw_gecos);
858 fprintf(fp,"\nTHREADS:\n"); Thread::dump_threads(fp);
859 fprintf(fp,"\nTRACES:\n"); BC_Signals::dump_traces(fp);
860 fprintf(fp,"\nLOCKS:\n"); BC_Signals::dump_locks(fp);
861 fprintf(fp,"\nBUFFERS:\n"); BC_Signals::dump_buffers(fp);
862 if( BC_Signals::trap_hook ) {
863 fprintf(fp,"\nMAIN HOOK:\n");
864 BC_Signals::trap_hook(fp, BC_Signals::trap_data);
866 fprintf(fp,"\nVERSION:\n"); bc_copy_textfile(fp,"/proc/version");
867 fprintf(fp,"\nMEMINFO:\n"); bc_copy_textfile(fp,"/proc/meminfo");
868 fprintf(fp,"\nMAPS:\n"); bc_copy_textfile(fp,"/proc/%d/maps",pid);
870 if( fp != stdout ) fclose(fp);
871 char cmd[1024], *cp = cmd;
872 cp += sprintf(cp, "exec gdb /proc/%d/exe -p %d --batch --quiet "
873 "-ex \"thread apply all info registers\" "
874 "-ex \"thread apply all bt full\" "
875 "-ex \"quit\"", pid, pid);
877 cp += sprintf(cp," >> \"%s\"", fn);
878 cp += sprintf(cp," 2>&1");
879 //printf("handle_dump:: pid=%d, cmd='%s' fn='%s'\n",pid,cmd,fn);
882 fprintf(stderr,"** can't start gdb, dump abondoned\n");
887 fprintf(stderr,"** dump complete\n");
890 char *const argv[4] = { (char*) "/bin/sh", (char*) "-c", cmd, 0 };
891 execvp(argv[0], &argv[0]);
900 // void* operator new(size_t size)
902 // //printf("new 1 %d\n", size);
903 // void *result = malloc(size);
904 // BUFFER(size, result, "new");
905 // //printf("new 2 %d\n", size);
909 // void* operator new[](size_t size)
911 // //printf("new [] 1 %d\n", size);
912 // void *result = malloc(size);
913 // BUFFER(size, result, "new []");
914 // //printf("new [] 2 %d\n", size);
918 // void operator delete(void *ptr)
920 // //printf("delete 1 %p\n", ptr);
922 // //printf("delete 2 %p\n", ptr);
926 // void operator delete[](void *ptr)
928 // //printf("delete [] 1 %p\n", ptr);
931 // //printf("delete [] 2 %p\n", ptr);