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