blob: 8fd80cc02297193e0f80aefa6efc997d4a46b6e2 [file] [log] [blame]
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001/*
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>
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070020#include <inttypes.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080021#include <signal.h>
22#include <stdarg.h>
23#include <stdbool.h>
24#include <stdio.h>
25#include <stdlib.h>
Elliott Hughes3da5d232015-01-25 08:35:20 -080026#include <string.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080027#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/Trace.h>
39
40using namespace android;
41
42#define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0])))
43
Mohamad Ayyash26dbcbe2014-04-08 15:24:11 -070044enum { MAX_SYS_FILES = 10 };
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080045
46const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
Jamie Gennisf7f29c82013-03-27 15:50:58 -070047const char* k_traceAppCmdlineProperty = "debug.atrace.app_cmdlines";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080048
49typedef enum { OPT, REQ } requiredness ;
50
51struct TracingCategory {
52 // The name identifying the category.
53 const char* name;
54
55 // A longer description of the category.
56 const char* longname;
57
58 // The userland tracing tags that the category enables.
59 uint64_t tags;
60
61 // The fname==NULL terminated list of /sys/ files that the category
62 // enables.
63 struct {
64 // Whether the file must be writable in order to enable the tracing
65 // category.
66 requiredness required;
67
68 // The path to the enable file.
69 const char* path;
70 } sysfiles[MAX_SYS_FILES];
71};
72
73/* Tracing categories */
74static const TracingCategory k_categories[] = {
Jamie Gennisb2a89e32013-03-11 19:37:53 -070075 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, { } },
76 { "input", "Input", ATRACE_TAG_INPUT, { } },
77 { "view", "View System", ATRACE_TAG_VIEW, { } },
78 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
79 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
80 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -050081 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070082 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
83 { "video", "Video", ATRACE_TAG_VIDEO, { } },
84 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
85 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -070086 { "app", "Application", ATRACE_TAG_APP, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -070087 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -070088 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -070089 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -070090 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -070091 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070092 { "sched", "CPU Scheduling", 0, {
93 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_switch/enable" },
94 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_wakeup/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080095 } },
Dan Willemsenf440d392014-04-11 15:44:09 -070096 { "irq", "IRQ Events", 0, {
97 { REQ, "/sys/kernel/debug/tracing/events/irq/enable" },
98 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070099 { "freq", "CPU Frequency", 0, {
100 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_frequency/enable" },
101 { OPT, "/sys/kernel/debug/tracing/events/power/clock_set_rate/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800102 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700103 { "membus", "Memory Bus Utilization", 0, {
104 { REQ, "/sys/kernel/debug/tracing/events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800105 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700106 { "idle", "CPU Idle", 0, {
107 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800108 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700109 { "disk", "Disk I/O", 0, {
Greg Hackmanne80d32c2014-11-20 12:59:44 -0800110 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_enter/enable" },
111 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_exit/enable" },
112 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_begin/enable" },
113 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_end/enable" },
114 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_begin/enable" },
115 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_end/enable" },
116 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable" },
117 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable" },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700118 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" },
119 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800120 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700121 { "mmc", "eMMC commands", 0, {
122 { REQ, "/sys/kernel/debug/tracing/events/mmc/enable" },
123 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700124 { "load", "CPU Load", 0, {
125 { REQ, "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800126 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700127 { "sync", "Synchronization", 0, {
128 { REQ, "/sys/kernel/debug/tracing/events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800129 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700130 { "workq", "Kernel Workqueues", 0, {
131 { REQ, "/sys/kernel/debug/tracing/events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800132 } },
Colin Cross580407f2014-08-18 15:22:13 -0700133 { "memreclaim", "Kernel Memory Reclaim", 0, {
134 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
135 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
136 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_wake/enable" },
137 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_sleep/enable" },
138 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800139};
140
141/* Command line options */
142static int g_traceDurationSeconds = 5;
143static bool g_traceOverwrite = false;
144static int g_traceBufferSizeKB = 2048;
145static bool g_compress = false;
146static bool g_nohup = false;
147static int g_initialSleepSecs = 0;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700148static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700149static const char* g_debugAppCmdLine = "";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800150
151/* Global state */
152static bool g_traceAborted = false;
153static bool g_categoryEnables[NELEM(k_categories)] = {};
154
155/* Sys file paths */
156static const char* k_traceClockPath =
157 "/sys/kernel/debug/tracing/trace_clock";
158
159static const char* k_traceBufferSizePath =
160 "/sys/kernel/debug/tracing/buffer_size_kb";
161
162static const char* k_tracingOverwriteEnablePath =
163 "/sys/kernel/debug/tracing/options/overwrite";
164
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700165static const char* k_currentTracerPath =
166 "/sys/kernel/debug/tracing/current_tracer";
167
168static const char* k_printTgidPath =
169 "/sys/kernel/debug/tracing/options/print-tgid";
170
171static const char* k_funcgraphAbsTimePath =
172 "/sys/kernel/debug/tracing/options/funcgraph-abstime";
173
174static const char* k_funcgraphCpuPath =
175 "/sys/kernel/debug/tracing/options/funcgraph-cpu";
176
177static const char* k_funcgraphProcPath =
178 "/sys/kernel/debug/tracing/options/funcgraph-proc";
179
180static const char* k_funcgraphFlatPath =
181 "/sys/kernel/debug/tracing/options/funcgraph-flat";
182
183static const char* k_funcgraphDurationPath =
184 "/sys/kernel/debug/tracing/options/funcgraph-duration";
185
186static const char* k_ftraceFilterPath =
187 "/sys/kernel/debug/tracing/set_ftrace_filter";
188
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800189static const char* k_tracingOnPath =
190 "/sys/kernel/debug/tracing/tracing_on";
191
192static const char* k_tracePath =
193 "/sys/kernel/debug/tracing/trace";
194
195// Check whether a file exists.
196static bool fileExists(const char* filename) {
197 return access(filename, F_OK) != -1;
198}
199
200// Check whether a file is writable.
201static bool fileIsWritable(const char* filename) {
202 return access(filename, W_OK) != -1;
203}
204
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700205// Truncate a file.
206static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800207{
Jamie Gennis43122e72013-03-21 14:06:31 -0700208 // This uses creat rather than truncate because some of the debug kernel
209 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
210 // calls to truncate, but they are cleared by calls to creat.
211 int traceFD = creat(path, 0);
212 if (traceFD == -1) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700213 fprintf(stderr, "error truncating %s: %s (%d)\n", path,
Jamie Gennis43122e72013-03-21 14:06:31 -0700214 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700215 return false;
216 }
217
Jamie Gennis43122e72013-03-21 14:06:31 -0700218 close(traceFD);
219
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700220 return true;
221}
222
223static bool _writeStr(const char* filename, const char* str, int flags)
224{
225 int fd = open(filename, flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800226 if (fd == -1) {
227 fprintf(stderr, "error opening %s: %s (%d)\n", filename,
228 strerror(errno), errno);
229 return false;
230 }
231
232 bool ok = true;
233 ssize_t len = strlen(str);
234 if (write(fd, str, len) != len) {
235 fprintf(stderr, "error writing to %s: %s (%d)\n", filename,
236 strerror(errno), errno);
237 ok = false;
238 }
239
240 close(fd);
241
242 return ok;
243}
244
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700245// Write a string to a file, returning true if the write was successful.
246static bool writeStr(const char* filename, const char* str)
247{
248 return _writeStr(filename, str, O_WRONLY);
249}
250
251// Append a string to a file, returning true if the write was successful.
252static bool appendStr(const char* filename, const char* str)
253{
254 return _writeStr(filename, str, O_APPEND|O_WRONLY);
255}
256
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800257// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
258// file.
259static bool setKernelOptionEnable(const char* filename, bool enable)
260{
261 return writeStr(filename, enable ? "1" : "0");
262}
263
264// Check whether the category is supported on the device with the current
265// rootness. A category is supported only if all its required /sys/ files are
266// writable and if enabling the category will enable one or more tracing tags
267// or /sys/ files.
268static bool isCategorySupported(const TracingCategory& category)
269{
270 bool ok = category.tags != 0;
271 for (int i = 0; i < MAX_SYS_FILES; i++) {
272 const char* path = category.sysfiles[i].path;
273 bool req = category.sysfiles[i].required == REQ;
274 if (path != NULL) {
275 if (req) {
276 if (!fileIsWritable(path)) {
277 return false;
278 } else {
279 ok = true;
280 }
281 } else {
282 ok |= fileIsWritable(path);
283 }
284 }
285 }
286 return ok;
287}
288
289// Check whether the category would be supported on the device if the user
290// were root. This function assumes that root is able to write to any file
291// that exists. It performs the same logic as isCategorySupported, but it
292// uses file existance rather than writability in the /sys/ file checks.
293static bool isCategorySupportedForRoot(const TracingCategory& category)
294{
295 bool ok = category.tags != 0;
296 for (int i = 0; i < MAX_SYS_FILES; i++) {
297 const char* path = category.sysfiles[i].path;
298 bool req = category.sysfiles[i].required == REQ;
299 if (path != NULL) {
300 if (req) {
301 if (!fileExists(path)) {
302 return false;
303 } else {
304 ok = true;
305 }
306 } else {
307 ok |= fileExists(path);
308 }
309 }
310 }
311 return ok;
312}
313
314// Enable or disable overwriting of the kernel trace buffers. Disabling this
315// will cause tracing to stop once the trace buffers have filled up.
316static bool setTraceOverwriteEnable(bool enable)
317{
318 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
319}
320
321// Enable or disable kernel tracing.
322static bool setTracingEnabled(bool enable)
323{
324 return setKernelOptionEnable(k_tracingOnPath, enable);
325}
326
327// Clear the contents of the kernel trace.
328static bool clearTrace()
329{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700330 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800331}
332
333// Set the size of the kernel's trace buffer in kilobytes.
334static bool setTraceBufferSizeKB(int size)
335{
336 char str[32] = "1";
337 int len;
338 if (size < 1) {
339 size = 1;
340 }
341 snprintf(str, 32, "%d", size);
342 return writeStr(k_traceBufferSizePath, str);
343}
344
Colin Crossb1ce49b2014-08-20 14:28:47 -0700345// Read the trace_clock sysfs file and return true if it matches the requested
346// value. The trace_clock file format is:
347// local [global] counter uptime perf
348static bool isTraceClock(const char *mode)
349{
350 int fd = open(k_traceClockPath, O_RDONLY);
351 if (fd == -1) {
352 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceClockPath,
353 strerror(errno), errno);
354 return false;
355 }
356
357 char buf[4097];
358 ssize_t n = read(fd, buf, 4096);
359 close(fd);
360 if (n == -1) {
361 fprintf(stderr, "error reading %s: %s (%d)\n", k_traceClockPath,
362 strerror(errno), errno);
363 return false;
364 }
365 buf[n] = '\0';
366
367 char *start = strchr(buf, '[');
368 if (start == NULL) {
369 return false;
370 }
371 start++;
372
373 char *end = strchr(start, ']');
374 if (end == NULL) {
375 return false;
376 }
377 *end = '\0';
378
379 return strcmp(mode, start) == 0;
380}
381
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800382// Enable or disable the kernel's use of the global clock. Disabling the global
383// clock will result in the kernel using a per-CPU local clock.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700384// Any write to the trace_clock sysfs file will reset the buffer, so only
385// update it if the requested value is not the current value.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800386static bool setGlobalClockEnable(bool enable)
387{
Colin Crossb1ce49b2014-08-20 14:28:47 -0700388 const char *clock = enable ? "global" : "local";
389
390 if (isTraceClock(clock)) {
391 return true;
392 }
393
394 return writeStr(k_traceClockPath, clock);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800395}
396
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700397static bool setPrintTgidEnableIfPresent(bool enable)
398{
399 if (fileExists(k_printTgidPath)) {
400 return setKernelOptionEnable(k_printTgidPath, enable);
401 }
402 return true;
403}
404
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800405// Poke all the binder-enabled processes in the system to get them to re-read
406// their system properties.
407static bool pokeBinderServices()
408{
409 sp<IServiceManager> sm = defaultServiceManager();
410 Vector<String16> services = sm->listServices();
411 for (size_t i = 0; i < services.size(); i++) {
412 sp<IBinder> obj = sm->checkService(services[i]);
413 if (obj != NULL) {
414 Parcel data;
415 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
416 NULL, 0) != OK) {
417 if (false) {
418 // XXX: For some reason this fails on tablets trying to
419 // poke the "phone" service. It's not clear whether some
420 // are expected to fail.
421 String8 svc(services[i]);
422 fprintf(stderr, "error poking binder service %s\n",
423 svc.string());
424 return false;
425 }
426 }
427 }
428 }
429 return true;
430}
431
432// Set the trace tags that userland tracing uses, and poke the running
433// processes to pick up the new value.
434static bool setTagsProperty(uint64_t tags)
435{
436 char buf[64];
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700437 snprintf(buf, 64, "%#" PRIx64, tags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800438 if (property_set(k_traceTagsProperty, buf) < 0) {
439 fprintf(stderr, "error setting trace tags system property\n");
440 return false;
441 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700442 return true;
443}
444
445// Set the system property that indicates which apps should perform
446// application-level tracing.
447static bool setAppCmdlineProperty(const char* cmdline)
448{
449 if (property_set(k_traceAppCmdlineProperty, cmdline) < 0) {
450 fprintf(stderr, "error setting trace app system property\n");
451 return false;
452 }
453 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800454}
455
456// Disable all /sys/ enable files.
457static bool disableKernelTraceEvents() {
458 bool ok = true;
459 for (int i = 0; i < NELEM(k_categories); i++) {
460 const TracingCategory &c = k_categories[i];
461 for (int j = 0; j < MAX_SYS_FILES; j++) {
462 const char* path = c.sysfiles[j].path;
463 if (path != NULL && fileIsWritable(path)) {
464 ok &= setKernelOptionEnable(path, false);
465 }
466 }
467 }
468 return ok;
469}
470
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700471// Verify that the comma separated list of functions are being traced by the
472// kernel.
473static bool verifyKernelTraceFuncs(const char* funcs)
474{
475 int fd = open(k_ftraceFilterPath, O_RDONLY);
476 if (fd == -1) {
477 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
478 strerror(errno), errno);
479 return false;
480 }
481
482 char buf[4097];
483 ssize_t n = read(fd, buf, 4096);
484 close(fd);
485 if (n == -1) {
486 fprintf(stderr, "error reading %s: %s (%d)\n", k_ftraceFilterPath,
487 strerror(errno), errno);
488 return false;
489 }
490
491 buf[n] = '\0';
492 String8 funcList = String8::format("\n%s", buf);
493
494 // Make sure that every function listed in funcs is in the list we just
495 // read from the kernel.
496 bool ok = true;
497 char* myFuncs = strdup(funcs);
498 char* func = strtok(myFuncs, ",");
499 while (func) {
500 String8 fancyFunc = String8::format("\n%s\n", func);
501 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
502 if (!found || func[0] == '\0') {
503 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
504 "to trace.\n", func);
505 ok = false;
506 }
507 func = strtok(NULL, ",");
508 }
509 free(myFuncs);
510
511 return ok;
512}
513
514// Set the comma separated list of functions that the kernel is to trace.
515static bool setKernelTraceFuncs(const char* funcs)
516{
517 bool ok = true;
518
519 if (funcs == NULL || funcs[0] == '\0') {
520 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700521 if (fileIsWritable(k_currentTracerPath)) {
522 ok &= writeStr(k_currentTracerPath, "nop");
523 }
524 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700525 ok &= truncateFile(k_ftraceFilterPath);
526 }
527 } else {
528 // Enable kernel function tracing.
529 ok &= writeStr(k_currentTracerPath, "function_graph");
530 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
531 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
532 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
533 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
534
535 // Set the requested filter functions.
536 ok &= truncateFile(k_ftraceFilterPath);
537 char* myFuncs = strdup(funcs);
538 char* func = strtok(myFuncs, ",");
539 while (func) {
540 ok &= appendStr(k_ftraceFilterPath, func);
541 func = strtok(NULL, ",");
542 }
543 free(myFuncs);
544
545 // Verify that the set functions are being traced.
546 if (ok) {
547 ok &= verifyKernelTraceFuncs(funcs);
548 }
549 }
550
551 return ok;
552}
553
554// Set all the kernel tracing settings to the desired state for this trace
555// capture.
556static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800557{
558 bool ok = true;
559
560 // Set up the tracing options.
561 ok &= setTraceOverwriteEnable(g_traceOverwrite);
562 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
563 ok &= setGlobalClockEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700564 ok &= setPrintTgidEnableIfPresent(true);
565 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800566
567 // Set up the tags property.
568 uint64_t tags = 0;
569 for (int i = 0; i < NELEM(k_categories); i++) {
570 if (g_categoryEnables[i]) {
571 const TracingCategory &c = k_categories[i];
572 tags |= c.tags;
573 }
574 }
575 ok &= setTagsProperty(tags);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700576 ok &= setAppCmdlineProperty(g_debugAppCmdLine);
577 ok &= pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800578
579 // Disable all the sysfs enables. This is done as a separate loop from
580 // the enables to allow the same enable to exist in multiple categories.
581 ok &= disableKernelTraceEvents();
582
583 // Enable all the sysfs enables that are in an enabled category.
584 for (int i = 0; i < NELEM(k_categories); i++) {
585 if (g_categoryEnables[i]) {
586 const TracingCategory &c = k_categories[i];
587 for (int j = 0; j < MAX_SYS_FILES; j++) {
588 const char* path = c.sysfiles[j].path;
589 bool required = c.sysfiles[j].required == REQ;
590 if (path != NULL) {
591 if (fileIsWritable(path)) {
592 ok &= setKernelOptionEnable(path, true);
593 } else if (required) {
594 fprintf(stderr, "error writing file %s\n", path);
595 ok = false;
596 }
597 }
598 }
599 }
600 }
601
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800602 return ok;
603}
604
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700605// Reset all the kernel tracing settings to their default state.
606static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800607{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800608 // Disable all tracing that we're able to.
609 disableKernelTraceEvents();
610
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700611 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800612 setTagsProperty(0);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700613 setAppCmdlineProperty("");
614 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800615
616 // Set the options back to their defaults.
617 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700618 setTraceBufferSizeKB(1);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800619 setGlobalClockEnable(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700620 setPrintTgidEnableIfPresent(false);
621 setKernelTraceFuncs(NULL);
622}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800623
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700624
625// Enable tracing in the kernel.
626static bool startTrace()
627{
628 return setTracingEnabled(true);
629}
630
631// Disable tracing in the kernel.
632static void stopTrace()
633{
634 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800635}
636
637// Read the current kernel trace and write it to stdout.
638static void dumpTrace()
639{
640 int traceFD = open(k_tracePath, O_RDWR);
641 if (traceFD == -1) {
642 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
643 strerror(errno), errno);
644 return;
645 }
646
647 if (g_compress) {
648 z_stream zs;
649 uint8_t *in, *out;
650 int result, flush;
651
Elliott Hughes3da5d232015-01-25 08:35:20 -0800652 memset(&zs, 0, sizeof(zs));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800653 result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
654 if (result != Z_OK) {
655 fprintf(stderr, "error initializing zlib: %d\n", result);
656 close(traceFD);
657 return;
658 }
659
660 const size_t bufSize = 64*1024;
661 in = (uint8_t*)malloc(bufSize);
662 out = (uint8_t*)malloc(bufSize);
663 flush = Z_NO_FLUSH;
664
665 zs.next_out = out;
666 zs.avail_out = bufSize;
667
668 do {
669
670 if (zs.avail_in == 0) {
671 // More input is needed.
672 result = read(traceFD, in, bufSize);
673 if (result < 0) {
674 fprintf(stderr, "error reading trace: %s (%d)\n",
675 strerror(errno), errno);
676 result = Z_STREAM_END;
677 break;
678 } else if (result == 0) {
679 flush = Z_FINISH;
680 } else {
681 zs.next_in = in;
682 zs.avail_in = result;
683 }
684 }
685
686 if (zs.avail_out == 0) {
687 // Need to write the output.
688 result = write(STDOUT_FILENO, out, bufSize);
689 if ((size_t)result < bufSize) {
690 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
691 strerror(errno), errno);
692 result = Z_STREAM_END; // skip deflate error message
693 zs.avail_out = bufSize; // skip the final write
694 break;
695 }
696 zs.next_out = out;
697 zs.avail_out = bufSize;
698 }
699
700 } while ((result = deflate(&zs, flush)) == Z_OK);
701
702 if (result != Z_STREAM_END) {
703 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
704 }
705
706 if (zs.avail_out < bufSize) {
707 size_t bytes = bufSize - zs.avail_out;
708 result = write(STDOUT_FILENO, out, bytes);
709 if ((size_t)result < bytes) {
710 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
711 strerror(errno), errno);
712 }
713 }
714
715 result = deflateEnd(&zs);
716 if (result != Z_OK) {
717 fprintf(stderr, "error cleaning up zlib: %d\n", result);
718 }
719
720 free(in);
721 free(out);
722 } else {
723 ssize_t sent = 0;
724 while ((sent = sendfile(STDOUT_FILENO, traceFD, NULL, 64*1024*1024)) > 0);
725 if (sent == -1) {
726 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
727 errno);
728 }
729 }
730
731 close(traceFD);
732}
733
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700734static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800735{
736 if (!g_nohup) {
737 g_traceAborted = true;
738 }
739}
740
741static void registerSigHandler()
742{
743 struct sigaction sa;
744 sigemptyset(&sa.sa_mask);
745 sa.sa_flags = 0;
746 sa.sa_handler = handleSignal;
747 sigaction(SIGHUP, &sa, NULL);
748 sigaction(SIGINT, &sa, NULL);
749 sigaction(SIGQUIT, &sa, NULL);
750 sigaction(SIGTERM, &sa, NULL);
751}
752
753static bool setCategoryEnable(const char* name, bool enable)
754{
755 for (int i = 0; i < NELEM(k_categories); i++) {
756 const TracingCategory& c = k_categories[i];
757 if (strcmp(name, c.name) == 0) {
758 if (isCategorySupported(c)) {
759 g_categoryEnables[i] = enable;
760 return true;
761 } else {
762 if (isCategorySupportedForRoot(c)) {
763 fprintf(stderr, "error: category \"%s\" requires root "
764 "privileges.\n", name);
765 } else {
766 fprintf(stderr, "error: category \"%s\" is not supported "
767 "on this device.\n", name);
768 }
769 return false;
770 }
771 }
772 }
773 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
774 return false;
775}
776
777static void listSupportedCategories()
778{
779 for (int i = 0; i < NELEM(k_categories); i++) {
780 const TracingCategory& c = k_categories[i];
781 if (isCategorySupported(c)) {
782 printf(" %10s - %s\n", c.name, c.longname);
783 }
784 }
785}
786
787// Print the command usage help to stderr.
788static void showHelp(const char *cmd)
789{
790 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
791 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700792 " -a appname enable app-level tracing for a comma "
793 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800794 " -b N use a trace buffer size of N KB\n"
795 " -c trace into a circular buffer\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700796 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800797 " -n ignore signals\n"
798 " -s N sleep for N seconds before tracing [default 0]\n"
799 " -t N trace for N seconds [defualt 5]\n"
800 " -z compress the trace dump\n"
801 " --async_start start circular trace and return immediatly\n"
802 " --async_dump dump the current contents of circular trace buffer\n"
803 " --async_stop stop tracing and dump the current contents of circular\n"
804 " trace buffer\n"
Jamie Gennis92573f12012-12-07 16:29:03 -0800805 " --list_categories\n"
806 " list the available tracing categories\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800807 );
808}
809
810int main(int argc, char **argv)
811{
812 bool async = false;
813 bool traceStart = true;
814 bool traceStop = true;
815 bool traceDump = true;
816
817 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
818 showHelp(argv[0]);
819 exit(0);
820 }
821
822 for (;;) {
823 int ret;
824 int option_index = 0;
825 static struct option long_options[] = {
826 {"async_start", no_argument, 0, 0 },
827 {"async_stop", no_argument, 0, 0 },
828 {"async_dump", no_argument, 0, 0 },
829 {"list_categories", no_argument, 0, 0 },
830 { 0, 0, 0, 0 }
831 };
832
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700833 ret = getopt_long(argc, argv, "a:b:ck:ns:t:z",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800834 long_options, &option_index);
835
836 if (ret < 0) {
837 for (int i = optind; i < argc; i++) {
838 if (!setCategoryEnable(argv[i], true)) {
839 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
840 exit(1);
841 }
842 }
843 break;
844 }
845
846 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700847 case 'a':
848 g_debugAppCmdLine = optarg;
849 break;
850
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800851 case 'b':
852 g_traceBufferSizeKB = atoi(optarg);
853 break;
854
855 case 'c':
856 g_traceOverwrite = true;
857 break;
858
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700859 case 'k':
860 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700861 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700862
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800863 case 'n':
864 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700865 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800866
867 case 's':
868 g_initialSleepSecs = atoi(optarg);
869 break;
870
871 case 't':
872 g_traceDurationSeconds = atoi(optarg);
873 break;
874
875 case 'z':
876 g_compress = true;
877 break;
878
879 case 0:
880 if (!strcmp(long_options[option_index].name, "async_start")) {
881 async = true;
882 traceStop = false;
883 traceDump = false;
884 g_traceOverwrite = true;
885 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
886 async = true;
887 traceStop = false;
888 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
889 async = true;
890 traceStart = false;
891 traceStop = false;
892 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
893 listSupportedCategories();
894 exit(0);
895 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700896 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800897
898 default:
899 fprintf(stderr, "\n");
900 showHelp(argv[0]);
901 exit(-1);
902 break;
903 }
904 }
905
906 registerSigHandler();
907
908 if (g_initialSleepSecs > 0) {
909 sleep(g_initialSleepSecs);
910 }
911
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700912 bool ok = true;
913 ok &= setUpTrace();
914 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800915
916 if (ok && traceStart) {
917 printf("capturing trace...");
918 fflush(stdout);
919
920 // We clear the trace after starting it because tracing gets enabled for
921 // each CPU individually in the kernel. Having the beginning of the trace
922 // contain entries from only one CPU can cause "begin" entries without a
923 // matching "end" entry to show up if a task gets migrated from one CPU to
924 // another.
925 ok = clearTrace();
926
927 if (ok && !async) {
928 // Sleep to allow the trace to be captured.
929 struct timespec timeLeft;
930 timeLeft.tv_sec = g_traceDurationSeconds;
931 timeLeft.tv_nsec = 0;
932 do {
933 if (g_traceAborted) {
934 break;
935 }
936 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
937 }
938 }
939
940 // Stop the trace and restore the default settings.
941 if (traceStop)
942 stopTrace();
943
944 if (ok && traceDump) {
945 if (!g_traceAborted) {
946 printf(" done\nTRACE:\n");
947 fflush(stdout);
948 dumpTrace();
949 } else {
950 printf("\ntrace aborted.\n");
951 fflush(stdout);
952 }
953 clearTrace();
954 } else if (!ok) {
955 fprintf(stderr, "unable to start tracing\n");
956 }
957
958 // Reset the trace buffer size to 1.
959 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700960 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800961
962 return g_traceAborted ? 1 : 0;
963}