blob: fb401931f2c2289c7e5b0137cb9ac6b04bd118d5 [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>
26#include <sys/sendfile.h>
27#include <time.h>
28#include <zlib.h>
29
30#include <binder/IBinder.h>
31#include <binder/IServiceManager.h>
32#include <binder/Parcel.h>
33
34#include <cutils/properties.h>
35
36#include <utils/String8.h>
37#include <utils/Trace.h>
38
39using namespace android;
40
41#define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0])))
42
Mohamad Ayyash26dbcbe2014-04-08 15:24:11 -070043enum { MAX_SYS_FILES = 10 };
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080044
45const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
Jamie Gennisf7f29c82013-03-27 15:50:58 -070046const char* k_traceAppCmdlineProperty = "debug.atrace.app_cmdlines";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080047
48typedef enum { OPT, REQ } requiredness ;
49
50struct TracingCategory {
51 // The name identifying the category.
52 const char* name;
53
54 // A longer description of the category.
55 const char* longname;
56
57 // The userland tracing tags that the category enables.
58 uint64_t tags;
59
60 // The fname==NULL terminated list of /sys/ files that the category
61 // enables.
62 struct {
63 // Whether the file must be writable in order to enable the tracing
64 // category.
65 requiredness required;
66
67 // The path to the enable file.
68 const char* path;
69 } sysfiles[MAX_SYS_FILES];
70};
71
72/* Tracing categories */
73static const TracingCategory k_categories[] = {
Jamie Gennisb2a89e32013-03-11 19:37:53 -070074 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, { } },
75 { "input", "Input", ATRACE_TAG_INPUT, { } },
76 { "view", "View System", ATRACE_TAG_VIEW, { } },
77 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
78 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
79 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -070080 { "sync", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070081 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
82 { "video", "Video", ATRACE_TAG_VIDEO, { } },
83 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
84 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -070085 { "app", "Application", ATRACE_TAG_APP, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -070086 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -070087 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -070088 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -070089 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -070090 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070091 { "sched", "CPU Scheduling", 0, {
92 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_switch/enable" },
93 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_wakeup/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080094 } },
Dan Willemsenf440d392014-04-11 15:44:09 -070095 { "irq", "IRQ Events", 0, {
96 { REQ, "/sys/kernel/debug/tracing/events/irq/enable" },
97 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070098 { "freq", "CPU Frequency", 0, {
99 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_frequency/enable" },
100 { OPT, "/sys/kernel/debug/tracing/events/power/clock_set_rate/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800101 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700102 { "membus", "Memory Bus Utilization", 0, {
103 { REQ, "/sys/kernel/debug/tracing/events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800104 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700105 { "idle", "CPU Idle", 0, {
106 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800107 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700108 { "disk", "Disk I/O", 0, {
Mohamad Ayyash26dbcbe2014-04-08 15:24:11 -0700109 { REQ, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_enter/enable" },
110 { REQ, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_exit/enable" },
111 { REQ, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_begin/enable" },
112 { REQ, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_end/enable" },
113 { REQ, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_begin/enable" },
114 { REQ, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_end/enable" },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700115 { REQ, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable" },
116 { REQ, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable" },
117 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" },
118 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800119 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700120 { "mmc", "eMMC commands", 0, {
121 { REQ, "/sys/kernel/debug/tracing/events/mmc/enable" },
122 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700123 { "load", "CPU Load", 0, {
124 { REQ, "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800125 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700126 { "sync", "Synchronization", 0, {
127 { REQ, "/sys/kernel/debug/tracing/events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800128 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700129 { "workq", "Kernel Workqueues", 0, {
130 { REQ, "/sys/kernel/debug/tracing/events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800131 } },
Colin Cross580407f2014-08-18 15:22:13 -0700132 { "memreclaim", "Kernel Memory Reclaim", 0, {
133 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
134 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
135 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_wake/enable" },
136 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_sleep/enable" },
137 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800138};
139
140/* Command line options */
141static int g_traceDurationSeconds = 5;
142static bool g_traceOverwrite = false;
143static int g_traceBufferSizeKB = 2048;
144static bool g_compress = false;
145static bool g_nohup = false;
146static int g_initialSleepSecs = 0;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700147static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700148static const char* g_debugAppCmdLine = "";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800149
150/* Global state */
151static bool g_traceAborted = false;
152static bool g_categoryEnables[NELEM(k_categories)] = {};
153
154/* Sys file paths */
155static const char* k_traceClockPath =
156 "/sys/kernel/debug/tracing/trace_clock";
157
158static const char* k_traceBufferSizePath =
159 "/sys/kernel/debug/tracing/buffer_size_kb";
160
161static const char* k_tracingOverwriteEnablePath =
162 "/sys/kernel/debug/tracing/options/overwrite";
163
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700164static const char* k_currentTracerPath =
165 "/sys/kernel/debug/tracing/current_tracer";
166
167static const char* k_printTgidPath =
168 "/sys/kernel/debug/tracing/options/print-tgid";
169
170static const char* k_funcgraphAbsTimePath =
171 "/sys/kernel/debug/tracing/options/funcgraph-abstime";
172
173static const char* k_funcgraphCpuPath =
174 "/sys/kernel/debug/tracing/options/funcgraph-cpu";
175
176static const char* k_funcgraphProcPath =
177 "/sys/kernel/debug/tracing/options/funcgraph-proc";
178
179static const char* k_funcgraphFlatPath =
180 "/sys/kernel/debug/tracing/options/funcgraph-flat";
181
182static const char* k_funcgraphDurationPath =
183 "/sys/kernel/debug/tracing/options/funcgraph-duration";
184
185static const char* k_ftraceFilterPath =
186 "/sys/kernel/debug/tracing/set_ftrace_filter";
187
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800188static const char* k_tracingOnPath =
189 "/sys/kernel/debug/tracing/tracing_on";
190
191static const char* k_tracePath =
192 "/sys/kernel/debug/tracing/trace";
193
194// Check whether a file exists.
195static bool fileExists(const char* filename) {
196 return access(filename, F_OK) != -1;
197}
198
199// Check whether a file is writable.
200static bool fileIsWritable(const char* filename) {
201 return access(filename, W_OK) != -1;
202}
203
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700204// Truncate a file.
205static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800206{
Jamie Gennis43122e72013-03-21 14:06:31 -0700207 // This uses creat rather than truncate because some of the debug kernel
208 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
209 // calls to truncate, but they are cleared by calls to creat.
210 int traceFD = creat(path, 0);
211 if (traceFD == -1) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700212 fprintf(stderr, "error truncating %s: %s (%d)\n", path,
Jamie Gennis43122e72013-03-21 14:06:31 -0700213 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700214 return false;
215 }
216
Jamie Gennis43122e72013-03-21 14:06:31 -0700217 close(traceFD);
218
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700219 return true;
220}
221
222static bool _writeStr(const char* filename, const char* str, int flags)
223{
224 int fd = open(filename, flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800225 if (fd == -1) {
226 fprintf(stderr, "error opening %s: %s (%d)\n", filename,
227 strerror(errno), errno);
228 return false;
229 }
230
231 bool ok = true;
232 ssize_t len = strlen(str);
233 if (write(fd, str, len) != len) {
234 fprintf(stderr, "error writing to %s: %s (%d)\n", filename,
235 strerror(errno), errno);
236 ok = false;
237 }
238
239 close(fd);
240
241 return ok;
242}
243
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700244// Write a string to a file, returning true if the write was successful.
245static bool writeStr(const char* filename, const char* str)
246{
247 return _writeStr(filename, str, O_WRONLY);
248}
249
250// Append a string to a file, returning true if the write was successful.
251static bool appendStr(const char* filename, const char* str)
252{
253 return _writeStr(filename, str, O_APPEND|O_WRONLY);
254}
255
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800256// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
257// file.
258static bool setKernelOptionEnable(const char* filename, bool enable)
259{
260 return writeStr(filename, enable ? "1" : "0");
261}
262
263// Check whether the category is supported on the device with the current
264// rootness. A category is supported only if all its required /sys/ files are
265// writable and if enabling the category will enable one or more tracing tags
266// or /sys/ files.
267static bool isCategorySupported(const TracingCategory& category)
268{
269 bool ok = category.tags != 0;
270 for (int i = 0; i < MAX_SYS_FILES; i++) {
271 const char* path = category.sysfiles[i].path;
272 bool req = category.sysfiles[i].required == REQ;
273 if (path != NULL) {
274 if (req) {
275 if (!fileIsWritable(path)) {
276 return false;
277 } else {
278 ok = true;
279 }
280 } else {
281 ok |= fileIsWritable(path);
282 }
283 }
284 }
285 return ok;
286}
287
288// Check whether the category would be supported on the device if the user
289// were root. This function assumes that root is able to write to any file
290// that exists. It performs the same logic as isCategorySupported, but it
291// uses file existance rather than writability in the /sys/ file checks.
292static bool isCategorySupportedForRoot(const TracingCategory& category)
293{
294 bool ok = category.tags != 0;
295 for (int i = 0; i < MAX_SYS_FILES; i++) {
296 const char* path = category.sysfiles[i].path;
297 bool req = category.sysfiles[i].required == REQ;
298 if (path != NULL) {
299 if (req) {
300 if (!fileExists(path)) {
301 return false;
302 } else {
303 ok = true;
304 }
305 } else {
306 ok |= fileExists(path);
307 }
308 }
309 }
310 return ok;
311}
312
313// Enable or disable overwriting of the kernel trace buffers. Disabling this
314// will cause tracing to stop once the trace buffers have filled up.
315static bool setTraceOverwriteEnable(bool enable)
316{
317 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
318}
319
320// Enable or disable kernel tracing.
321static bool setTracingEnabled(bool enable)
322{
323 return setKernelOptionEnable(k_tracingOnPath, enable);
324}
325
326// Clear the contents of the kernel trace.
327static bool clearTrace()
328{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700329 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800330}
331
332// Set the size of the kernel's trace buffer in kilobytes.
333static bool setTraceBufferSizeKB(int size)
334{
335 char str[32] = "1";
336 int len;
337 if (size < 1) {
338 size = 1;
339 }
340 snprintf(str, 32, "%d", size);
341 return writeStr(k_traceBufferSizePath, str);
342}
343
344// Enable or disable the kernel's use of the global clock. Disabling the global
345// clock will result in the kernel using a per-CPU local clock.
346static bool setGlobalClockEnable(bool enable)
347{
348 return writeStr(k_traceClockPath, enable ? "global" : "local");
349}
350
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700351static bool setPrintTgidEnableIfPresent(bool enable)
352{
353 if (fileExists(k_printTgidPath)) {
354 return setKernelOptionEnable(k_printTgidPath, enable);
355 }
356 return true;
357}
358
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800359// Poke all the binder-enabled processes in the system to get them to re-read
360// their system properties.
361static bool pokeBinderServices()
362{
363 sp<IServiceManager> sm = defaultServiceManager();
364 Vector<String16> services = sm->listServices();
365 for (size_t i = 0; i < services.size(); i++) {
366 sp<IBinder> obj = sm->checkService(services[i]);
367 if (obj != NULL) {
368 Parcel data;
369 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
370 NULL, 0) != OK) {
371 if (false) {
372 // XXX: For some reason this fails on tablets trying to
373 // poke the "phone" service. It's not clear whether some
374 // are expected to fail.
375 String8 svc(services[i]);
376 fprintf(stderr, "error poking binder service %s\n",
377 svc.string());
378 return false;
379 }
380 }
381 }
382 }
383 return true;
384}
385
386// Set the trace tags that userland tracing uses, and poke the running
387// processes to pick up the new value.
388static bool setTagsProperty(uint64_t tags)
389{
390 char buf[64];
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700391 snprintf(buf, 64, "%#" PRIx64, tags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800392 if (property_set(k_traceTagsProperty, buf) < 0) {
393 fprintf(stderr, "error setting trace tags system property\n");
394 return false;
395 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700396 return true;
397}
398
399// Set the system property that indicates which apps should perform
400// application-level tracing.
401static bool setAppCmdlineProperty(const char* cmdline)
402{
403 if (property_set(k_traceAppCmdlineProperty, cmdline) < 0) {
404 fprintf(stderr, "error setting trace app system property\n");
405 return false;
406 }
407 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800408}
409
410// Disable all /sys/ enable files.
411static bool disableKernelTraceEvents() {
412 bool ok = true;
413 for (int i = 0; i < NELEM(k_categories); i++) {
414 const TracingCategory &c = k_categories[i];
415 for (int j = 0; j < MAX_SYS_FILES; j++) {
416 const char* path = c.sysfiles[j].path;
417 if (path != NULL && fileIsWritable(path)) {
418 ok &= setKernelOptionEnable(path, false);
419 }
420 }
421 }
422 return ok;
423}
424
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700425// Verify that the comma separated list of functions are being traced by the
426// kernel.
427static bool verifyKernelTraceFuncs(const char* funcs)
428{
429 int fd = open(k_ftraceFilterPath, O_RDONLY);
430 if (fd == -1) {
431 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
432 strerror(errno), errno);
433 return false;
434 }
435
436 char buf[4097];
437 ssize_t n = read(fd, buf, 4096);
438 close(fd);
439 if (n == -1) {
440 fprintf(stderr, "error reading %s: %s (%d)\n", k_ftraceFilterPath,
441 strerror(errno), errno);
442 return false;
443 }
444
445 buf[n] = '\0';
446 String8 funcList = String8::format("\n%s", buf);
447
448 // Make sure that every function listed in funcs is in the list we just
449 // read from the kernel.
450 bool ok = true;
451 char* myFuncs = strdup(funcs);
452 char* func = strtok(myFuncs, ",");
453 while (func) {
454 String8 fancyFunc = String8::format("\n%s\n", func);
455 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
456 if (!found || func[0] == '\0') {
457 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
458 "to trace.\n", func);
459 ok = false;
460 }
461 func = strtok(NULL, ",");
462 }
463 free(myFuncs);
464
465 return ok;
466}
467
468// Set the comma separated list of functions that the kernel is to trace.
469static bool setKernelTraceFuncs(const char* funcs)
470{
471 bool ok = true;
472
473 if (funcs == NULL || funcs[0] == '\0') {
474 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700475 if (fileIsWritable(k_currentTracerPath)) {
476 ok &= writeStr(k_currentTracerPath, "nop");
477 }
478 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700479 ok &= truncateFile(k_ftraceFilterPath);
480 }
481 } else {
482 // Enable kernel function tracing.
483 ok &= writeStr(k_currentTracerPath, "function_graph");
484 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
485 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
486 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
487 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
488
489 // Set the requested filter functions.
490 ok &= truncateFile(k_ftraceFilterPath);
491 char* myFuncs = strdup(funcs);
492 char* func = strtok(myFuncs, ",");
493 while (func) {
494 ok &= appendStr(k_ftraceFilterPath, func);
495 func = strtok(NULL, ",");
496 }
497 free(myFuncs);
498
499 // Verify that the set functions are being traced.
500 if (ok) {
501 ok &= verifyKernelTraceFuncs(funcs);
502 }
503 }
504
505 return ok;
506}
507
508// Set all the kernel tracing settings to the desired state for this trace
509// capture.
510static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800511{
512 bool ok = true;
513
514 // Set up the tracing options.
515 ok &= setTraceOverwriteEnable(g_traceOverwrite);
516 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
517 ok &= setGlobalClockEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700518 ok &= setPrintTgidEnableIfPresent(true);
519 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800520
521 // Set up the tags property.
522 uint64_t tags = 0;
523 for (int i = 0; i < NELEM(k_categories); i++) {
524 if (g_categoryEnables[i]) {
525 const TracingCategory &c = k_categories[i];
526 tags |= c.tags;
527 }
528 }
529 ok &= setTagsProperty(tags);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700530 ok &= setAppCmdlineProperty(g_debugAppCmdLine);
531 ok &= pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800532
533 // Disable all the sysfs enables. This is done as a separate loop from
534 // the enables to allow the same enable to exist in multiple categories.
535 ok &= disableKernelTraceEvents();
536
537 // Enable all the sysfs enables that are in an enabled category.
538 for (int i = 0; i < NELEM(k_categories); i++) {
539 if (g_categoryEnables[i]) {
540 const TracingCategory &c = k_categories[i];
541 for (int j = 0; j < MAX_SYS_FILES; j++) {
542 const char* path = c.sysfiles[j].path;
543 bool required = c.sysfiles[j].required == REQ;
544 if (path != NULL) {
545 if (fileIsWritable(path)) {
546 ok &= setKernelOptionEnable(path, true);
547 } else if (required) {
548 fprintf(stderr, "error writing file %s\n", path);
549 ok = false;
550 }
551 }
552 }
553 }
554 }
555
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800556 return ok;
557}
558
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700559// Reset all the kernel tracing settings to their default state.
560static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800561{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800562 // Disable all tracing that we're able to.
563 disableKernelTraceEvents();
564
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700565 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800566 setTagsProperty(0);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700567 setAppCmdlineProperty("");
568 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800569
570 // Set the options back to their defaults.
571 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700572 setTraceBufferSizeKB(1);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800573 setGlobalClockEnable(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700574 setPrintTgidEnableIfPresent(false);
575 setKernelTraceFuncs(NULL);
576}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800577
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700578
579// Enable tracing in the kernel.
580static bool startTrace()
581{
582 return setTracingEnabled(true);
583}
584
585// Disable tracing in the kernel.
586static void stopTrace()
587{
588 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800589}
590
591// Read the current kernel trace and write it to stdout.
592static void dumpTrace()
593{
594 int traceFD = open(k_tracePath, O_RDWR);
595 if (traceFD == -1) {
596 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
597 strerror(errno), errno);
598 return;
599 }
600
601 if (g_compress) {
602 z_stream zs;
603 uint8_t *in, *out;
604 int result, flush;
605
606 bzero(&zs, sizeof(zs));
607 result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
608 if (result != Z_OK) {
609 fprintf(stderr, "error initializing zlib: %d\n", result);
610 close(traceFD);
611 return;
612 }
613
614 const size_t bufSize = 64*1024;
615 in = (uint8_t*)malloc(bufSize);
616 out = (uint8_t*)malloc(bufSize);
617 flush = Z_NO_FLUSH;
618
619 zs.next_out = out;
620 zs.avail_out = bufSize;
621
622 do {
623
624 if (zs.avail_in == 0) {
625 // More input is needed.
626 result = read(traceFD, in, bufSize);
627 if (result < 0) {
628 fprintf(stderr, "error reading trace: %s (%d)\n",
629 strerror(errno), errno);
630 result = Z_STREAM_END;
631 break;
632 } else if (result == 0) {
633 flush = Z_FINISH;
634 } else {
635 zs.next_in = in;
636 zs.avail_in = result;
637 }
638 }
639
640 if (zs.avail_out == 0) {
641 // Need to write the output.
642 result = write(STDOUT_FILENO, out, bufSize);
643 if ((size_t)result < bufSize) {
644 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
645 strerror(errno), errno);
646 result = Z_STREAM_END; // skip deflate error message
647 zs.avail_out = bufSize; // skip the final write
648 break;
649 }
650 zs.next_out = out;
651 zs.avail_out = bufSize;
652 }
653
654 } while ((result = deflate(&zs, flush)) == Z_OK);
655
656 if (result != Z_STREAM_END) {
657 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
658 }
659
660 if (zs.avail_out < bufSize) {
661 size_t bytes = bufSize - zs.avail_out;
662 result = write(STDOUT_FILENO, out, bytes);
663 if ((size_t)result < bytes) {
664 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
665 strerror(errno), errno);
666 }
667 }
668
669 result = deflateEnd(&zs);
670 if (result != Z_OK) {
671 fprintf(stderr, "error cleaning up zlib: %d\n", result);
672 }
673
674 free(in);
675 free(out);
676 } else {
677 ssize_t sent = 0;
678 while ((sent = sendfile(STDOUT_FILENO, traceFD, NULL, 64*1024*1024)) > 0);
679 if (sent == -1) {
680 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
681 errno);
682 }
683 }
684
685 close(traceFD);
686}
687
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700688static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800689{
690 if (!g_nohup) {
691 g_traceAborted = true;
692 }
693}
694
695static void registerSigHandler()
696{
697 struct sigaction sa;
698 sigemptyset(&sa.sa_mask);
699 sa.sa_flags = 0;
700 sa.sa_handler = handleSignal;
701 sigaction(SIGHUP, &sa, NULL);
702 sigaction(SIGINT, &sa, NULL);
703 sigaction(SIGQUIT, &sa, NULL);
704 sigaction(SIGTERM, &sa, NULL);
705}
706
707static bool setCategoryEnable(const char* name, bool enable)
708{
709 for (int i = 0; i < NELEM(k_categories); i++) {
710 const TracingCategory& c = k_categories[i];
711 if (strcmp(name, c.name) == 0) {
712 if (isCategorySupported(c)) {
713 g_categoryEnables[i] = enable;
714 return true;
715 } else {
716 if (isCategorySupportedForRoot(c)) {
717 fprintf(stderr, "error: category \"%s\" requires root "
718 "privileges.\n", name);
719 } else {
720 fprintf(stderr, "error: category \"%s\" is not supported "
721 "on this device.\n", name);
722 }
723 return false;
724 }
725 }
726 }
727 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
728 return false;
729}
730
731static void listSupportedCategories()
732{
733 for (int i = 0; i < NELEM(k_categories); i++) {
734 const TracingCategory& c = k_categories[i];
735 if (isCategorySupported(c)) {
736 printf(" %10s - %s\n", c.name, c.longname);
737 }
738 }
739}
740
741// Print the command usage help to stderr.
742static void showHelp(const char *cmd)
743{
744 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
745 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700746 " -a appname enable app-level tracing for a comma "
747 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800748 " -b N use a trace buffer size of N KB\n"
749 " -c trace into a circular buffer\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700750 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800751 " -n ignore signals\n"
752 " -s N sleep for N seconds before tracing [default 0]\n"
753 " -t N trace for N seconds [defualt 5]\n"
754 " -z compress the trace dump\n"
755 " --async_start start circular trace and return immediatly\n"
756 " --async_dump dump the current contents of circular trace buffer\n"
757 " --async_stop stop tracing and dump the current contents of circular\n"
758 " trace buffer\n"
Jamie Gennis92573f12012-12-07 16:29:03 -0800759 " --list_categories\n"
760 " list the available tracing categories\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800761 );
762}
763
764int main(int argc, char **argv)
765{
766 bool async = false;
767 bool traceStart = true;
768 bool traceStop = true;
769 bool traceDump = true;
770
771 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
772 showHelp(argv[0]);
773 exit(0);
774 }
775
776 for (;;) {
777 int ret;
778 int option_index = 0;
779 static struct option long_options[] = {
780 {"async_start", no_argument, 0, 0 },
781 {"async_stop", no_argument, 0, 0 },
782 {"async_dump", no_argument, 0, 0 },
783 {"list_categories", no_argument, 0, 0 },
784 { 0, 0, 0, 0 }
785 };
786
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700787 ret = getopt_long(argc, argv, "a:b:ck:ns:t:z",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800788 long_options, &option_index);
789
790 if (ret < 0) {
791 for (int i = optind; i < argc; i++) {
792 if (!setCategoryEnable(argv[i], true)) {
793 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
794 exit(1);
795 }
796 }
797 break;
798 }
799
800 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700801 case 'a':
802 g_debugAppCmdLine = optarg;
803 break;
804
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800805 case 'b':
806 g_traceBufferSizeKB = atoi(optarg);
807 break;
808
809 case 'c':
810 g_traceOverwrite = true;
811 break;
812
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700813 case 'k':
814 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700815 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700816
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800817 case 'n':
818 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700819 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800820
821 case 's':
822 g_initialSleepSecs = atoi(optarg);
823 break;
824
825 case 't':
826 g_traceDurationSeconds = atoi(optarg);
827 break;
828
829 case 'z':
830 g_compress = true;
831 break;
832
833 case 0:
834 if (!strcmp(long_options[option_index].name, "async_start")) {
835 async = true;
836 traceStop = false;
837 traceDump = false;
838 g_traceOverwrite = true;
839 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
840 async = true;
841 traceStop = false;
842 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
843 async = true;
844 traceStart = false;
845 traceStop = false;
846 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
847 listSupportedCategories();
848 exit(0);
849 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700850 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800851
852 default:
853 fprintf(stderr, "\n");
854 showHelp(argv[0]);
855 exit(-1);
856 break;
857 }
858 }
859
860 registerSigHandler();
861
862 if (g_initialSleepSecs > 0) {
863 sleep(g_initialSleepSecs);
864 }
865
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700866 bool ok = true;
867 ok &= setUpTrace();
868 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800869
870 if (ok && traceStart) {
871 printf("capturing trace...");
872 fflush(stdout);
873
874 // We clear the trace after starting it because tracing gets enabled for
875 // each CPU individually in the kernel. Having the beginning of the trace
876 // contain entries from only one CPU can cause "begin" entries without a
877 // matching "end" entry to show up if a task gets migrated from one CPU to
878 // another.
879 ok = clearTrace();
880
881 if (ok && !async) {
882 // Sleep to allow the trace to be captured.
883 struct timespec timeLeft;
884 timeLeft.tv_sec = g_traceDurationSeconds;
885 timeLeft.tv_nsec = 0;
886 do {
887 if (g_traceAborted) {
888 break;
889 }
890 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
891 }
892 }
893
894 // Stop the trace and restore the default settings.
895 if (traceStop)
896 stopTrace();
897
898 if (ok && traceDump) {
899 if (!g_traceAborted) {
900 printf(" done\nTRACE:\n");
901 fflush(stdout);
902 dumpTrace();
903 } else {
904 printf("\ntrace aborted.\n");
905 fflush(stdout);
906 }
907 clearTrace();
908 } else if (!ok) {
909 fprintf(stderr, "unable to start tracing\n");
910 }
911
912 // Reset the trace buffer size to 1.
913 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700914 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800915
916 return g_traceAborted ? 1 : 0;
917}