1 /* 2 * Copyright 2005-2011, Ingo Weinhold, ingo_weinhold@gmx.de. 3 * Copyright 2013, Rene Gollent, rene@gollent.com. 4 * Copyright 2015, Axel Dörfler, axeld@pinc-software.de. 5 * Distributed under the terms of the MIT License. 6 */ 7 8 9 #include <ctype.h> 10 #include <stdio.h> 11 #include <stdlib.h> 12 #include <string.h> 13 #include <strings.h> 14 #include <errno.h> 15 #include <signal.h> 16 17 #include <algorithm> 18 #include <map> 19 #include <string> 20 #include <vector> 21 22 #include <debugger.h> 23 #include <image.h> 24 #include <syscalls.h> 25 26 #include "debug_utils.h" 27 28 #include "Context.h" 29 #include "MemoryReader.h" 30 #include "Syscall.h" 31 #include "TypeHandler.h" 32 33 34 using std::map; 35 using std::string; 36 using std::vector; 37 38 39 struct syscall_stats { 40 bigtime_t time; 41 uint32 count; 42 }; 43 44 45 extern void get_syscalls0(vector<Syscall*> &syscalls); 46 extern void get_syscalls1(vector<Syscall*> &syscalls); 47 extern void get_syscalls2(vector<Syscall*> &syscalls); 48 extern void get_syscalls3(vector<Syscall*> &syscalls); 49 extern void get_syscalls4(vector<Syscall*> &syscalls); 50 extern void get_syscalls5(vector<Syscall*> &syscalls); 51 extern void get_syscalls6(vector<Syscall*> &syscalls); 52 extern void get_syscalls7(vector<Syscall*> &syscalls); 53 extern void get_syscalls8(vector<Syscall*> &syscalls); 54 extern void get_syscalls9(vector<Syscall*> &syscalls); 55 extern void get_syscalls10(vector<Syscall*> &syscalls); 56 extern void get_syscalls11(vector<Syscall*> &syscalls); 57 extern void get_syscalls12(vector<Syscall*> &syscalls); 58 extern void get_syscalls13(vector<Syscall*> &syscalls); 59 extern void get_syscalls14(vector<Syscall*> &syscalls); 60 extern void get_syscalls15(vector<Syscall*> &syscalls); 61 extern void get_syscalls16(vector<Syscall*> &syscalls); 62 extern void get_syscalls17(vector<Syscall*> &syscalls); 63 extern void get_syscalls18(vector<Syscall*> &syscalls); 64 extern void get_syscalls19(vector<Syscall*> &syscalls); 65 66 67 extern const char *__progname; 68 static const char *kCommandName = __progname; 69 70 71 // usage 72 static const char *kUsage = 73 "Usage: %s [ <options> ] [ <thread or team ID> | <executable with args> ]\n" 74 "\n" 75 "Traces the syscalls of a thread or a team. If an executable with\n" 76 "arguments is supplied, it is loaded and it's main thread traced.\n" 77 "\n" 78 "Options:\n" 79 " -a - Don't print syscall arguments.\n" 80 " -c - Record and dump syscall usage statistics.\n" 81 " -C - Same as -c, but also print syscalls as usual.\n" 82 " -d <name> - Filter the types that have their contents retrieved.\n" 83 " <name> is one of: strings, enums, simple, complex or\n" 84 " pointer_values\n" 85 " -f - Fast mode. Syscall arguments contents aren't retrieved.\n" 86 " -h, --help - Print this text.\n" 87 " -i - Print integers in decimal format instead of hexadecimal.\n" 88 " -l - Also trace loading the executable. Only considered when\n" 89 " an executable is provided.\n" 90 " --no-color - Don't colorize output.\n" 91 " -r - Don't print syscall return values.\n" 92 " -s - Also trace all threads spawned by the supplied thread,\n" 93 " respectively the loaded executable's main thread.\n" 94 " -t - Also recursively trace all teams created by a traced\n" 95 " thread or team.\n" 96 " -T - Trace all threads of the supplied or loaded executable's\n" 97 " team. If an ID is supplied, it is interpreted as a team\n" 98 " ID.\n" 99 " -o <file> - directs output into the specified file.\n" 100 " -S - prints output to serial debug line.\n" 101 " -g - turns off signal tracing.\n" 102 ; 103 104 105 // terminal color escape sequences 106 // (http://www.dee.ufcg.edu.br/~rrbrandt/tools/ansi.html) 107 static const char *kTerminalTextNormal = "\33[0m"; 108 static const char *kTerminalTextRed = "\33[31m"; 109 static const char *kTerminalTextMagenta = "\33[35m"; 110 static const char *kTerminalTextBlue = "\33[34m"; 111 112 113 // signal names 114 static const char *kSignalName[] = { 115 /* 0 */ "SIG0", 116 /* 1 */ "SIGHUP", 117 /* 2 */ "SIGINT", 118 /* 3 */ "SIGQUIT", 119 /* 4 */ "SIGILL", 120 /* 5 */ "SIGCHLD", 121 /* 6 */ "SIGABRT", 122 /* 7 */ "SIGPIPE", 123 /* 8 */ "SIGFPE", 124 /* 9 */ "SIGKILL", 125 /* 10 */ "SIGSTOP", 126 /* 11 */ "SIGSEGV", 127 /* 12 */ "SIGCONT", 128 /* 13 */ "SIGTSTP", 129 /* 14 */ "SIGALRM", 130 /* 15 */ "SIGTERM", 131 /* 16 */ "SIGTTIN", 132 /* 17 */ "SIGTTOU", 133 /* 18 */ "SIGUSR1", 134 /* 19 */ "SIGUSR2", 135 /* 20 */ "SIGWINCH", 136 /* 21 */ "SIGKILLTHR", 137 /* 22 */ "SIGTRAP", 138 /* 23 */ "SIGPOLL", 139 /* 24 */ "SIGPROF", 140 /* 25 */ "SIGSYS", 141 /* 26 */ "SIGURG", 142 /* 27 */ "SIGVTALRM", 143 /* 28 */ "SIGXCPU", 144 /* 29 */ "SIGXFSZ", 145 /* 30 */ "SIGBUS", 146 /* 31 */ "SIGRESERVED1", 147 /* 32 */ "SIGRESERVED2", 148 }; 149 150 151 // command line args 152 static int sArgc; 153 static const char *const *sArgv; 154 155 // syscalls 156 static vector<Syscall*> sSyscallVector; 157 static map<string, Syscall*> sSyscallMap; 158 159 // statistics 160 typedef map<string, syscall_stats> StatsMap; 161 static StatsMap sSyscallStats; 162 static bigtime_t sSyscallTime; 163 164 165 struct Team { 166 Team(team_id id) 167 : 168 fID(id), 169 fNubPort(-1) 170 { 171 } 172 173 team_id ID() const 174 { 175 return fID; 176 } 177 178 port_id NubPort() const 179 { 180 return fNubPort; 181 } 182 183 MemoryReader& GetMemoryReader() 184 { 185 return fMemoryReader; 186 } 187 188 status_t InstallDebugger(port_id debuggerPort, bool traceTeam, 189 bool traceChildTeams, bool traceSignal) 190 { 191 fNubPort = install_team_debugger(fID, debuggerPort); 192 if (fNubPort < 0) { 193 fprintf(stderr, "%s: Failed to install team debugger: %s\n", 194 kCommandName, strerror(fNubPort)); 195 return fNubPort; 196 } 197 198 // set team debugging flags 199 int32 teamDebugFlags = 200 (traceTeam ? B_TEAM_DEBUG_PRE_SYSCALL | B_TEAM_DEBUG_POST_SYSCALL : 0) 201 | (traceChildTeams ? B_TEAM_DEBUG_TEAM_CREATION : 0) 202 | (traceSignal ? B_TEAM_DEBUG_SIGNALS : 0); 203 if (set_team_debugging_flags(fNubPort, teamDebugFlags) != B_OK) 204 exit(1); 205 206 return fMemoryReader.Init(fNubPort); 207 } 208 209 private: 210 team_id fID; 211 port_id fNubPort; 212 MemoryReader fMemoryReader; 213 }; 214 215 216 static void 217 print_usage(bool error) 218 { 219 // print usage 220 fprintf((error ? stderr : stdout), kUsage, kCommandName); 221 } 222 223 224 static void 225 print_usage_and_exit(bool error) 226 { 227 print_usage(error); 228 exit(error ? 1 : 0); 229 } 230 231 232 static bool 233 get_id(const char *str, int32 &id) 234 { 235 int32 len = strlen(str); 236 for (int32 i = 0; i < len; i++) { 237 if (!isdigit(str[i])) 238 return false; 239 } 240 241 id = atol(str); 242 return true; 243 } 244 245 246 Syscall * 247 get_syscall(const char *name) 248 { 249 map<string, Syscall *>::const_iterator i = sSyscallMap.find(name); 250 if (i == sSyscallMap.end()) 251 return NULL; 252 253 return i->second; 254 } 255 256 257 static void 258 patch_syscalls() 259 { 260 // instead of having this done here manually we should either add the 261 // patching step to gensyscalls also manually or add metadata to 262 // kernel/syscalls.h and have it parsed automatically 263 extern void patch_ioctl(); 264 265 patch_ioctl(); 266 267 Syscall *poll = get_syscall("_kern_poll"); 268 poll->ParameterAt(0)->SetInOut(true); 269 270 Syscall *select = get_syscall("_kern_select"); 271 select->ParameterAt(1)->SetInOut(true); 272 select->ParameterAt(2)->SetInOut(true); 273 select->ParameterAt(3)->SetInOut(true); 274 } 275 276 277 static void 278 init_syscalls() 279 { 280 // init the syscall vector 281 get_syscalls0(sSyscallVector); 282 get_syscalls1(sSyscallVector); 283 get_syscalls2(sSyscallVector); 284 get_syscalls3(sSyscallVector); 285 get_syscalls4(sSyscallVector); 286 get_syscalls5(sSyscallVector); 287 get_syscalls6(sSyscallVector); 288 get_syscalls7(sSyscallVector); 289 get_syscalls8(sSyscallVector); 290 get_syscalls9(sSyscallVector); 291 get_syscalls10(sSyscallVector); 292 get_syscalls11(sSyscallVector); 293 get_syscalls12(sSyscallVector); 294 get_syscalls13(sSyscallVector); 295 get_syscalls14(sSyscallVector); 296 get_syscalls15(sSyscallVector); 297 get_syscalls16(sSyscallVector); 298 get_syscalls17(sSyscallVector); 299 get_syscalls18(sSyscallVector); 300 get_syscalls19(sSyscallVector); 301 302 // init the syscall map 303 int32 count = sSyscallVector.size(); 304 for (int32 i = 0; i < count; i++) { 305 Syscall *syscall = sSyscallVector[i]; 306 sSyscallMap[syscall->Name()] = syscall; 307 } 308 309 patch_syscalls(); 310 } 311 312 313 static void 314 record_syscall_stats(const Syscall& syscall, debug_post_syscall& message) 315 { 316 syscall_stats& stats = sSyscallStats[syscall.Name()]; 317 stats.count++; 318 319 bigtime_t time = message.end_time - message.start_time; 320 stats.time += time; 321 sSyscallTime += time; 322 } 323 324 325 static void 326 print_buffer(FILE *outputFile, char* buffer, int32 length) 327 { 328 // output either to file or serial debug line 329 if (outputFile != NULL) 330 fwrite(buffer, length, 1, outputFile); 331 else 332 _kern_debug_output(buffer); 333 } 334 335 336 static void 337 print_to_string(char **_buffer, int32 *_length, const char *format, ...) 338 { 339 va_list list; 340 va_start(list, format); 341 ssize_t length = vsnprintf(*_buffer, *_length, format, list); 342 va_end(list); 343 344 *_buffer += length; 345 *_length -= length; 346 } 347 348 349 static void 350 print_syscall(FILE *outputFile, Syscall* syscall, debug_pre_syscall &message, 351 MemoryReader &memoryReader, bool printArguments, uint32 contentsFlags, 352 bool colorize, bool decimal, thread_id ¤tThreadID) 353 { 354 char buffer[4096], *string = buffer; 355 int32 length = (int32)sizeof(buffer); 356 357 Context ctx(syscall, (char *)message.args, memoryReader, 358 contentsFlags | Context::INPUT_VALUES, decimal); 359 360 if (currentThreadID != message.origin.thread) { 361 if (currentThreadID != -1) 362 print_to_string(&string, &length, " <unfinished ...>\n"); 363 currentThreadID = message.origin.thread; 364 } 365 366 // print syscall name, without the "_kern_" 367 if (colorize) { 368 print_to_string(&string, &length, "[%6" B_PRId32 "] %s%s%s(", 369 message.origin.thread, kTerminalTextBlue, 370 syscall->Name().c_str() + 6, kTerminalTextNormal); 371 } else { 372 print_to_string(&string, &length, "[%6" B_PRId32 "] %s(", 373 message.origin.thread, syscall->Name().c_str() + 6); 374 } 375 376 // print arguments 377 if (printArguments) { 378 int32 count = syscall->CountParameters(); 379 for (int32 i = 0; i < count; i++) { 380 // get the value 381 Parameter *parameter = syscall->ParameterAt(i); 382 TypeHandler *handler = parameter->Handler(); 383 ::string value = 384 handler->GetParameterValue(ctx, parameter, 385 ctx.GetValue(parameter)); 386 387 print_to_string(&string, &length, (i > 0 ? ", %s" : "%s"), 388 value.c_str()); 389 } 390 } 391 392 print_to_string(&string, &length, ")"); 393 394 print_buffer(outputFile, buffer, sizeof(buffer) - length); 395 } 396 397 398 static void 399 print_syscall(FILE *outputFile, Syscall* syscall, debug_post_syscall &message, 400 MemoryReader &memoryReader, bool printArguments, uint32 contentsFlags, 401 bool printReturnValue, bool colorize, bool decimal, 402 thread_id ¤tThreadID) 403 { 404 char buffer[4096], *string = buffer; 405 int32 length = (int32)sizeof(buffer); 406 bool threadChanged = false; 407 408 Context ctx(syscall, (char *)message.args, memoryReader, 409 contentsFlags | Context::OUTPUT_VALUES, decimal, message.return_value); 410 411 if (currentThreadID != message.origin.thread) { 412 if (currentThreadID != -1) { 413 print_to_string(&string, &length, " <unfinished ...>\n"); 414 } 415 threadChanged = true; 416 } 417 currentThreadID = -1; 418 419 // print return value 420 if (printReturnValue) { 421 if (threadChanged) { 422 // print syscall name, without the "_kern_" 423 if (colorize) { 424 print_to_string(&string, &length, "[%6" B_PRId32 "] <... " 425 "%s%s%s resumed> ", message.origin.thread, kTerminalTextBlue, 426 syscall->Name().c_str() + 6, kTerminalTextNormal); 427 } else { 428 print_to_string(&string, &length, "[%6" B_PRId32 "] <... %s" 429 " resumed> ", message.origin.thread, 430 syscall->Name().c_str() + 6); 431 } 432 } 433 Type *returnType = syscall->ReturnType(); 434 TypeHandler *handler = returnType->Handler(); 435 ::string value = handler->GetReturnValue(ctx, message.return_value); 436 if (value.length() > 0) { 437 print_to_string(&string, &length, " = %s", value.c_str()); 438 439 // if the return type is status_t or ssize_t, print human-readable 440 // error codes 441 if (returnType->TypeName() == "status_t" 442 || ((returnType->TypeName() == "ssize_t" 443 || returnType->TypeName() == "int") 444 && message.return_value < 0)) { 445 print_to_string(&string, &length, " %s", strerror(message.return_value)); 446 } 447 } 448 } 449 450 // print arguments 451 if (printArguments) { 452 int32 count = syscall->CountParameters(); 453 int added = 0; 454 print_to_string(&string, &length, " ("); 455 for (int32 i = 0; i < count; i++) { 456 // get the value 457 Parameter *parameter = syscall->ParameterAt(i); 458 if (!parameter->InOut()) 459 continue; 460 TypeHandler *handler = parameter->Handler(); 461 ::string value = 462 handler->GetParameterValue(ctx, parameter, 463 ctx.GetValue(parameter)); 464 465 print_to_string(&string, &length, (added > 0 ? ", %s" : "%s"), 466 value.c_str()); 467 added++; 468 } 469 print_to_string(&string, &length, ")"); 470 } 471 472 if (colorize) { 473 print_to_string(&string, &length, " %s(%lld us)%s\n", kTerminalTextMagenta, 474 message.end_time - message.start_time, kTerminalTextNormal); 475 } else { 476 print_to_string(&string, &length, " (%lld us)\n", 477 message.end_time - message.start_time); 478 } 479 480 //for (int32 i = 0; i < 16; i++) { 481 // if (i % 4 == 0) { 482 // if (i > 0) 483 // printf("\n"); 484 // printf(" "); 485 // } else 486 // printf(" "); 487 // printf("%08lx", message.args[i]); 488 //} 489 //printf("\n"); 490 print_buffer(outputFile, buffer, sizeof(buffer) - length); 491 } 492 493 494 static const char * 495 signal_name(int signal) 496 { 497 if (signal >= 0 && signal <= SIGRESERVED2) 498 return kSignalName[signal]; 499 500 static char buffer[32]; 501 sprintf(buffer, "%d", signal); 502 return buffer; 503 } 504 505 506 static void 507 print_signal(FILE *outputFile, debug_signal_received &message, 508 bool colorize) 509 { 510 char buffer[4096], *string = buffer; 511 int32 length = (int32)sizeof(buffer); 512 int signalNumber = message.signal; 513 514 // print signal name 515 if (colorize) { 516 print_to_string(&string, &length, "[%6" B_PRId32 "] --- %s%s (%s) %s---\n", 517 message.origin.thread, kTerminalTextRed, signal_name(signalNumber), 518 strsignal(signalNumber), kTerminalTextNormal); 519 } else { 520 print_to_string(&string, &length, "[%6" B_PRId32 "] --- %s (%s) ---\n", 521 message.origin.thread, signal_name(signalNumber), 522 strsignal(signalNumber)); 523 } 524 525 print_buffer(outputFile, buffer, sizeof(buffer) - length); 526 } 527 528 529 static bool 530 compare_stats_by_time( 531 const std::pair<const std::string*, const syscall_stats*>& a, 532 const std::pair<const std::string*, const syscall_stats*>& b) 533 { 534 return a.second->time > b.second->time; 535 } 536 537 538 static void 539 print_stats(FILE* outputFile) 540 { 541 char buffer[4096], *string = buffer; 542 int32 length = (int32)sizeof(buffer); 543 544 typedef std::vector<std::pair<const std::string*, const syscall_stats*> > 545 StatsRefVector; 546 StatsRefVector calls; 547 StatsMap::const_iterator iterator = sSyscallStats.begin(); 548 for (; iterator != sSyscallStats.end(); iterator++) 549 calls.push_back(std::make_pair(&iterator->first, &iterator->second)); 550 551 // Sort calls by time spent 552 std::sort(calls.begin(), calls.end(), compare_stats_by_time); 553 554 print_to_string(&string, &length, "\n%-6s %-10s %-7s %-10s Syscall\n", 555 "Time %", "Usecs", "Calls", "Usecs/call"); 556 print_to_string(&string, &length, "------ ---------- ------- ---------- " 557 "--------------------\n"); 558 559 StatsRefVector::const_iterator callIterator = calls.begin(); 560 for (; callIterator != calls.end(); callIterator++) { 561 const syscall_stats& stats = *callIterator->second; 562 double percent = stats.time * 100.0 / sSyscallTime; 563 bigtime_t perCall = stats.time / stats.count; 564 565 print_to_string(&string, &length, "%6.2f %10" B_PRIu64 " %7" B_PRIu32 566 " %10" B_PRIu64 " %s\n", percent, stats.time, stats.count, perCall, 567 callIterator->first->c_str()); 568 } 569 570 print_buffer(outputFile, buffer, sizeof(buffer) - length); 571 } 572 573 574 int 575 main(int argc, const char *const *argv) 576 { 577 sArgc = argc; 578 sArgv = argv; 579 580 // parameters 581 const char *const *programArgs = NULL; 582 int32 programArgCount = 0; 583 bool printArguments = true; 584 bool colorize = true; 585 bool stats = false; 586 bool trace = true; 587 uint32 contentsFlags = 0; 588 bool decimalFormat = false; 589 bool fastMode = false; 590 bool traceLoading = false; 591 bool printReturnValues = true; 592 bool traceChildThreads = false; 593 bool traceTeam = false; 594 bool traceChildTeams = false; 595 bool traceSignal = true; 596 bool serialOutput = false; 597 FILE *outputFile = stdout; 598 599 // parse arguments 600 for (int argi = 1; argi < argc; argi++) { 601 const char *arg = argv[argi]; 602 if (arg[0] == '-') { 603 // ToDo: improve option parsing so that ie. "-rsf" would also work 604 if (strcmp(arg, "-h") == 0 || strcmp(arg, "--help") == 0) { 605 print_usage_and_exit(false); 606 } else if (strcmp(arg, "-a") == 0) { 607 printArguments = false; 608 } else if (strcmp(arg, "-c") == 0) { 609 stats = true; 610 trace = false; 611 } else if (strcmp(arg, "-C") == 0) { 612 stats = true; 613 } else if (strcmp(arg, "--no-color") == 0) { 614 colorize = false; 615 } else if (strcmp(arg, "-d") == 0) { 616 const char *what = NULL; 617 618 if (arg[2] == '\0' 619 && argi + 1 < argc && argv[argi + 1][0] != '-') { 620 // next arg is what 621 what = argv[++argi]; 622 } else 623 print_usage_and_exit(true); 624 625 if (strcasecmp(what, "strings") == 0) 626 contentsFlags |= Context::STRINGS; 627 else if (strcasecmp(what, "enums") == 0) 628 contentsFlags |= Context::ENUMERATIONS; 629 else if (strcasecmp(what, "simple") == 0) 630 contentsFlags |= Context::SIMPLE_STRUCTS; 631 else if (strcasecmp(what, "complex") == 0) 632 contentsFlags |= Context::COMPLEX_STRUCTS; 633 else if (strcasecmp(what, "pointer_values") == 0) 634 contentsFlags |= Context::POINTER_VALUES; 635 else { 636 fprintf(stderr, "%s: Unknown content filter `%s'\n", 637 kCommandName, what); 638 exit(1); 639 } 640 } else if (strcmp(arg, "-f") == 0) { 641 fastMode = true; 642 } else if (strcmp(arg, "-i") == 0) { 643 decimalFormat = true; 644 } else if (strcmp(arg, "-l") == 0) { 645 traceLoading = true; 646 } else if (strcmp(arg, "-r") == 0) { 647 printReturnValues = false; 648 } else if (strcmp(arg, "-s") == 0) { 649 traceChildThreads = true; 650 } else if (strcmp(arg, "-t") == 0) { 651 traceChildTeams = true; 652 } else if (strcmp(arg, "-T") == 0) { 653 traceTeam = true; 654 } else if (strcmp(arg, "-g") == 0) { 655 traceSignal = false; 656 } else if (strcmp(arg, "-S") == 0) { 657 serialOutput = true; 658 outputFile = NULL; 659 } else if (strncmp(arg, "-o", 2) == 0) { 660 // read filename 661 const char *filename = NULL; 662 if (arg[2] == '=') { 663 // name follows 664 filename = arg + 3; 665 } else if (arg[2] == '\0' 666 && argi + 1 < argc && argv[argi + 1][0] != '-') { 667 // next arg is name 668 filename = argv[++argi]; 669 } else 670 print_usage_and_exit(true); 671 672 outputFile = fopen(filename, "w+"); 673 if (outputFile == NULL) { 674 fprintf(stderr, "%s: Could not open `%s': %s\n", 675 kCommandName, filename, strerror(errno)); 676 exit(1); 677 } 678 } else { 679 print_usage_and_exit(true); 680 } 681 } else { 682 programArgs = argv + argi; 683 programArgCount = argc - argi; 684 break; 685 } 686 } 687 688 // check parameters 689 if (!programArgs) 690 print_usage_and_exit(true); 691 692 if (fastMode) 693 contentsFlags = 0; 694 else if (contentsFlags == 0) 695 contentsFlags = Context::ALL; 696 697 // initialize our syscalls vector and map 698 init_syscalls(); 699 700 // don't colorize the output, if we don't have a terminal 701 if (outputFile == stdout) 702 colorize = colorize && isatty(STDOUT_FILENO); 703 else if (outputFile) 704 colorize = false; 705 706 // get thread/team to be debugged 707 thread_id threadID = -1; 708 team_id teamID = -1; 709 if (programArgCount > 1 710 || !get_id(*programArgs, (traceTeam ? teamID : threadID))) { 711 // we've been given an executable and need to load it 712 threadID = load_program(programArgs, programArgCount, traceLoading); 713 if (threadID < 0) { 714 fprintf(stderr, "%s: Failed to start `%s': %s\n", kCommandName, 715 programArgs[0], strerror(threadID)); 716 exit(1); 717 } 718 } 719 720 // get the team ID, if we have none yet 721 if (teamID < 0) { 722 thread_info threadInfo; 723 status_t error = get_thread_info(threadID, &threadInfo); 724 if (error != B_OK) { 725 fprintf(stderr, "%s: Failed to get info for thread %" B_PRId32 726 ": %s\n", kCommandName, threadID, strerror(error)); 727 exit(1); 728 } 729 teamID = threadInfo.team; 730 } 731 732 // create a debugger port 733 port_id debuggerPort = create_port(10, "debugger port"); 734 if (debuggerPort < 0) { 735 fprintf(stderr, "%s: Failed to create debugger port: %s\n", 736 kCommandName, strerror(debuggerPort)); 737 exit(1); 738 } 739 740 // install ourselves as the team debugger 741 typedef map<team_id, Team*> TeamMap; 742 TeamMap debuggedTeams; 743 port_id nubPort; 744 745 { 746 Team* team = new Team(teamID); 747 status_t error = team->InstallDebugger(debuggerPort, traceTeam, 748 traceChildTeams, traceSignal); 749 if (error != B_OK) 750 exit(1); 751 752 debuggedTeams[team->ID()] = team; 753 754 nubPort = team->NubPort(); 755 } 756 757 // set thread debugging flags 758 if (threadID >= 0) { 759 int32 threadDebugFlags = 0; 760 if (!traceTeam) { 761 threadDebugFlags = B_THREAD_DEBUG_PRE_SYSCALL | B_THREAD_DEBUG_POST_SYSCALL 762 | (traceChildThreads 763 ? B_THREAD_DEBUG_SYSCALL_TRACE_CHILD_THREADS : 0); 764 } 765 if (set_thread_debugging_flags(nubPort, threadID, threadDebugFlags) 766 != B_OK) { 767 exit(1); 768 } 769 770 // resume the target thread to be sure, it's running 771 resume_thread(threadID); 772 } 773 774 thread_id currentThreadID = -1; 775 776 // debug loop 777 while (true) { 778 bool quitLoop = false; 779 int32 code; 780 debug_debugger_message_data message; 781 ssize_t messageSize = read_port(debuggerPort, &code, &message, 782 sizeof(message)); 783 784 if (messageSize < 0) { 785 if (messageSize == B_INTERRUPTED) 786 continue; 787 788 fprintf(stderr, "%s: Reading from debugger port failed: %s\n", 789 kCommandName, strerror(messageSize)); 790 exit(1); 791 } 792 793 switch (code) { 794 case B_DEBUGGER_MESSAGE_PRE_SYSCALL: 795 { 796 TeamMap::iterator it = debuggedTeams.find(message.origin.team); 797 if (it == debuggedTeams.end()) 798 break; 799 800 Team* team = it->second; 801 MemoryReader& memoryReader = team->GetMemoryReader(); 802 803 uint32 syscallNumber = message.pre_syscall.syscall; 804 if (syscallNumber >= sSyscallVector.size()) { 805 fprintf(stderr, "%s: invalid syscall %" B_PRIu32 " attempted\n", 806 kCommandName, syscallNumber); 807 break; 808 } 809 Syscall* syscall = sSyscallVector[syscallNumber]; 810 811 if (trace) { 812 print_syscall(outputFile, syscall, message.pre_syscall, 813 memoryReader, printArguments, contentsFlags, 814 colorize, decimalFormat, currentThreadID); 815 } 816 break; 817 } 818 819 case B_DEBUGGER_MESSAGE_POST_SYSCALL: 820 { 821 TeamMap::iterator it = debuggedTeams.find(message.origin.team); 822 if (it == debuggedTeams.end()) 823 break; 824 825 Team* team = it->second; 826 MemoryReader& memoryReader = team->GetMemoryReader(); 827 828 uint32 syscallNumber = message.post_syscall.syscall; 829 if (syscallNumber >= sSyscallVector.size()) { 830 fprintf(stderr, "%s: invalid syscall %" B_PRIu32 " attempted\n", 831 kCommandName, syscallNumber); 832 break; 833 } 834 Syscall* syscall = sSyscallVector[syscallNumber]; 835 836 if (stats) 837 record_syscall_stats(*syscall, message.post_syscall); 838 839 if (trace) { 840 print_syscall(outputFile, syscall, message.post_syscall, 841 memoryReader, printArguments, contentsFlags, 842 printReturnValues, colorize, decimalFormat, 843 currentThreadID); 844 } 845 break; 846 } 847 848 case B_DEBUGGER_MESSAGE_SIGNAL_RECEIVED: 849 { 850 if (traceSignal && trace) 851 print_signal(outputFile, message.signal_received, colorize); 852 break; 853 } 854 855 case B_DEBUGGER_MESSAGE_THREAD_DEBUGGED: 856 case B_DEBUGGER_MESSAGE_DEBUGGER_CALL: 857 case B_DEBUGGER_MESSAGE_BREAKPOINT_HIT: 858 case B_DEBUGGER_MESSAGE_WATCHPOINT_HIT: 859 case B_DEBUGGER_MESSAGE_SINGLE_STEP: 860 case B_DEBUGGER_MESSAGE_EXCEPTION_OCCURRED: 861 case B_DEBUGGER_MESSAGE_THREAD_CREATED: 862 case B_DEBUGGER_MESSAGE_THREAD_DELETED: 863 case B_DEBUGGER_MESSAGE_IMAGE_CREATED: 864 case B_DEBUGGER_MESSAGE_IMAGE_DELETED: 865 break; 866 867 case B_DEBUGGER_MESSAGE_TEAM_CREATED: 868 { 869 if (!traceChildTeams) 870 break; 871 872 Team* team = new(std::nothrow) Team( 873 message.team_created.new_team); 874 if (team == NULL) { 875 fprintf(stderr, "%s: Out of memory!\n", kCommandName); 876 break; 877 } 878 879 status_t error = team->InstallDebugger(debuggerPort, true, true, 880 traceSignal); 881 if (error != B_OK) { 882 delete team; 883 break; 884 } 885 886 debuggedTeams[team->ID()] = team; 887 break; 888 } 889 890 case B_DEBUGGER_MESSAGE_TEAM_DELETED: 891 { 892 // a debugged team is gone 893 TeamMap::iterator it = debuggedTeams.find(message.origin.team); 894 if (it == debuggedTeams.end()) 895 break; 896 897 Team* team = it->second; 898 debuggedTeams.erase(it); 899 delete team; 900 901 // if all debugged teams are gone, we're done 902 quitLoop = debuggedTeams.empty(); 903 break; 904 } 905 } 906 907 if (quitLoop) 908 break; 909 910 // tell the thread to continue (only when there is a thread and the 911 // message was synchronous) 912 if (message.origin.thread >= 0 && message.origin.nub_port >= 0) { 913 if (continue_thread(message.origin.nub_port, 914 message.origin.thread) != B_OK) { 915 // the team can already be gone 916 } 917 } 918 } 919 920 if (stats) { 921 // Dump recorded statistics 922 print_stats(outputFile); 923 } 924 925 if (outputFile != NULL && outputFile != stdout) 926 fclose(outputFile); 927 928 return 0; 929 } 930