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"
25 #include "bcresources.h"
36 #include <sys/ioctl.h>
37 #include <sys/prctl.h>
38 #include <sys/types.h>
40 BC_Signals* BC_Signals::global_signals = 0;
41 static int signal_done = 0;
42 static int table_id = 0;
44 static bc_locktrace_t* new_bc_locktrace(void *ptr,
48 bc_locktrace_t *result = (bc_locktrace_t*)malloc(sizeof(bc_locktrace_t));
50 result->title = title;
51 result->location = location;
53 result->id = table_id++;
54 result->tid = pthread_self();
59 static struct sigaction old_segv = {0, }, old_intr = {0, };
60 static void handle_dump(int n, siginfo_t * info, void *sc);
62 const char *BC_Signals::trap_path = 0;
63 void *BC_Signals::trap_data = 0;
64 void (*BC_Signals::trap_hook)(FILE *fp, void *data) = 0;
65 bool BC_Signals::trap_sigsegv = false;
66 bool BC_Signals::trap_sigintr = false;
68 static void uncatch_sig(int sig, struct sigaction &old)
71 sigaction(sig, &old, &act);
75 static void catch_sig(int sig, struct sigaction &old)
78 memset(&act, 0, sizeof(act));
79 act.sa_sigaction = handle_dump;
80 act.sa_flags = SA_SIGINFO;
81 sigaction(sig, &act, (!old.sa_handler ? &old : 0));
84 static void uncatch_intr() { uncatch_sig(SIGINT, old_intr); }
85 static void catch_intr() { catch_sig(SIGINT, old_intr); }
86 static void uncatch_segv() { uncatch_sig(SIGSEGV, old_segv); }
87 static void catch_segv() { catch_sig(SIGSEGV, old_segv); }
89 void BC_Signals::set_trap_path(const char *path)
94 void BC_Signals::set_trap_hook(void (*hook)(FILE *fp, void *vp), void *data)
100 void BC_Signals::set_catch_segv(bool v) {
101 if( v == trap_sigsegv ) return;
102 if( v ) catch_segv();
107 void BC_Signals::set_catch_intr(bool v) {
108 if( v == trap_sigintr ) return;
109 if( v ) catch_intr();
118 const char *location;
121 static bc_buffertrace_t* new_bc_buffertrace(int size, void *ptr, const char *location)
123 bc_buffertrace_t *result = (bc_buffertrace_t*)malloc(sizeof(bc_buffertrace_t));
126 result->location = location;
130 static void bc_copy_textfile(int lines, FILE *ofp, const char *fmt,...)
132 va_list ap; va_start(ap, fmt);
133 char bfr[BCTEXTLEN]; vsnprintf(bfr, sizeof(bfr), fmt, ap);
135 FILE *ifp = fopen(bfr,"r");
137 while( --lines >= 0 && fgets(bfr,sizeof(bfr),ifp) ) fputs(bfr,ofp);
142 // Need our own table to avoid recursion with the memory manager
148 // This points to the next value to replace if the table wraps around
152 static void* append_table(bc_table_t *table, void *ptr)
154 if(table->allocation <= table->size)
156 if(table->allocation)
158 int new_allocation = table->allocation * 2;
159 void **new_values = (void**)calloc(new_allocation, sizeof(void*));
160 memcpy(new_values, table->values, sizeof(void*) * table->size);
162 table->values = new_values;
163 table->allocation = new_allocation;
167 table->allocation = 4096;
168 table->values = (void**)calloc(table->allocation, sizeof(void*));
172 table->values[table->size++] = ptr;
176 // Replace item in table pointed to by current_value and advance
178 static void* overwrite_table(bc_table_t *table, void *ptr)
180 free(table->values[table->current_value]);
181 table->values[table->current_value++] = ptr;
182 if(table->current_value >= table->size) table->current_value = 0;
186 static void clear_table(bc_table_t *table, int delete_objects)
190 for(int i = 0; i < table->size; i++)
192 free(table->values[i]);
198 static void clear_table_entry(bc_table_t *table, int number, int delete_object)
200 if(delete_object) free(table->values[number]);
201 for(int i = number; i < table->size - 1; i++)
203 table->values[i] = table->values[i + 1];
208 // Table of functions currently running.
209 static bc_table_t execution_table = { 0, 0, 0, 0 };
211 // Table of locked positions
212 static bc_table_t lock_table = { 0, 0, 0, 0 };
215 static bc_table_t memory_table = { 0, 0, 0, 0 };
217 static bc_table_t temp_files = { 0, 0, 0, 0 };
219 // Can't use Mutex because it would be recursive
220 static pthread_mutex_t *lock = 0;
221 static pthread_mutex_t *handler_lock = 0;
222 // incase lock set after task ends
223 static pthread_t last_lock_thread = 0;
224 static const char *last_lock_title = 0;
225 static const char *last_lock_location = 0;
226 // Don't trace memory until this is true to avoid initialization
227 static int trace_memory = 0;
230 static const char* signal_titles[] =
250 void BC_Signals::dump_stack(FILE *fp)
253 int total = backtrace (buffer, 256);
254 char **result = backtrace_symbols (buffer, total);
255 fprintf(fp, "BC_Signals::dump_stack\n");
256 for(int i = 0; i < total; i++)
258 fprintf(fp, "%s\n", result[i]);
263 void BC_Signals::kill_subs()
265 // List /proc directory
267 struct dirent64 *new_filename;
269 char path[BCTEXTLEN];
270 char string[BCTEXTLEN];
272 dirstream = opendir("/proc");
273 if(!dirstream) return;
275 while( (new_filename = readdir64(dirstream)) != 0 )
277 // All digits are numbers
278 char *ptr = new_filename->d_name;
282 if(*ptr == '.' || isalpha(*ptr++))
289 if(got_alpha) continue;
291 // Must be a directory
292 sprintf(path, "/proc/%s", new_filename->d_name);
293 if(!stat(path, &ostat))
295 if(S_ISDIR(ostat.st_mode))
298 strcat(path, "/stat");
299 //printf("kill_subs %d %s\n", __LINE__, path);
300 FILE *fd = fopen(path, "r");
302 // Must search forwards because the file is 0 length
308 //printf("kill_subs %d %d\n", __LINE__, c);
311 // Search for 2 spaces
313 while(!feof(fd) && spaces < 2)
320 // Read in parent process
333 // printf("kill_subs %d process=%d getpid=%d parent_process=%d\n",
335 // atoi(new_filename->d_name),
338 int parent_process = atoi(string);
339 int child_process = atoi(new_filename->d_name);
341 // Kill if we're the parent
342 if(getpid() == parent_process)
344 //printf("kill_subs %d: process=%d\n", __LINE__, atoi(new_filename->d_name));
345 kill(child_process, SIGKILL);
357 static void signal_entry(int signum)
359 signal(signum, SIG_DFL);
361 pthread_mutex_lock(handler_lock);
364 pthread_mutex_unlock(handler_lock);
369 pthread_mutex_unlock(handler_lock);
372 printf("signal_entry: got %s my pid=%d execution table size=%d:\n",
373 signal_titles[signum],
375 execution_table.size);
377 BC_Signals::kill_subs();
378 BC_Signals::dump_traces();
379 BC_Signals::dump_locks();
380 BC_Signals::dump_buffers();
381 BC_Signals::delete_temps();
383 // Call user defined signal handler
384 BC_Signals::global_signals->signal_handler(signum);
389 static void signal_entry_recoverable(int signum)
391 printf("signal_entry_recoverable: got %s my pid=%d\n",
392 signal_titles[signum],
396 // used to terminate child processes when program terminates
397 static void handle_exit(int signum)
399 //printf("child %d exit\n", getpid());
403 void BC_Signals::set_sighup_exit(int enable)
406 // causes SIGHUP to be generated when parent dies
407 signal(SIGHUP, handle_exit);
408 prctl(PR_SET_PDEATHSIG, SIGHUP, 0,0,0);
409 // prevents ^C from signalling child when attached to gdb
411 if( isatty(0) ) ioctl(0, TIOCNOTTY, 0);
414 signal(SIGHUP, signal_entry);
415 prctl(PR_SET_PDEATHSIG, 0,0,0,0);
419 BC_Signals::BC_Signals()
423 void BC_Signals::dump_traces(FILE *fp)
426 if(execution_table.size)
428 for(int i = execution_table.current_value; i < execution_table.size; i++)
429 fprintf(fp," %s\n", (char*)execution_table.values[i]);
430 for(int i = 0; i < execution_table.current_value; i++)
431 fprintf(fp," %s\n", (char*)execution_table.values[i]);
436 void BC_Signals::dump_locks(FILE *fp)
440 fprintf(fp,"signal_entry: lock table size=%d\n", lock_table.size);
441 for(int i = 0; i < lock_table.size; i++)
443 bc_locktrace_t *table = (bc_locktrace_t*)lock_table.values[i];
444 fprintf(fp," %p %s %s %p%s\n", table->ptr,
445 table->title, table->location, (void*)table->tid,
446 table->is_owner ? " *" : "");
451 void BC_Signals::dump_buffers(FILE *fp)
454 pthread_mutex_lock(lock);
456 fprintf(fp,"BC_Signals::dump_buffers: buffer table size=%d\n", memory_table.size);
457 for(int i = 0; i < memory_table.size; i++)
459 bc_buffertrace_t *entry = (bc_buffertrace_t*)memory_table.values[i];
460 fprintf(fp," %d %p %s\n", entry->size, entry->ptr, entry->location);
462 pthread_mutex_unlock(lock);
466 void BC_Signals::delete_temps()
468 pthread_mutex_lock(lock);
469 if(temp_files.size) printf("BC_Signals::delete_temps: deleting %d temp files\n", temp_files.size);
470 for(int i = 0; i < temp_files.size; i++)
472 printf(" %s\n", (char*)temp_files.values[i]);
473 remove((char*)temp_files.values[i]);
475 pthread_mutex_unlock(lock);
478 void BC_Signals::reset_locks()
480 pthread_mutex_unlock(lock);
483 void BC_Signals::set_temp(char *string)
485 char *new_string = strdup(string);
486 append_table(&temp_files, new_string);
489 void BC_Signals::unset_temp(char *string)
491 for(int i = 0; i < temp_files.size; i++)
493 if(!strcmp((char*)temp_files.values[i], string))
495 clear_table_entry(&temp_files, i, 1);
502 int BC_Signals::x_error_handler(Display *display, XErrorEvent *event)
505 XGetErrorText(event->display, event->error_code, string, 1024);
506 fprintf(stderr, "BC_Signals::x_error_handler: error_code=%d opcode=%d,%d %s\n",
507 event->error_code, event->request_code, event->minor_code, string);
512 void BC_Signals::initialize()
514 BC_Signals::global_signals = this;
515 lock = (pthread_mutex_t*)calloc(1, sizeof(pthread_mutex_t));
516 handler_lock = (pthread_mutex_t*)calloc(1, sizeof(pthread_mutex_t));
517 pthread_mutex_init(lock, 0);
518 pthread_mutex_init(handler_lock, 0);
519 old_err_handler = XSetErrorHandler(x_error_handler);
523 void BC_Signals::terminate()
525 BC_Signals::global_signals = 0;
526 uncatch_segv(); uncatch_intr();
527 signal(SIGHUP, SIG_DFL);
528 signal(SIGINT, SIG_DFL);
529 signal(SIGQUIT, SIG_DFL);
530 signal(SIGTERM, SIG_DFL);
531 signal(SIGFPE, SIG_DFL);
532 signal(SIGPIPE, SIG_DFL);
533 signal(SIGUSR2, SIG_DFL);
534 XSetErrorHandler(old_err_handler);
537 // callable from debugger
541 BC_Signals::dump_traces();
542 BC_Signals::dump_locks();
543 BC_Signals::dump_buffers();
547 void BC_Signals::signal_dump(int signum)
549 BC_KeyboardHandler::kill_grabs();
551 signal(SIGUSR2, signal_dump);
559 void BC_Signals::initialize2()
561 signal(SIGHUP, signal_entry);
562 signal(SIGINT, signal_entry);
563 signal(SIGQUIT, signal_entry);
564 // SIGKILL cannot be stopped
565 // signal(SIGKILL, signal_entry);
567 signal(SIGTERM, signal_entry);
568 signal(SIGFPE, signal_entry);
569 signal(SIGPIPE, signal_entry_recoverable);
570 signal(SIGUSR2, signal_dump);
574 void BC_Signals::signal_handler(int signum)
576 printf("BC_Signals::signal_handler\n");
580 const char* BC_Signals::sig_to_str(int number)
582 return signal_titles[number];
585 #define TOTAL_TRACES 16
587 void BC_Signals::new_trace(const char *text)
589 if(!global_signals) return;
590 pthread_mutex_lock(lock);
593 if(execution_table.size >= TOTAL_TRACES)
595 overwrite_table(&execution_table, strdup(text));
596 // clear_table(&execution_table, 1);
600 append_table(&execution_table, strdup(text));
602 pthread_mutex_unlock(lock);
605 void BC_Signals::new_trace(const char *file, const char *function, int line)
607 char string[BCTEXTLEN];
608 snprintf(string, BCTEXTLEN, "%s: %s: %d", file, function, line);
612 void BC_Signals::delete_traces()
614 if(!global_signals) return;
615 pthread_mutex_lock(lock);
616 clear_table(&execution_table, 0);
617 pthread_mutex_unlock(lock);
620 // no canceling with lock held
621 void BC_Signals::lock_locks(const char *s)
623 pthread_mutex_lock(lock);
624 last_lock_thread = pthread_self();
626 last_lock_location = 0;
629 void BC_Signals::unlock_locks()
631 pthread_mutex_unlock(lock);
634 #define TOTAL_LOCKS 256
636 int BC_Signals::set_lock(void *ptr,
638 const char *location)
640 if(!global_signals) return 0;
641 bc_locktrace_t *table = 0;
644 pthread_mutex_lock(lock);
645 last_lock_thread = pthread_self();
646 last_lock_title = title;
647 last_lock_location = location;
648 if(lock_table.size >= TOTAL_LOCKS)
649 clear_table(&lock_table, 0);
651 // Put new lock entry
652 table = new_bc_locktrace(ptr, title, location);
653 append_table(&lock_table, table);
654 id_return = table->id;
656 pthread_mutex_unlock(lock);
660 void BC_Signals::set_lock2(int table_id)
662 if(!global_signals) return;
664 bc_locktrace_t *table = 0;
665 pthread_mutex_lock(lock);
666 for(int i = lock_table.size - 1; i >= 0; i--)
668 table = (bc_locktrace_t*)lock_table.values[i];
669 // Got it. Hasn't been unlocked/deleted yet.
670 if(table->id == table_id)
673 table->tid = pthread_self();
674 pthread_mutex_unlock(lock);
678 pthread_mutex_unlock(lock);
681 void BC_Signals::unset_lock2(int table_id)
683 if(!global_signals) return;
685 bc_locktrace_t *table = 0;
686 pthread_mutex_lock(lock);
687 for(int i = lock_table.size - 1; i >= 0; i--)
689 table = (bc_locktrace_t*)lock_table.values[i];
690 if(table->id == table_id)
692 clear_table_entry(&lock_table, i, 1);
696 pthread_mutex_unlock(lock);
699 void BC_Signals::unset_lock(void *ptr)
701 if(!global_signals) return;
703 bc_locktrace_t *table = 0;
704 pthread_mutex_lock(lock);
706 // Take off currently held entry
707 for(int i = 0; i < lock_table.size; i++)
709 table = (bc_locktrace_t*)lock_table.values[i];
710 if(table->ptr == ptr)
714 clear_table_entry(&lock_table, i, 1);
720 pthread_mutex_unlock(lock);
724 void BC_Signals::unset_all_locks(void *ptr)
726 if(!global_signals) return;
727 pthread_mutex_lock(lock);
728 // Take off previous lock entry
729 for(int i = 0; i < lock_table.size; )
731 bc_locktrace_t *table = (bc_locktrace_t*)lock_table.values[i];
732 if(table->ptr == ptr)
734 clear_table_entry(&lock_table, i, 1);
739 pthread_mutex_unlock(lock);
742 void BC_Signals::clear_locks_tid(pthread_t tid)
744 if(!global_signals) return;
745 pthread_mutex_lock(lock);
746 // Take off previous lock entry
747 for(int i = 0; i < lock_table.size; )
749 bc_locktrace_t *table = (bc_locktrace_t*)lock_table.values[i];
750 if(table->tid == tid)
752 clear_table_entry(&lock_table, i, 1);
757 pthread_mutex_unlock(lock);
761 void BC_Signals::enable_memory()
766 void BC_Signals::disable_memory()
772 void BC_Signals::set_buffer(int size, void *ptr, const char* location)
774 if(!global_signals) return;
775 if(!trace_memory) return;
777 //printf("BC_Signals::set_buffer %p %s\n", ptr, location);
778 pthread_mutex_lock(lock);
779 append_table(&memory_table, new_bc_buffertrace(size, ptr, location));
780 pthread_mutex_unlock(lock);
783 int BC_Signals::unset_buffer(void *ptr)
785 if(!global_signals) return 0;
786 if(!trace_memory) return 0;
789 pthread_mutex_lock(lock);
790 for(int i = 0; i < memory_table.size; i++)
792 if(((bc_buffertrace_t*)memory_table.values[i])->ptr == ptr)
794 //printf("BC_Signals::unset_buffer %p\n", ptr);
795 clear_table_entry(&memory_table, i, 1);
801 pthread_mutex_unlock(lock);
802 // fprintf(stderr, "BC_Signals::unset_buffer buffer %p not found.\n", ptr);
807 #include <ucontext.h>
808 #include <sys/wait.h>
822 static void handle_dump(int n, siginfo_t * info, void *sc)
824 uncatch_segv(); uncatch_intr();
825 signal(SIGSEGV, SIG_DFL);
826 signal(SIGINT, SIG_DFL);
827 // gotta be root, or the dump is worthless
829 if( uid != 0 ) return;
830 ucontext_t *uc = (ucontext_t *)sc;
831 int pid = getpid(), tid = gettid();
832 struct sigcontext *c = (struct sigcontext *)&uc->uc_mcontext;
833 fprintf(stderr,"** %s at %p in pid %d, tid %d\n",
834 n==SIGSEGV? "segv" : n==SIGINT? "intr" : "trap",
835 (void*)c->IP, pid, tid);
838 if( BC_Signals::trap_path ) {
839 snprintf(fn, sizeof(fn), BC_Signals::trap_path, pid);
843 fprintf(stderr,"writing debug data to %s\n", fn);
844 fprintf(fp,"** %s at %p in pid %d, tid %d\n",
845 n==SIGSEGV? "segv" : n==SIGINT? "intr" : "trap",
846 (void*)c->IP, pid, tid);
849 strcpy(fn, "stdout");
853 fprintf(fp,"created on %s", ctime(&t));
854 struct passwd *pw = getpwuid(uid);
856 fprintf(fp," by %d:%d %s(%s)\n",
857 pw->pw_uid, pw->pw_gid, pw->pw_name, pw->pw_gecos);
859 fprintf(fp,"\nCPUS: %d\n", BC_Resources::get_machine_cpus());
860 fprintf(fp,"\nCPUINFO:\n"); bc_copy_textfile(32, fp,"/proc/cpuinfo");
861 fprintf(fp,"\nTHREADS:\n"); Thread::dump_threads(fp);
862 fprintf(fp,"\nTRACES:\n"); BC_Signals::dump_traces(fp);
863 fprintf(fp,"\nLOCKS:\n"); BC_Signals::dump_locks(fp);
864 fprintf(fp,"\nBUFFERS:\n"); BC_Signals::dump_buffers(fp);
865 if( BC_Signals::trap_hook ) {
866 fprintf(fp,"\nMAIN HOOK:\n");
867 BC_Signals::trap_hook(fp, BC_Signals::trap_data);
869 fprintf(fp,"\nVERSION:\n"); bc_copy_textfile(INT_MAX, fp,"/proc/version");
870 fprintf(fp,"\nMEMINFO:\n"); bc_copy_textfile(INT_MAX, fp,"/proc/meminfo");
871 fprintf(fp,"\nMAPS:\n"); bc_copy_textfile(INT_MAX, fp,"/proc/%d/maps",pid);
873 if( fp != stdout ) fclose(fp);
874 char cmd[1024], *cp = cmd;
875 cp += sprintf(cp, "exec gdb /proc/%d/exe -p %d --batch --quiet "
876 "-ex \"thread apply all info registers\" "
877 "-ex \"thread apply all bt full\" "
878 "-ex \"quit\"", pid, pid);
880 cp += sprintf(cp," >> \"%s\"", fn);
881 cp += sprintf(cp," 2>&1");
882 //printf("handle_dump:: pid=%d, cmd='%s' fn='%s'\n",pid,cmd,fn);
885 fprintf(stderr,"** can't start gdb, dump abondoned\n");
890 fprintf(stderr,"** dump complete\n");
893 char *const argv[4] = { (char*) "/bin/sh", (char*) "-c", cmd, 0 };
894 execvp(argv[0], &argv[0]);
903 // void* operator new(size_t size)
905 // //printf("new 1 %d\n", size);
906 // void *result = malloc(size);
907 // BUFFER(size, result, "new");
908 // //printf("new 2 %d\n", size);
912 // void* operator new[](size_t size)
914 // //printf("new [] 1 %d\n", size);
915 // void *result = malloc(size);
916 // BUFFER(size, result, "new []");
917 // //printf("new [] 2 %d\n", size);
921 // void operator delete(void *ptr)
923 // //printf("delete 1 %p\n", ptr);
925 // //printf("delete 2 %p\n", ptr);
929 // void operator delete[](void *ptr)
931 // //printf("delete [] 1 %p\n", ptr);
934 // //printf("delete [] 2 %p\n", ptr);