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