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