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