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