atrace.cpp revision 750aa9743c0c4c592213fbb39b8d328bd0075fd6
1/* 2 * Copyright (C) 2012 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17#include <errno.h> 18#include <fcntl.h> 19#include <getopt.h> 20#include <inttypes.h> 21#include <signal.h> 22#include <stdarg.h> 23#include <stdbool.h> 24#include <stdio.h> 25#include <stdlib.h> 26#include <sys/sendfile.h> 27#include <time.h> 28#include <zlib.h> 29 30#include <binder/IBinder.h> 31#include <binder/IServiceManager.h> 32#include <binder/Parcel.h> 33 34#include <cutils/properties.h> 35 36#include <utils/String8.h> 37#include <utils/Trace.h> 38 39using namespace android; 40 41#define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0]))) 42 43enum { MAX_SYS_FILES = 8 }; 44 45const char* k_traceTagsProperty = "debug.atrace.tags.enableflags"; 46const char* k_traceAppCmdlineProperty = "debug.atrace.app_cmdlines"; 47 48typedef enum { OPT, REQ } requiredness ; 49 50struct TracingCategory { 51 // The name identifying the category. 52 const char* name; 53 54 // A longer description of the category. 55 const char* longname; 56 57 // The userland tracing tags that the category enables. 58 uint64_t tags; 59 60 // The fname==NULL terminated list of /sys/ files that the category 61 // enables. 62 struct { 63 // Whether the file must be writable in order to enable the tracing 64 // category. 65 requiredness required; 66 67 // The path to the enable file. 68 const char* path; 69 } sysfiles[MAX_SYS_FILES]; 70}; 71 72/* Tracing categories */ 73static const TracingCategory k_categories[] = { 74 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, { } }, 75 { "input", "Input", ATRACE_TAG_INPUT, { } }, 76 { "view", "View System", ATRACE_TAG_VIEW, { } }, 77 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } }, 78 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } }, 79 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } }, 80 { "audio", "Audio", ATRACE_TAG_AUDIO, { } }, 81 { "video", "Video", ATRACE_TAG_VIDEO, { } }, 82 { "camera", "Camera", ATRACE_TAG_CAMERA, { } }, 83 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } }, 84 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } }, 85 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } }, 86 { "rs", "RenderScript", ATRACE_TAG_RS, { } }, 87 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } }, 88 { "sched", "CPU Scheduling", 0, { 89 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_switch/enable" }, 90 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_wakeup/enable" }, 91 } }, 92 { "freq", "CPU Frequency", 0, { 93 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_frequency/enable" }, 94 { OPT, "/sys/kernel/debug/tracing/events/power/clock_set_rate/enable" }, 95 } }, 96 { "membus", "Memory Bus Utilization", 0, { 97 { REQ, "/sys/kernel/debug/tracing/events/memory_bus/enable" }, 98 } }, 99 { "idle", "CPU Idle", 0, { 100 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_idle/enable" }, 101 } }, 102 { "disk", "Disk I/O", 0, { 103 { REQ, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable" }, 104 { REQ, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable" }, 105 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" }, 106 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable" }, 107 } }, 108 { "mmc", "eMMC commands", 0, { 109 { REQ, "/sys/kernel/debug/tracing/events/mmc/enable" }, 110 } }, 111 { "load", "CPU Load", 0, { 112 { REQ, "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable" }, 113 } }, 114 { "sync", "Synchronization", 0, { 115 { REQ, "/sys/kernel/debug/tracing/events/sync/enable" }, 116 } }, 117 { "workq", "Kernel Workqueues", 0, { 118 { REQ, "/sys/kernel/debug/tracing/events/workqueue/enable" }, 119 } }, 120}; 121 122/* Command line options */ 123static int g_traceDurationSeconds = 5; 124static bool g_traceOverwrite = false; 125static int g_traceBufferSizeKB = 2048; 126static bool g_compress = false; 127static bool g_nohup = false; 128static int g_initialSleepSecs = 0; 129static const char* g_kernelTraceFuncs = NULL; 130static const char* g_debugAppCmdLine = ""; 131 132/* Global state */ 133static bool g_traceAborted = false; 134static bool g_categoryEnables[NELEM(k_categories)] = {}; 135 136/* Sys file paths */ 137static const char* k_traceClockPath = 138 "/sys/kernel/debug/tracing/trace_clock"; 139 140static const char* k_traceBufferSizePath = 141 "/sys/kernel/debug/tracing/buffer_size_kb"; 142 143static const char* k_tracingOverwriteEnablePath = 144 "/sys/kernel/debug/tracing/options/overwrite"; 145 146static const char* k_currentTracerPath = 147 "/sys/kernel/debug/tracing/current_tracer"; 148 149static const char* k_printTgidPath = 150 "/sys/kernel/debug/tracing/options/print-tgid"; 151 152static const char* k_funcgraphAbsTimePath = 153 "/sys/kernel/debug/tracing/options/funcgraph-abstime"; 154 155static const char* k_funcgraphCpuPath = 156 "/sys/kernel/debug/tracing/options/funcgraph-cpu"; 157 158static const char* k_funcgraphProcPath = 159 "/sys/kernel/debug/tracing/options/funcgraph-proc"; 160 161static const char* k_funcgraphFlatPath = 162 "/sys/kernel/debug/tracing/options/funcgraph-flat"; 163 164static const char* k_funcgraphDurationPath = 165 "/sys/kernel/debug/tracing/options/funcgraph-duration"; 166 167static const char* k_ftraceFilterPath = 168 "/sys/kernel/debug/tracing/set_ftrace_filter"; 169 170static const char* k_tracingOnPath = 171 "/sys/kernel/debug/tracing/tracing_on"; 172 173static const char* k_tracePath = 174 "/sys/kernel/debug/tracing/trace"; 175 176// Check whether a file exists. 177static bool fileExists(const char* filename) { 178 return access(filename, F_OK) != -1; 179} 180 181// Check whether a file is writable. 182static bool fileIsWritable(const char* filename) { 183 return access(filename, W_OK) != -1; 184} 185 186// Truncate a file. 187static bool truncateFile(const char* path) 188{ 189 // This uses creat rather than truncate because some of the debug kernel 190 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by 191 // calls to truncate, but they are cleared by calls to creat. 192 int traceFD = creat(path, 0); 193 if (traceFD == -1) { 194 fprintf(stderr, "error truncating %s: %s (%d)\n", path, 195 strerror(errno), errno); 196 return false; 197 } 198 199 close(traceFD); 200 201 return true; 202} 203 204static bool _writeStr(const char* filename, const char* str, int flags) 205{ 206 int fd = open(filename, flags); 207 if (fd == -1) { 208 fprintf(stderr, "error opening %s: %s (%d)\n", filename, 209 strerror(errno), errno); 210 return false; 211 } 212 213 bool ok = true; 214 ssize_t len = strlen(str); 215 if (write(fd, str, len) != len) { 216 fprintf(stderr, "error writing to %s: %s (%d)\n", filename, 217 strerror(errno), errno); 218 ok = false; 219 } 220 221 close(fd); 222 223 return ok; 224} 225 226// Write a string to a file, returning true if the write was successful. 227static bool writeStr(const char* filename, const char* str) 228{ 229 return _writeStr(filename, str, O_WRONLY); 230} 231 232// Append a string to a file, returning true if the write was successful. 233static bool appendStr(const char* filename, const char* str) 234{ 235 return _writeStr(filename, str, O_APPEND|O_WRONLY); 236} 237 238// Enable or disable a kernel option by writing a "1" or a "0" into a /sys 239// file. 240static bool setKernelOptionEnable(const char* filename, bool enable) 241{ 242 return writeStr(filename, enable ? "1" : "0"); 243} 244 245// Check whether the category is supported on the device with the current 246// rootness. A category is supported only if all its required /sys/ files are 247// writable and if enabling the category will enable one or more tracing tags 248// or /sys/ files. 249static bool isCategorySupported(const TracingCategory& category) 250{ 251 bool ok = category.tags != 0; 252 for (int i = 0; i < MAX_SYS_FILES; i++) { 253 const char* path = category.sysfiles[i].path; 254 bool req = category.sysfiles[i].required == REQ; 255 if (path != NULL) { 256 if (req) { 257 if (!fileIsWritable(path)) { 258 return false; 259 } else { 260 ok = true; 261 } 262 } else { 263 ok |= fileIsWritable(path); 264 } 265 } 266 } 267 return ok; 268} 269 270// Check whether the category would be supported on the device if the user 271// were root. This function assumes that root is able to write to any file 272// that exists. It performs the same logic as isCategorySupported, but it 273// uses file existance rather than writability in the /sys/ file checks. 274static bool isCategorySupportedForRoot(const TracingCategory& category) 275{ 276 bool ok = category.tags != 0; 277 for (int i = 0; i < MAX_SYS_FILES; i++) { 278 const char* path = category.sysfiles[i].path; 279 bool req = category.sysfiles[i].required == REQ; 280 if (path != NULL) { 281 if (req) { 282 if (!fileExists(path)) { 283 return false; 284 } else { 285 ok = true; 286 } 287 } else { 288 ok |= fileExists(path); 289 } 290 } 291 } 292 return ok; 293} 294 295// Enable or disable overwriting of the kernel trace buffers. Disabling this 296// will cause tracing to stop once the trace buffers have filled up. 297static bool setTraceOverwriteEnable(bool enable) 298{ 299 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable); 300} 301 302// Enable or disable kernel tracing. 303static bool setTracingEnabled(bool enable) 304{ 305 return setKernelOptionEnable(k_tracingOnPath, enable); 306} 307 308// Clear the contents of the kernel trace. 309static bool clearTrace() 310{ 311 return truncateFile(k_tracePath); 312} 313 314// Set the size of the kernel's trace buffer in kilobytes. 315static bool setTraceBufferSizeKB(int size) 316{ 317 char str[32] = "1"; 318 int len; 319 if (size < 1) { 320 size = 1; 321 } 322 snprintf(str, 32, "%d", size); 323 return writeStr(k_traceBufferSizePath, str); 324} 325 326// Enable or disable the kernel's use of the global clock. Disabling the global 327// clock will result in the kernel using a per-CPU local clock. 328static bool setGlobalClockEnable(bool enable) 329{ 330 return writeStr(k_traceClockPath, enable ? "global" : "local"); 331} 332 333static bool setPrintTgidEnableIfPresent(bool enable) 334{ 335 if (fileExists(k_printTgidPath)) { 336 return setKernelOptionEnable(k_printTgidPath, enable); 337 } 338 return true; 339} 340 341// Poke all the binder-enabled processes in the system to get them to re-read 342// their system properties. 343static bool pokeBinderServices() 344{ 345 sp<IServiceManager> sm = defaultServiceManager(); 346 Vector<String16> services = sm->listServices(); 347 for (size_t i = 0; i < services.size(); i++) { 348 sp<IBinder> obj = sm->checkService(services[i]); 349 if (obj != NULL) { 350 Parcel data; 351 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data, 352 NULL, 0) != OK) { 353 if (false) { 354 // XXX: For some reason this fails on tablets trying to 355 // poke the "phone" service. It's not clear whether some 356 // are expected to fail. 357 String8 svc(services[i]); 358 fprintf(stderr, "error poking binder service %s\n", 359 svc.string()); 360 return false; 361 } 362 } 363 } 364 } 365 return true; 366} 367 368// Set the trace tags that userland tracing uses, and poke the running 369// processes to pick up the new value. 370static bool setTagsProperty(uint64_t tags) 371{ 372 char buf[64]; 373 snprintf(buf, 64, "%#" PRIx64, tags); 374 if (property_set(k_traceTagsProperty, buf) < 0) { 375 fprintf(stderr, "error setting trace tags system property\n"); 376 return false; 377 } 378 return true; 379} 380 381// Set the system property that indicates which apps should perform 382// application-level tracing. 383static bool setAppCmdlineProperty(const char* cmdline) 384{ 385 if (property_set(k_traceAppCmdlineProperty, cmdline) < 0) { 386 fprintf(stderr, "error setting trace app system property\n"); 387 return false; 388 } 389 return true; 390} 391 392// Disable all /sys/ enable files. 393static bool disableKernelTraceEvents() { 394 bool ok = true; 395 for (int i = 0; i < NELEM(k_categories); i++) { 396 const TracingCategory &c = k_categories[i]; 397 for (int j = 0; j < MAX_SYS_FILES; j++) { 398 const char* path = c.sysfiles[j].path; 399 if (path != NULL && fileIsWritable(path)) { 400 ok &= setKernelOptionEnable(path, false); 401 } 402 } 403 } 404 return ok; 405} 406 407// Verify that the comma separated list of functions are being traced by the 408// kernel. 409static bool verifyKernelTraceFuncs(const char* funcs) 410{ 411 int fd = open(k_ftraceFilterPath, O_RDONLY); 412 if (fd == -1) { 413 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath, 414 strerror(errno), errno); 415 return false; 416 } 417 418 char buf[4097]; 419 ssize_t n = read(fd, buf, 4096); 420 close(fd); 421 if (n == -1) { 422 fprintf(stderr, "error reading %s: %s (%d)\n", k_ftraceFilterPath, 423 strerror(errno), errno); 424 return false; 425 } 426 427 buf[n] = '\0'; 428 String8 funcList = String8::format("\n%s", buf); 429 430 // Make sure that every function listed in funcs is in the list we just 431 // read from the kernel. 432 bool ok = true; 433 char* myFuncs = strdup(funcs); 434 char* func = strtok(myFuncs, ","); 435 while (func) { 436 String8 fancyFunc = String8::format("\n%s\n", func); 437 bool found = funcList.find(fancyFunc.string(), 0) >= 0; 438 if (!found || func[0] == '\0') { 439 fprintf(stderr, "error: \"%s\" is not a valid kernel function " 440 "to trace.\n", func); 441 ok = false; 442 } 443 func = strtok(NULL, ","); 444 } 445 free(myFuncs); 446 447 return ok; 448} 449 450// Set the comma separated list of functions that the kernel is to trace. 451static bool setKernelTraceFuncs(const char* funcs) 452{ 453 bool ok = true; 454 455 if (funcs == NULL || funcs[0] == '\0') { 456 // Disable kernel function tracing. 457 if (fileIsWritable(k_currentTracerPath)) { 458 ok &= writeStr(k_currentTracerPath, "nop"); 459 } 460 if (fileIsWritable(k_ftraceFilterPath)) { 461 ok &= truncateFile(k_ftraceFilterPath); 462 } 463 } else { 464 // Enable kernel function tracing. 465 ok &= writeStr(k_currentTracerPath, "function_graph"); 466 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true); 467 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true); 468 ok &= setKernelOptionEnable(k_funcgraphProcPath, true); 469 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true); 470 471 // Set the requested filter functions. 472 ok &= truncateFile(k_ftraceFilterPath); 473 char* myFuncs = strdup(funcs); 474 char* func = strtok(myFuncs, ","); 475 while (func) { 476 ok &= appendStr(k_ftraceFilterPath, func); 477 func = strtok(NULL, ","); 478 } 479 free(myFuncs); 480 481 // Verify that the set functions are being traced. 482 if (ok) { 483 ok &= verifyKernelTraceFuncs(funcs); 484 } 485 } 486 487 return ok; 488} 489 490// Set all the kernel tracing settings to the desired state for this trace 491// capture. 492static bool setUpTrace() 493{ 494 bool ok = true; 495 496 // Set up the tracing options. 497 ok &= setTraceOverwriteEnable(g_traceOverwrite); 498 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB); 499 ok &= setGlobalClockEnable(true); 500 ok &= setPrintTgidEnableIfPresent(true); 501 ok &= setKernelTraceFuncs(g_kernelTraceFuncs); 502 503 // Set up the tags property. 504 uint64_t tags = 0; 505 for (int i = 0; i < NELEM(k_categories); i++) { 506 if (g_categoryEnables[i]) { 507 const TracingCategory &c = k_categories[i]; 508 tags |= c.tags; 509 } 510 } 511 ok &= setTagsProperty(tags); 512 ok &= setAppCmdlineProperty(g_debugAppCmdLine); 513 ok &= pokeBinderServices(); 514 515 // Disable all the sysfs enables. This is done as a separate loop from 516 // the enables to allow the same enable to exist in multiple categories. 517 ok &= disableKernelTraceEvents(); 518 519 // Enable all the sysfs enables that are in an enabled category. 520 for (int i = 0; i < NELEM(k_categories); i++) { 521 if (g_categoryEnables[i]) { 522 const TracingCategory &c = k_categories[i]; 523 for (int j = 0; j < MAX_SYS_FILES; j++) { 524 const char* path = c.sysfiles[j].path; 525 bool required = c.sysfiles[j].required == REQ; 526 if (path != NULL) { 527 if (fileIsWritable(path)) { 528 ok &= setKernelOptionEnable(path, true); 529 } else if (required) { 530 fprintf(stderr, "error writing file %s\n", path); 531 ok = false; 532 } 533 } 534 } 535 } 536 } 537 538 return ok; 539} 540 541// Reset all the kernel tracing settings to their default state. 542static void cleanUpTrace() 543{ 544 // Disable all tracing that we're able to. 545 disableKernelTraceEvents(); 546 547 // Reset the system properties. 548 setTagsProperty(0); 549 setAppCmdlineProperty(""); 550 pokeBinderServices(); 551 552 // Set the options back to their defaults. 553 setTraceOverwriteEnable(true); 554 setTraceBufferSizeKB(1); 555 setGlobalClockEnable(false); 556 setPrintTgidEnableIfPresent(false); 557 setKernelTraceFuncs(NULL); 558} 559 560 561// Enable tracing in the kernel. 562static bool startTrace() 563{ 564 return setTracingEnabled(true); 565} 566 567// Disable tracing in the kernel. 568static void stopTrace() 569{ 570 setTracingEnabled(false); 571} 572 573// Read the current kernel trace and write it to stdout. 574static void dumpTrace() 575{ 576 int traceFD = open(k_tracePath, O_RDWR); 577 if (traceFD == -1) { 578 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath, 579 strerror(errno), errno); 580 return; 581 } 582 583 if (g_compress) { 584 z_stream zs; 585 uint8_t *in, *out; 586 int result, flush; 587 588 bzero(&zs, sizeof(zs)); 589 result = deflateInit(&zs, Z_DEFAULT_COMPRESSION); 590 if (result != Z_OK) { 591 fprintf(stderr, "error initializing zlib: %d\n", result); 592 close(traceFD); 593 return; 594 } 595 596 const size_t bufSize = 64*1024; 597 in = (uint8_t*)malloc(bufSize); 598 out = (uint8_t*)malloc(bufSize); 599 flush = Z_NO_FLUSH; 600 601 zs.next_out = out; 602 zs.avail_out = bufSize; 603 604 do { 605 606 if (zs.avail_in == 0) { 607 // More input is needed. 608 result = read(traceFD, in, bufSize); 609 if (result < 0) { 610 fprintf(stderr, "error reading trace: %s (%d)\n", 611 strerror(errno), errno); 612 result = Z_STREAM_END; 613 break; 614 } else if (result == 0) { 615 flush = Z_FINISH; 616 } else { 617 zs.next_in = in; 618 zs.avail_in = result; 619 } 620 } 621 622 if (zs.avail_out == 0) { 623 // Need to write the output. 624 result = write(STDOUT_FILENO, out, bufSize); 625 if ((size_t)result < bufSize) { 626 fprintf(stderr, "error writing deflated trace: %s (%d)\n", 627 strerror(errno), errno); 628 result = Z_STREAM_END; // skip deflate error message 629 zs.avail_out = bufSize; // skip the final write 630 break; 631 } 632 zs.next_out = out; 633 zs.avail_out = bufSize; 634 } 635 636 } while ((result = deflate(&zs, flush)) == Z_OK); 637 638 if (result != Z_STREAM_END) { 639 fprintf(stderr, "error deflating trace: %s\n", zs.msg); 640 } 641 642 if (zs.avail_out < bufSize) { 643 size_t bytes = bufSize - zs.avail_out; 644 result = write(STDOUT_FILENO, out, bytes); 645 if ((size_t)result < bytes) { 646 fprintf(stderr, "error writing deflated trace: %s (%d)\n", 647 strerror(errno), errno); 648 } 649 } 650 651 result = deflateEnd(&zs); 652 if (result != Z_OK) { 653 fprintf(stderr, "error cleaning up zlib: %d\n", result); 654 } 655 656 free(in); 657 free(out); 658 } else { 659 ssize_t sent = 0; 660 while ((sent = sendfile(STDOUT_FILENO, traceFD, NULL, 64*1024*1024)) > 0); 661 if (sent == -1) { 662 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno), 663 errno); 664 } 665 } 666 667 close(traceFD); 668} 669 670static void handleSignal(int /*signo*/) 671{ 672 if (!g_nohup) { 673 g_traceAborted = true; 674 } 675} 676 677static void registerSigHandler() 678{ 679 struct sigaction sa; 680 sigemptyset(&sa.sa_mask); 681 sa.sa_flags = 0; 682 sa.sa_handler = handleSignal; 683 sigaction(SIGHUP, &sa, NULL); 684 sigaction(SIGINT, &sa, NULL); 685 sigaction(SIGQUIT, &sa, NULL); 686 sigaction(SIGTERM, &sa, NULL); 687} 688 689static bool setCategoryEnable(const char* name, bool enable) 690{ 691 for (int i = 0; i < NELEM(k_categories); i++) { 692 const TracingCategory& c = k_categories[i]; 693 if (strcmp(name, c.name) == 0) { 694 if (isCategorySupported(c)) { 695 g_categoryEnables[i] = enable; 696 return true; 697 } else { 698 if (isCategorySupportedForRoot(c)) { 699 fprintf(stderr, "error: category \"%s\" requires root " 700 "privileges.\n", name); 701 } else { 702 fprintf(stderr, "error: category \"%s\" is not supported " 703 "on this device.\n", name); 704 } 705 return false; 706 } 707 } 708 } 709 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name); 710 return false; 711} 712 713static void listSupportedCategories() 714{ 715 for (int i = 0; i < NELEM(k_categories); i++) { 716 const TracingCategory& c = k_categories[i]; 717 if (isCategorySupported(c)) { 718 printf(" %10s - %s\n", c.name, c.longname); 719 } 720 } 721} 722 723// Print the command usage help to stderr. 724static void showHelp(const char *cmd) 725{ 726 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd); 727 fprintf(stderr, "options include:\n" 728 " -a appname enable app-level tracing for a comma " 729 "separated list of cmdlines\n" 730 " -b N use a trace buffer size of N KB\n" 731 " -c trace into a circular buffer\n" 732 " -k fname,... trace the listed kernel functions\n" 733 " -n ignore signals\n" 734 " -s N sleep for N seconds before tracing [default 0]\n" 735 " -t N trace for N seconds [defualt 5]\n" 736 " -z compress the trace dump\n" 737 " --async_start start circular trace and return immediatly\n" 738 " --async_dump dump the current contents of circular trace buffer\n" 739 " --async_stop stop tracing and dump the current contents of circular\n" 740 " trace buffer\n" 741 " --list_categories\n" 742 " list the available tracing categories\n" 743 ); 744} 745 746int main(int argc, char **argv) 747{ 748 bool async = false; 749 bool traceStart = true; 750 bool traceStop = true; 751 bool traceDump = true; 752 753 if (argc == 2 && 0 == strcmp(argv[1], "--help")) { 754 showHelp(argv[0]); 755 exit(0); 756 } 757 758 for (;;) { 759 int ret; 760 int option_index = 0; 761 static struct option long_options[] = { 762 {"async_start", no_argument, 0, 0 }, 763 {"async_stop", no_argument, 0, 0 }, 764 {"async_dump", no_argument, 0, 0 }, 765 {"list_categories", no_argument, 0, 0 }, 766 { 0, 0, 0, 0 } 767 }; 768 769 ret = getopt_long(argc, argv, "a:b:ck:ns:t:z", 770 long_options, &option_index); 771 772 if (ret < 0) { 773 for (int i = optind; i < argc; i++) { 774 if (!setCategoryEnable(argv[i], true)) { 775 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]); 776 exit(1); 777 } 778 } 779 break; 780 } 781 782 switch(ret) { 783 case 'a': 784 g_debugAppCmdLine = optarg; 785 break; 786 787 case 'b': 788 g_traceBufferSizeKB = atoi(optarg); 789 break; 790 791 case 'c': 792 g_traceOverwrite = true; 793 break; 794 795 case 'k': 796 g_kernelTraceFuncs = optarg; 797 break; 798 799 case 'n': 800 g_nohup = true; 801 break; 802 803 case 's': 804 g_initialSleepSecs = atoi(optarg); 805 break; 806 807 case 't': 808 g_traceDurationSeconds = atoi(optarg); 809 break; 810 811 case 'z': 812 g_compress = true; 813 break; 814 815 case 0: 816 if (!strcmp(long_options[option_index].name, "async_start")) { 817 async = true; 818 traceStop = false; 819 traceDump = false; 820 g_traceOverwrite = true; 821 } else if (!strcmp(long_options[option_index].name, "async_stop")) { 822 async = true; 823 traceStop = false; 824 } else if (!strcmp(long_options[option_index].name, "async_dump")) { 825 async = true; 826 traceStart = false; 827 traceStop = false; 828 } else if (!strcmp(long_options[option_index].name, "list_categories")) { 829 listSupportedCategories(); 830 exit(0); 831 } 832 break; 833 834 default: 835 fprintf(stderr, "\n"); 836 showHelp(argv[0]); 837 exit(-1); 838 break; 839 } 840 } 841 842 registerSigHandler(); 843 844 if (g_initialSleepSecs > 0) { 845 sleep(g_initialSleepSecs); 846 } 847 848 bool ok = true; 849 ok &= setUpTrace(); 850 ok &= startTrace(); 851 852 if (ok && traceStart) { 853 printf("capturing trace..."); 854 fflush(stdout); 855 856 // We clear the trace after starting it because tracing gets enabled for 857 // each CPU individually in the kernel. Having the beginning of the trace 858 // contain entries from only one CPU can cause "begin" entries without a 859 // matching "end" entry to show up if a task gets migrated from one CPU to 860 // another. 861 ok = clearTrace(); 862 863 if (ok && !async) { 864 // Sleep to allow the trace to be captured. 865 struct timespec timeLeft; 866 timeLeft.tv_sec = g_traceDurationSeconds; 867 timeLeft.tv_nsec = 0; 868 do { 869 if (g_traceAborted) { 870 break; 871 } 872 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR); 873 } 874 } 875 876 // Stop the trace and restore the default settings. 877 if (traceStop) 878 stopTrace(); 879 880 if (ok && traceDump) { 881 if (!g_traceAborted) { 882 printf(" done\nTRACE:\n"); 883 fflush(stdout); 884 dumpTrace(); 885 } else { 886 printf("\ntrace aborted.\n"); 887 fflush(stdout); 888 } 889 clearTrace(); 890 } else if (!ok) { 891 fprintf(stderr, "unable to start tracing\n"); 892 } 893 894 // Reset the trace buffer size to 1. 895 if (traceStop) 896 cleanUpTrace(); 897 898 return g_traceAborted ? 1 : 0; 899} 900