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