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