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