atrace.cpp revision c545a3ae0b89766194ab4d7380dfc5cccaa4d5be
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.
554    bool ok = true;
555    char* myFuncs = strdup(funcs);
556    char* func = strtok(myFuncs, ",");
557    while (func) {
558        String8 fancyFunc = String8::format("\n%s\n", func);
559        bool found = funcList.find(fancyFunc.string(), 0) >= 0;
560        if (!found || func[0] == '\0') {
561            fprintf(stderr, "error: \"%s\" is not a valid kernel function "
562                "to trace.\n", func);
563            ok = false;
564        }
565        func = strtok(NULL, ",");
566    }
567    free(myFuncs);
568
569    return ok;
570}
571
572// Set the comma separated list of functions that the kernel is to trace.
573static bool setKernelTraceFuncs(const char* funcs)
574{
575    bool ok = true;
576
577    if (funcs == NULL || funcs[0] == '\0') {
578        // Disable kernel function tracing.
579        if (fileIsWritable(k_currentTracerPath)) {
580            ok &= writeStr(k_currentTracerPath, "nop");
581        }
582        if (fileIsWritable(k_ftraceFilterPath)) {
583            ok &= truncateFile(k_ftraceFilterPath);
584        }
585    } else {
586        // Enable kernel function tracing.
587        ok &= writeStr(k_currentTracerPath, "function_graph");
588        ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
589        ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
590        ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
591        ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
592
593        // Set the requested filter functions.
594        ok &= truncateFile(k_ftraceFilterPath);
595        char* myFuncs = strdup(funcs);
596        char* func = strtok(myFuncs, ",");
597        while (func) {
598            ok &= appendStr(k_ftraceFilterPath, func);
599            func = strtok(NULL, ",");
600        }
601        free(myFuncs);
602
603        // Verify that the set functions are being traced.
604        if (ok) {
605            ok &= verifyKernelTraceFuncs(funcs);
606        }
607    }
608
609    return ok;
610}
611
612static bool setCategoryEnable(const char* name, bool enable)
613{
614    for (int i = 0; i < NELEM(k_categories); i++) {
615        const TracingCategory& c = k_categories[i];
616        if (strcmp(name, c.name) == 0) {
617            if (isCategorySupported(c)) {
618                g_categoryEnables[i] = enable;
619                return true;
620            } else {
621                if (isCategorySupportedForRoot(c)) {
622                    fprintf(stderr, "error: category \"%s\" requires root "
623                            "privileges.\n", name);
624                } else {
625                    fprintf(stderr, "error: category \"%s\" is not supported "
626                            "on this device.\n", name);
627                }
628                return false;
629            }
630        }
631    }
632    fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
633    return false;
634}
635
636static bool setCategoriesEnableFromFile(const char* categories_file)
637{
638    if (!categories_file) {
639        return true;
640    }
641    Tokenizer* tokenizer = NULL;
642    if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
643        return false;
644    }
645    bool ok = true;
646    while (!tokenizer->isEol()) {
647        String8 token = tokenizer->nextToken(" ");
648        if (token.isEmpty()) {
649            tokenizer->skipDelimiters(" ");
650            continue;
651        }
652        ok &= setCategoryEnable(token.string(), true);
653    }
654    delete tokenizer;
655    return ok;
656}
657
658// Set all the kernel tracing settings to the desired state for this trace
659// capture.
660static bool setUpTrace()
661{
662    bool ok = true;
663
664    // Set up the tracing options.
665    ok &= setCategoriesEnableFromFile(g_categoriesFile);
666    ok &= setTraceOverwriteEnable(g_traceOverwrite);
667    ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
668    ok &= setGlobalClockEnable(true);
669    ok &= setPrintTgidEnableIfPresent(true);
670    ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
671
672    // Set up the tags property.
673    uint64_t tags = 0;
674    for (int i = 0; i < NELEM(k_categories); i++) {
675        if (g_categoryEnables[i]) {
676            const TracingCategory &c = k_categories[i];
677            tags |= c.tags;
678        }
679    }
680    ok &= setTagsProperty(tags);
681    ok &= setAppCmdlineProperty(g_debugAppCmdLine);
682    ok &= pokeBinderServices();
683
684    // Disable all the sysfs enables.  This is done as a separate loop from
685    // the enables to allow the same enable to exist in multiple categories.
686    ok &= disableKernelTraceEvents();
687
688    // Enable all the sysfs enables that are in an enabled category.
689    for (int i = 0; i < NELEM(k_categories); i++) {
690        if (g_categoryEnables[i]) {
691            const TracingCategory &c = k_categories[i];
692            for (int j = 0; j < MAX_SYS_FILES; j++) {
693                const char* path = c.sysfiles[j].path;
694                bool required = c.sysfiles[j].required == REQ;
695                if (path != NULL) {
696                    if (fileIsWritable(path)) {
697                        ok &= setKernelOptionEnable(path, true);
698                    } else if (required) {
699                        fprintf(stderr, "error writing file %s\n", path);
700                        ok = false;
701                    }
702                }
703            }
704        }
705    }
706
707    return ok;
708}
709
710// Reset all the kernel tracing settings to their default state.
711static void cleanUpTrace()
712{
713    // Disable all tracing that we're able to.
714    disableKernelTraceEvents();
715
716    // Reset the system properties.
717    setTagsProperty(0);
718    setAppCmdlineProperty("");
719    pokeBinderServices();
720
721    // Set the options back to their defaults.
722    setTraceOverwriteEnable(true);
723    setTraceBufferSizeKB(1);
724    setGlobalClockEnable(false);
725    setPrintTgidEnableIfPresent(false);
726    setKernelTraceFuncs(NULL);
727}
728
729
730// Enable tracing in the kernel.
731static bool startTrace()
732{
733    return setTracingEnabled(true);
734}
735
736// Disable tracing in the kernel.
737static void stopTrace()
738{
739    setTracingEnabled(false);
740}
741
742// Read data from the tracing pipe and forward to stdout
743static void streamTrace()
744{
745    char trace_data[4096];
746    int traceFD = open(k_traceStreamPath, O_RDWR);
747    if (traceFD == -1) {
748        fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
749                strerror(errno), errno);
750        return;
751    }
752    while (!g_traceAborted) {
753        ssize_t bytes_read = read(traceFD, trace_data, 4096);
754        if (bytes_read > 0) {
755            write(STDOUT_FILENO, trace_data, bytes_read);
756            fflush(stdout);
757        } else {
758            if (!g_traceAborted) {
759                fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
760                        bytes_read, errno, strerror(errno));
761            }
762            break;
763        }
764    }
765}
766
767// Read the current kernel trace and write it to stdout.
768static void dumpTrace()
769{
770    int traceFD = open(k_tracePath, O_RDWR);
771    if (traceFD == -1) {
772        fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
773                strerror(errno), errno);
774        return;
775    }
776
777    if (g_compress) {
778        z_stream zs;
779        uint8_t *in, *out;
780        int result, flush;
781
782        memset(&zs, 0, sizeof(zs));
783        result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
784        if (result != Z_OK) {
785            fprintf(stderr, "error initializing zlib: %d\n", result);
786            close(traceFD);
787            return;
788        }
789
790        const size_t bufSize = 64*1024;
791        in = (uint8_t*)malloc(bufSize);
792        out = (uint8_t*)malloc(bufSize);
793        flush = Z_NO_FLUSH;
794
795        zs.next_out = out;
796        zs.avail_out = bufSize;
797
798        do {
799
800            if (zs.avail_in == 0) {
801                // More input is needed.
802                result = read(traceFD, in, bufSize);
803                if (result < 0) {
804                    fprintf(stderr, "error reading trace: %s (%d)\n",
805                            strerror(errno), errno);
806                    result = Z_STREAM_END;
807                    break;
808                } else if (result == 0) {
809                    flush = Z_FINISH;
810                } else {
811                    zs.next_in = in;
812                    zs.avail_in = result;
813                }
814            }
815
816            if (zs.avail_out == 0) {
817                // Need to write the output.
818                result = write(STDOUT_FILENO, out, bufSize);
819                if ((size_t)result < bufSize) {
820                    fprintf(stderr, "error writing deflated trace: %s (%d)\n",
821                            strerror(errno), errno);
822                    result = Z_STREAM_END; // skip deflate error message
823                    zs.avail_out = bufSize; // skip the final write
824                    break;
825                }
826                zs.next_out = out;
827                zs.avail_out = bufSize;
828            }
829
830        } while ((result = deflate(&zs, flush)) == Z_OK);
831
832        if (result != Z_STREAM_END) {
833            fprintf(stderr, "error deflating trace: %s\n", zs.msg);
834        }
835
836        if (zs.avail_out < bufSize) {
837            size_t bytes = bufSize - zs.avail_out;
838            result = write(STDOUT_FILENO, out, bytes);
839            if ((size_t)result < bytes) {
840                fprintf(stderr, "error writing deflated trace: %s (%d)\n",
841                        strerror(errno), errno);
842            }
843        }
844
845        result = deflateEnd(&zs);
846        if (result != Z_OK) {
847            fprintf(stderr, "error cleaning up zlib: %d\n", result);
848        }
849
850        free(in);
851        free(out);
852    } else {
853        ssize_t sent = 0;
854        while ((sent = sendfile(STDOUT_FILENO, traceFD, NULL, 64*1024*1024)) > 0);
855        if (sent == -1) {
856            fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
857                    errno);
858        }
859    }
860
861    close(traceFD);
862}
863
864static void handleSignal(int /*signo*/)
865{
866    if (!g_nohup) {
867        g_traceAborted = true;
868    }
869}
870
871static void registerSigHandler()
872{
873    struct sigaction sa;
874    sigemptyset(&sa.sa_mask);
875    sa.sa_flags = 0;
876    sa.sa_handler = handleSignal;
877    sigaction(SIGHUP, &sa, NULL);
878    sigaction(SIGINT, &sa, NULL);
879    sigaction(SIGQUIT, &sa, NULL);
880    sigaction(SIGTERM, &sa, NULL);
881}
882
883static void listSupportedCategories()
884{
885    for (int i = 0; i < NELEM(k_categories); i++) {
886        const TracingCategory& c = k_categories[i];
887        if (isCategorySupported(c)) {
888            printf("  %10s - %s\n", c.name, c.longname);
889        }
890    }
891}
892
893// Print the command usage help to stderr.
894static void showHelp(const char *cmd)
895{
896    fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
897    fprintf(stderr, "options include:\n"
898                    "  -a appname      enable app-level tracing for a comma "
899                        "separated list of cmdlines\n"
900                    "  -b N            use a trace buffer size of N KB\n"
901                    "  -c              trace into a circular buffer\n"
902                    "  -f filename     use the categories written in a file as space-separated\n"
903                    "                    values in a line\n"
904                    "  -k fname,...    trace the listed kernel functions\n"
905                    "  -n              ignore signals\n"
906                    "  -s N            sleep for N seconds before tracing [default 0]\n"
907                    "  -t N            trace for N seconds [defualt 5]\n"
908                    "  -z              compress the trace dump\n"
909                    "  --async_start   start circular trace and return immediatly\n"
910                    "  --async_dump    dump the current contents of circular trace buffer\n"
911                    "  --async_stop    stop tracing and dump the current contents of circular\n"
912                    "                    trace buffer\n"
913                    "  --stream        stream trace to stdout as it enters the trace buffer\n"
914                    "                    Note: this can take significant CPU time, and is best\n"
915                    "                    used for measuring things that are not affected by\n"
916                    "                    CPU performance, like pagecache usage.\n"
917                    "  --list_categories\n"
918                    "                  list the available tracing categories\n"
919            );
920}
921
922int main(int argc, char **argv)
923{
924    bool async = false;
925    bool traceStart = true;
926    bool traceStop = true;
927    bool traceDump = true;
928    bool traceStream = false;
929
930    if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
931        showHelp(argv[0]);
932        exit(0);
933    }
934
935    for (;;) {
936        int ret;
937        int option_index = 0;
938        static struct option long_options[] = {
939            {"async_start",     no_argument, 0,  0 },
940            {"async_stop",      no_argument, 0,  0 },
941            {"async_dump",      no_argument, 0,  0 },
942            {"list_categories", no_argument, 0,  0 },
943            {"stream",          no_argument, 0,  0 },
944            {           0,                0, 0,  0 }
945        };
946
947        ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:z",
948                          long_options, &option_index);
949
950        if (ret < 0) {
951            for (int i = optind; i < argc; i++) {
952                if (!setCategoryEnable(argv[i], true)) {
953                    fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
954                    exit(1);
955                }
956            }
957            break;
958        }
959
960        switch(ret) {
961            case 'a':
962                g_debugAppCmdLine = optarg;
963            break;
964
965            case 'b':
966                g_traceBufferSizeKB = atoi(optarg);
967            break;
968
969            case 'c':
970                g_traceOverwrite = true;
971            break;
972
973            case 'f':
974                g_categoriesFile = optarg;
975            break;
976
977            case 'k':
978                g_kernelTraceFuncs = optarg;
979            break;
980
981            case 'n':
982                g_nohup = true;
983            break;
984
985            case 's':
986                g_initialSleepSecs = atoi(optarg);
987            break;
988
989            case 't':
990                g_traceDurationSeconds = atoi(optarg);
991            break;
992
993            case 'z':
994                g_compress = true;
995            break;
996
997            case 0:
998                if (!strcmp(long_options[option_index].name, "async_start")) {
999                    async = true;
1000                    traceStop = false;
1001                    traceDump = false;
1002                    g_traceOverwrite = true;
1003                } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1004                    async = true;
1005                    traceStart = false;
1006                } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1007                    async = true;
1008                    traceStart = false;
1009                    traceStop = false;
1010                } else if (!strcmp(long_options[option_index].name, "stream")) {
1011                    traceStream = true;
1012                    traceDump = false;
1013                } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1014                    listSupportedCategories();
1015                    exit(0);
1016                }
1017            break;
1018
1019            default:
1020                fprintf(stderr, "\n");
1021                showHelp(argv[0]);
1022                exit(-1);
1023            break;
1024        }
1025    }
1026
1027    registerSigHandler();
1028
1029    if (g_initialSleepSecs > 0) {
1030        sleep(g_initialSleepSecs);
1031    }
1032
1033    bool ok = true;
1034    ok &= setUpTrace();
1035    ok &= startTrace();
1036
1037    if (ok && traceStart) {
1038        if (!traceStream) {
1039            printf("capturing trace...");
1040            fflush(stdout);
1041        }
1042
1043        // We clear the trace after starting it because tracing gets enabled for
1044        // each CPU individually in the kernel. Having the beginning of the trace
1045        // contain entries from only one CPU can cause "begin" entries without a
1046        // matching "end" entry to show up if a task gets migrated from one CPU to
1047        // another.
1048        ok = clearTrace();
1049
1050        writeClockSyncMarker();
1051        if (ok && !async && !traceStream) {
1052            // Sleep to allow the trace to be captured.
1053            struct timespec timeLeft;
1054            timeLeft.tv_sec = g_traceDurationSeconds;
1055            timeLeft.tv_nsec = 0;
1056            do {
1057                if (g_traceAborted) {
1058                    break;
1059                }
1060            } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1061        }
1062
1063        if (traceStream) {
1064            streamTrace();
1065        }
1066    }
1067
1068    // Stop the trace and restore the default settings.
1069    if (traceStop)
1070        stopTrace();
1071
1072    if (ok && traceDump) {
1073        if (!g_traceAborted) {
1074            printf(" done\nTRACE:\n");
1075            fflush(stdout);
1076            dumpTrace();
1077        } else {
1078            printf("\ntrace aborted.\n");
1079            fflush(stdout);
1080        }
1081        clearTrace();
1082    } else if (!ok) {
1083        fprintf(stderr, "unable to start tracing\n");
1084    }
1085
1086    // Reset the trace buffer size to 1.
1087    if (traceStop)
1088        cleanUpTrace();
1089
1090    return g_traceAborted ? 1 : 0;
1091}
1092