blob: 0d71bbdeba08ff1485dd0ac91eab007845fbb0c2 [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, { } },
80 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
81 { "video", "Video", ATRACE_TAG_VIDEO, { } },
82 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
83 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -070084 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -070085 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -070086 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -070087 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070088 { "sched", "CPU Scheduling", 0, {
89 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_switch/enable" },
90 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_wakeup/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080091 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070092 { "freq", "CPU Frequency", 0, {
93 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_frequency/enable" },
94 { OPT, "/sys/kernel/debug/tracing/events/power/clock_set_rate/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080095 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070096 { "membus", "Memory Bus Utilization", 0, {
97 { REQ, "/sys/kernel/debug/tracing/events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080098 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070099 { "idle", "CPU Idle", 0, {
100 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800101 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700102 { "disk", "Disk I/O", 0, {
Mohamad Ayyash26dbcbe2014-04-08 15:24:11 -0700103 { REQ, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_enter/enable" },
104 { REQ, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_exit/enable" },
105 { REQ, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_begin/enable" },
106 { REQ, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_end/enable" },
107 { REQ, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_begin/enable" },
108 { REQ, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_end/enable" },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700109 { REQ, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable" },
110 { REQ, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable" },
111 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" },
112 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800113 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700114 { "mmc", "eMMC commands", 0, {
115 { REQ, "/sys/kernel/debug/tracing/events/mmc/enable" },
116 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700117 { "load", "CPU Load", 0, {
118 { REQ, "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800119 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700120 { "sync", "Synchronization", 0, {
121 { REQ, "/sys/kernel/debug/tracing/events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800122 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700123 { "workq", "Kernel Workqueues", 0, {
124 { REQ, "/sys/kernel/debug/tracing/events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800125 } },
126};
127
128/* Command line options */
129static int g_traceDurationSeconds = 5;
130static bool g_traceOverwrite = false;
131static int g_traceBufferSizeKB = 2048;
132static bool g_compress = false;
133static bool g_nohup = false;
134static int g_initialSleepSecs = 0;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700135static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700136static const char* g_debugAppCmdLine = "";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800137
138/* Global state */
139static bool g_traceAborted = false;
140static bool g_categoryEnables[NELEM(k_categories)] = {};
141
142/* Sys file paths */
143static const char* k_traceClockPath =
144 "/sys/kernel/debug/tracing/trace_clock";
145
146static const char* k_traceBufferSizePath =
147 "/sys/kernel/debug/tracing/buffer_size_kb";
148
149static const char* k_tracingOverwriteEnablePath =
150 "/sys/kernel/debug/tracing/options/overwrite";
151
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700152static const char* k_currentTracerPath =
153 "/sys/kernel/debug/tracing/current_tracer";
154
155static const char* k_printTgidPath =
156 "/sys/kernel/debug/tracing/options/print-tgid";
157
158static const char* k_funcgraphAbsTimePath =
159 "/sys/kernel/debug/tracing/options/funcgraph-abstime";
160
161static const char* k_funcgraphCpuPath =
162 "/sys/kernel/debug/tracing/options/funcgraph-cpu";
163
164static const char* k_funcgraphProcPath =
165 "/sys/kernel/debug/tracing/options/funcgraph-proc";
166
167static const char* k_funcgraphFlatPath =
168 "/sys/kernel/debug/tracing/options/funcgraph-flat";
169
170static const char* k_funcgraphDurationPath =
171 "/sys/kernel/debug/tracing/options/funcgraph-duration";
172
173static const char* k_ftraceFilterPath =
174 "/sys/kernel/debug/tracing/set_ftrace_filter";
175
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800176static const char* k_tracingOnPath =
177 "/sys/kernel/debug/tracing/tracing_on";
178
179static const char* k_tracePath =
180 "/sys/kernel/debug/tracing/trace";
181
182// Check whether a file exists.
183static bool fileExists(const char* filename) {
184 return access(filename, F_OK) != -1;
185}
186
187// Check whether a file is writable.
188static bool fileIsWritable(const char* filename) {
189 return access(filename, W_OK) != -1;
190}
191
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700192// Truncate a file.
193static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800194{
Jamie Gennis43122e72013-03-21 14:06:31 -0700195 // This uses creat rather than truncate because some of the debug kernel
196 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
197 // calls to truncate, but they are cleared by calls to creat.
198 int traceFD = creat(path, 0);
199 if (traceFD == -1) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700200 fprintf(stderr, "error truncating %s: %s (%d)\n", path,
Jamie Gennis43122e72013-03-21 14:06:31 -0700201 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700202 return false;
203 }
204
Jamie Gennis43122e72013-03-21 14:06:31 -0700205 close(traceFD);
206
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700207 return true;
208}
209
210static bool _writeStr(const char* filename, const char* str, int flags)
211{
212 int fd = open(filename, flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800213 if (fd == -1) {
214 fprintf(stderr, "error opening %s: %s (%d)\n", filename,
215 strerror(errno), errno);
216 return false;
217 }
218
219 bool ok = true;
220 ssize_t len = strlen(str);
221 if (write(fd, str, len) != len) {
222 fprintf(stderr, "error writing to %s: %s (%d)\n", filename,
223 strerror(errno), errno);
224 ok = false;
225 }
226
227 close(fd);
228
229 return ok;
230}
231
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700232// Write a string to a file, returning true if the write was successful.
233static bool writeStr(const char* filename, const char* str)
234{
235 return _writeStr(filename, str, O_WRONLY);
236}
237
238// Append a string to a file, returning true if the write was successful.
239static bool appendStr(const char* filename, const char* str)
240{
241 return _writeStr(filename, str, O_APPEND|O_WRONLY);
242}
243
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800244// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
245// file.
246static bool setKernelOptionEnable(const char* filename, bool enable)
247{
248 return writeStr(filename, enable ? "1" : "0");
249}
250
251// Check whether the category is supported on the device with the current
252// rootness. A category is supported only if all its required /sys/ files are
253// writable and if enabling the category will enable one or more tracing tags
254// or /sys/ files.
255static bool isCategorySupported(const TracingCategory& category)
256{
257 bool ok = category.tags != 0;
258 for (int i = 0; i < MAX_SYS_FILES; i++) {
259 const char* path = category.sysfiles[i].path;
260 bool req = category.sysfiles[i].required == REQ;
261 if (path != NULL) {
262 if (req) {
263 if (!fileIsWritable(path)) {
264 return false;
265 } else {
266 ok = true;
267 }
268 } else {
269 ok |= fileIsWritable(path);
270 }
271 }
272 }
273 return ok;
274}
275
276// Check whether the category would be supported on the device if the user
277// were root. This function assumes that root is able to write to any file
278// that exists. It performs the same logic as isCategorySupported, but it
279// uses file existance rather than writability in the /sys/ file checks.
280static bool isCategorySupportedForRoot(const TracingCategory& category)
281{
282 bool ok = category.tags != 0;
283 for (int i = 0; i < MAX_SYS_FILES; i++) {
284 const char* path = category.sysfiles[i].path;
285 bool req = category.sysfiles[i].required == REQ;
286 if (path != NULL) {
287 if (req) {
288 if (!fileExists(path)) {
289 return false;
290 } else {
291 ok = true;
292 }
293 } else {
294 ok |= fileExists(path);
295 }
296 }
297 }
298 return ok;
299}
300
301// Enable or disable overwriting of the kernel trace buffers. Disabling this
302// will cause tracing to stop once the trace buffers have filled up.
303static bool setTraceOverwriteEnable(bool enable)
304{
305 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
306}
307
308// Enable or disable kernel tracing.
309static bool setTracingEnabled(bool enable)
310{
311 return setKernelOptionEnable(k_tracingOnPath, enable);
312}
313
314// Clear the contents of the kernel trace.
315static bool clearTrace()
316{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700317 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800318}
319
320// Set the size of the kernel's trace buffer in kilobytes.
321static bool setTraceBufferSizeKB(int size)
322{
323 char str[32] = "1";
324 int len;
325 if (size < 1) {
326 size = 1;
327 }
328 snprintf(str, 32, "%d", size);
329 return writeStr(k_traceBufferSizePath, str);
330}
331
332// Enable or disable the kernel's use of the global clock. Disabling the global
333// clock will result in the kernel using a per-CPU local clock.
334static bool setGlobalClockEnable(bool enable)
335{
336 return writeStr(k_traceClockPath, enable ? "global" : "local");
337}
338
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700339static bool setPrintTgidEnableIfPresent(bool enable)
340{
341 if (fileExists(k_printTgidPath)) {
342 return setKernelOptionEnable(k_printTgidPath, enable);
343 }
344 return true;
345}
346
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800347// Poke all the binder-enabled processes in the system to get them to re-read
348// their system properties.
349static bool pokeBinderServices()
350{
351 sp<IServiceManager> sm = defaultServiceManager();
352 Vector<String16> services = sm->listServices();
353 for (size_t i = 0; i < services.size(); i++) {
354 sp<IBinder> obj = sm->checkService(services[i]);
355 if (obj != NULL) {
356 Parcel data;
357 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
358 NULL, 0) != OK) {
359 if (false) {
360 // XXX: For some reason this fails on tablets trying to
361 // poke the "phone" service. It's not clear whether some
362 // are expected to fail.
363 String8 svc(services[i]);
364 fprintf(stderr, "error poking binder service %s\n",
365 svc.string());
366 return false;
367 }
368 }
369 }
370 }
371 return true;
372}
373
374// Set the trace tags that userland tracing uses, and poke the running
375// processes to pick up the new value.
376static bool setTagsProperty(uint64_t tags)
377{
378 char buf[64];
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700379 snprintf(buf, 64, "%#" PRIx64, tags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800380 if (property_set(k_traceTagsProperty, buf) < 0) {
381 fprintf(stderr, "error setting trace tags system property\n");
382 return false;
383 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700384 return true;
385}
386
387// Set the system property that indicates which apps should perform
388// application-level tracing.
389static bool setAppCmdlineProperty(const char* cmdline)
390{
391 if (property_set(k_traceAppCmdlineProperty, cmdline) < 0) {
392 fprintf(stderr, "error setting trace app system property\n");
393 return false;
394 }
395 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800396}
397
398// Disable all /sys/ enable files.
399static bool disableKernelTraceEvents() {
400 bool ok = true;
401 for (int i = 0; i < NELEM(k_categories); i++) {
402 const TracingCategory &c = k_categories[i];
403 for (int j = 0; j < MAX_SYS_FILES; j++) {
404 const char* path = c.sysfiles[j].path;
405 if (path != NULL && fileIsWritable(path)) {
406 ok &= setKernelOptionEnable(path, false);
407 }
408 }
409 }
410 return ok;
411}
412
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700413// Verify that the comma separated list of functions are being traced by the
414// kernel.
415static bool verifyKernelTraceFuncs(const char* funcs)
416{
417 int fd = open(k_ftraceFilterPath, O_RDONLY);
418 if (fd == -1) {
419 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
420 strerror(errno), errno);
421 return false;
422 }
423
424 char buf[4097];
425 ssize_t n = read(fd, buf, 4096);
426 close(fd);
427 if (n == -1) {
428 fprintf(stderr, "error reading %s: %s (%d)\n", k_ftraceFilterPath,
429 strerror(errno), errno);
430 return false;
431 }
432
433 buf[n] = '\0';
434 String8 funcList = String8::format("\n%s", buf);
435
436 // Make sure that every function listed in funcs is in the list we just
437 // read from the kernel.
438 bool ok = true;
439 char* myFuncs = strdup(funcs);
440 char* func = strtok(myFuncs, ",");
441 while (func) {
442 String8 fancyFunc = String8::format("\n%s\n", func);
443 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
444 if (!found || func[0] == '\0') {
445 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
446 "to trace.\n", func);
447 ok = false;
448 }
449 func = strtok(NULL, ",");
450 }
451 free(myFuncs);
452
453 return ok;
454}
455
456// Set the comma separated list of functions that the kernel is to trace.
457static bool setKernelTraceFuncs(const char* funcs)
458{
459 bool ok = true;
460
461 if (funcs == NULL || funcs[0] == '\0') {
462 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700463 if (fileIsWritable(k_currentTracerPath)) {
464 ok &= writeStr(k_currentTracerPath, "nop");
465 }
466 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700467 ok &= truncateFile(k_ftraceFilterPath);
468 }
469 } else {
470 // Enable kernel function tracing.
471 ok &= writeStr(k_currentTracerPath, "function_graph");
472 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
473 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
474 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
475 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
476
477 // Set the requested filter functions.
478 ok &= truncateFile(k_ftraceFilterPath);
479 char* myFuncs = strdup(funcs);
480 char* func = strtok(myFuncs, ",");
481 while (func) {
482 ok &= appendStr(k_ftraceFilterPath, func);
483 func = strtok(NULL, ",");
484 }
485 free(myFuncs);
486
487 // Verify that the set functions are being traced.
488 if (ok) {
489 ok &= verifyKernelTraceFuncs(funcs);
490 }
491 }
492
493 return ok;
494}
495
496// Set all the kernel tracing settings to the desired state for this trace
497// capture.
498static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800499{
500 bool ok = true;
501
502 // Set up the tracing options.
503 ok &= setTraceOverwriteEnable(g_traceOverwrite);
504 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
505 ok &= setGlobalClockEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700506 ok &= setPrintTgidEnableIfPresent(true);
507 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800508
509 // Set up the tags property.
510 uint64_t tags = 0;
511 for (int i = 0; i < NELEM(k_categories); i++) {
512 if (g_categoryEnables[i]) {
513 const TracingCategory &c = k_categories[i];
514 tags |= c.tags;
515 }
516 }
517 ok &= setTagsProperty(tags);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700518 ok &= setAppCmdlineProperty(g_debugAppCmdLine);
519 ok &= pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800520
521 // Disable all the sysfs enables. This is done as a separate loop from
522 // the enables to allow the same enable to exist in multiple categories.
523 ok &= disableKernelTraceEvents();
524
525 // Enable all the sysfs enables that are in an enabled category.
526 for (int i = 0; i < NELEM(k_categories); i++) {
527 if (g_categoryEnables[i]) {
528 const TracingCategory &c = k_categories[i];
529 for (int j = 0; j < MAX_SYS_FILES; j++) {
530 const char* path = c.sysfiles[j].path;
531 bool required = c.sysfiles[j].required == REQ;
532 if (path != NULL) {
533 if (fileIsWritable(path)) {
534 ok &= setKernelOptionEnable(path, true);
535 } else if (required) {
536 fprintf(stderr, "error writing file %s\n", path);
537 ok = false;
538 }
539 }
540 }
541 }
542 }
543
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800544 return ok;
545}
546
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700547// Reset all the kernel tracing settings to their default state.
548static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800549{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800550 // Disable all tracing that we're able to.
551 disableKernelTraceEvents();
552
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700553 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800554 setTagsProperty(0);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700555 setAppCmdlineProperty("");
556 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800557
558 // Set the options back to their defaults.
559 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700560 setTraceBufferSizeKB(1);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800561 setGlobalClockEnable(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700562 setPrintTgidEnableIfPresent(false);
563 setKernelTraceFuncs(NULL);
564}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800565
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700566
567// Enable tracing in the kernel.
568static bool startTrace()
569{
570 return setTracingEnabled(true);
571}
572
573// Disable tracing in the kernel.
574static void stopTrace()
575{
576 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800577}
578
579// Read the current kernel trace and write it to stdout.
580static void dumpTrace()
581{
582 int traceFD = open(k_tracePath, O_RDWR);
583 if (traceFD == -1) {
584 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
585 strerror(errno), errno);
586 return;
587 }
588
589 if (g_compress) {
590 z_stream zs;
591 uint8_t *in, *out;
592 int result, flush;
593
594 bzero(&zs, sizeof(zs));
595 result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
596 if (result != Z_OK) {
597 fprintf(stderr, "error initializing zlib: %d\n", result);
598 close(traceFD);
599 return;
600 }
601
602 const size_t bufSize = 64*1024;
603 in = (uint8_t*)malloc(bufSize);
604 out = (uint8_t*)malloc(bufSize);
605 flush = Z_NO_FLUSH;
606
607 zs.next_out = out;
608 zs.avail_out = bufSize;
609
610 do {
611
612 if (zs.avail_in == 0) {
613 // More input is needed.
614 result = read(traceFD, in, bufSize);
615 if (result < 0) {
616 fprintf(stderr, "error reading trace: %s (%d)\n",
617 strerror(errno), errno);
618 result = Z_STREAM_END;
619 break;
620 } else if (result == 0) {
621 flush = Z_FINISH;
622 } else {
623 zs.next_in = in;
624 zs.avail_in = result;
625 }
626 }
627
628 if (zs.avail_out == 0) {
629 // Need to write the output.
630 result = write(STDOUT_FILENO, out, bufSize);
631 if ((size_t)result < bufSize) {
632 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
633 strerror(errno), errno);
634 result = Z_STREAM_END; // skip deflate error message
635 zs.avail_out = bufSize; // skip the final write
636 break;
637 }
638 zs.next_out = out;
639 zs.avail_out = bufSize;
640 }
641
642 } while ((result = deflate(&zs, flush)) == Z_OK);
643
644 if (result != Z_STREAM_END) {
645 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
646 }
647
648 if (zs.avail_out < bufSize) {
649 size_t bytes = bufSize - zs.avail_out;
650 result = write(STDOUT_FILENO, out, bytes);
651 if ((size_t)result < bytes) {
652 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
653 strerror(errno), errno);
654 }
655 }
656
657 result = deflateEnd(&zs);
658 if (result != Z_OK) {
659 fprintf(stderr, "error cleaning up zlib: %d\n", result);
660 }
661
662 free(in);
663 free(out);
664 } else {
665 ssize_t sent = 0;
666 while ((sent = sendfile(STDOUT_FILENO, traceFD, NULL, 64*1024*1024)) > 0);
667 if (sent == -1) {
668 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
669 errno);
670 }
671 }
672
673 close(traceFD);
674}
675
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700676static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800677{
678 if (!g_nohup) {
679 g_traceAborted = true;
680 }
681}
682
683static void registerSigHandler()
684{
685 struct sigaction sa;
686 sigemptyset(&sa.sa_mask);
687 sa.sa_flags = 0;
688 sa.sa_handler = handleSignal;
689 sigaction(SIGHUP, &sa, NULL);
690 sigaction(SIGINT, &sa, NULL);
691 sigaction(SIGQUIT, &sa, NULL);
692 sigaction(SIGTERM, &sa, NULL);
693}
694
695static bool setCategoryEnable(const char* name, bool enable)
696{
697 for (int i = 0; i < NELEM(k_categories); i++) {
698 const TracingCategory& c = k_categories[i];
699 if (strcmp(name, c.name) == 0) {
700 if (isCategorySupported(c)) {
701 g_categoryEnables[i] = enable;
702 return true;
703 } else {
704 if (isCategorySupportedForRoot(c)) {
705 fprintf(stderr, "error: category \"%s\" requires root "
706 "privileges.\n", name);
707 } else {
708 fprintf(stderr, "error: category \"%s\" is not supported "
709 "on this device.\n", name);
710 }
711 return false;
712 }
713 }
714 }
715 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
716 return false;
717}
718
719static void listSupportedCategories()
720{
721 for (int i = 0; i < NELEM(k_categories); i++) {
722 const TracingCategory& c = k_categories[i];
723 if (isCategorySupported(c)) {
724 printf(" %10s - %s\n", c.name, c.longname);
725 }
726 }
727}
728
729// Print the command usage help to stderr.
730static void showHelp(const char *cmd)
731{
732 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
733 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700734 " -a appname enable app-level tracing for a comma "
735 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800736 " -b N use a trace buffer size of N KB\n"
737 " -c trace into a circular buffer\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700738 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800739 " -n ignore signals\n"
740 " -s N sleep for N seconds before tracing [default 0]\n"
741 " -t N trace for N seconds [defualt 5]\n"
742 " -z compress the trace dump\n"
743 " --async_start start circular trace and return immediatly\n"
744 " --async_dump dump the current contents of circular trace buffer\n"
745 " --async_stop stop tracing and dump the current contents of circular\n"
746 " trace buffer\n"
Jamie Gennis92573f12012-12-07 16:29:03 -0800747 " --list_categories\n"
748 " list the available tracing categories\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800749 );
750}
751
752int main(int argc, char **argv)
753{
754 bool async = false;
755 bool traceStart = true;
756 bool traceStop = true;
757 bool traceDump = true;
758
759 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
760 showHelp(argv[0]);
761 exit(0);
762 }
763
764 for (;;) {
765 int ret;
766 int option_index = 0;
767 static struct option long_options[] = {
768 {"async_start", no_argument, 0, 0 },
769 {"async_stop", no_argument, 0, 0 },
770 {"async_dump", no_argument, 0, 0 },
771 {"list_categories", no_argument, 0, 0 },
772 { 0, 0, 0, 0 }
773 };
774
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700775 ret = getopt_long(argc, argv, "a:b:ck:ns:t:z",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800776 long_options, &option_index);
777
778 if (ret < 0) {
779 for (int i = optind; i < argc; i++) {
780 if (!setCategoryEnable(argv[i], true)) {
781 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
782 exit(1);
783 }
784 }
785 break;
786 }
787
788 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700789 case 'a':
790 g_debugAppCmdLine = optarg;
791 break;
792
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800793 case 'b':
794 g_traceBufferSizeKB = atoi(optarg);
795 break;
796
797 case 'c':
798 g_traceOverwrite = true;
799 break;
800
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700801 case 'k':
802 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700803 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700804
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800805 case 'n':
806 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700807 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800808
809 case 's':
810 g_initialSleepSecs = atoi(optarg);
811 break;
812
813 case 't':
814 g_traceDurationSeconds = atoi(optarg);
815 break;
816
817 case 'z':
818 g_compress = true;
819 break;
820
821 case 0:
822 if (!strcmp(long_options[option_index].name, "async_start")) {
823 async = true;
824 traceStop = false;
825 traceDump = false;
826 g_traceOverwrite = true;
827 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
828 async = true;
829 traceStop = false;
830 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
831 async = true;
832 traceStart = false;
833 traceStop = false;
834 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
835 listSupportedCategories();
836 exit(0);
837 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700838 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800839
840 default:
841 fprintf(stderr, "\n");
842 showHelp(argv[0]);
843 exit(-1);
844 break;
845 }
846 }
847
848 registerSigHandler();
849
850 if (g_initialSleepSecs > 0) {
851 sleep(g_initialSleepSecs);
852 }
853
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700854 bool ok = true;
855 ok &= setUpTrace();
856 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800857
858 if (ok && traceStart) {
859 printf("capturing trace...");
860 fflush(stdout);
861
862 // We clear the trace after starting it because tracing gets enabled for
863 // each CPU individually in the kernel. Having the beginning of the trace
864 // contain entries from only one CPU can cause "begin" entries without a
865 // matching "end" entry to show up if a task gets migrated from one CPU to
866 // another.
867 ok = clearTrace();
868
869 if (ok && !async) {
870 // Sleep to allow the trace to be captured.
871 struct timespec timeLeft;
872 timeLeft.tv_sec = g_traceDurationSeconds;
873 timeLeft.tv_nsec = 0;
874 do {
875 if (g_traceAborted) {
876 break;
877 }
878 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
879 }
880 }
881
882 // Stop the trace and restore the default settings.
883 if (traceStop)
884 stopTrace();
885
886 if (ok && traceDump) {
887 if (!g_traceAborted) {
888 printf(" done\nTRACE:\n");
889 fflush(stdout);
890 dumpTrace();
891 } else {
892 printf("\ntrace aborted.\n");
893 fflush(stdout);
894 }
895 clearTrace();
896 } else if (!ok) {
897 fprintf(stderr, "unable to start tracing\n");
898 }
899
900 // Reset the trace buffer size to 1.
901 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700902 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800903
904 return g_traceAborted ? 1 : 0;
905}