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