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