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