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