blob: 9688cc67c9762d9ba35c55b2d562bbe57a8c169e [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 } },
132};
133
134/* Command line options */
135static int g_traceDurationSeconds = 5;
136static bool g_traceOverwrite = false;
137static int g_traceBufferSizeKB = 2048;
138static bool g_compress = false;
139static bool g_nohup = false;
140static int g_initialSleepSecs = 0;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700141static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700142static const char* g_debugAppCmdLine = "";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800143
144/* Global state */
145static bool g_traceAborted = false;
146static bool g_categoryEnables[NELEM(k_categories)] = {};
147
148/* Sys file paths */
149static const char* k_traceClockPath =
150 "/sys/kernel/debug/tracing/trace_clock";
151
152static const char* k_traceBufferSizePath =
153 "/sys/kernel/debug/tracing/buffer_size_kb";
154
155static const char* k_tracingOverwriteEnablePath =
156 "/sys/kernel/debug/tracing/options/overwrite";
157
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700158static const char* k_currentTracerPath =
159 "/sys/kernel/debug/tracing/current_tracer";
160
161static const char* k_printTgidPath =
162 "/sys/kernel/debug/tracing/options/print-tgid";
163
164static const char* k_funcgraphAbsTimePath =
165 "/sys/kernel/debug/tracing/options/funcgraph-abstime";
166
167static const char* k_funcgraphCpuPath =
168 "/sys/kernel/debug/tracing/options/funcgraph-cpu";
169
170static const char* k_funcgraphProcPath =
171 "/sys/kernel/debug/tracing/options/funcgraph-proc";
172
173static const char* k_funcgraphFlatPath =
174 "/sys/kernel/debug/tracing/options/funcgraph-flat";
175
176static const char* k_funcgraphDurationPath =
177 "/sys/kernel/debug/tracing/options/funcgraph-duration";
178
179static const char* k_ftraceFilterPath =
180 "/sys/kernel/debug/tracing/set_ftrace_filter";
181
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800182static const char* k_tracingOnPath =
183 "/sys/kernel/debug/tracing/tracing_on";
184
185static const char* k_tracePath =
186 "/sys/kernel/debug/tracing/trace";
187
188// Check whether a file exists.
189static bool fileExists(const char* filename) {
190 return access(filename, F_OK) != -1;
191}
192
193// Check whether a file is writable.
194static bool fileIsWritable(const char* filename) {
195 return access(filename, W_OK) != -1;
196}
197
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700198// Truncate a file.
199static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800200{
Jamie Gennis43122e72013-03-21 14:06:31 -0700201 // This uses creat rather than truncate because some of the debug kernel
202 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
203 // calls to truncate, but they are cleared by calls to creat.
204 int traceFD = creat(path, 0);
205 if (traceFD == -1) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700206 fprintf(stderr, "error truncating %s: %s (%d)\n", path,
Jamie Gennis43122e72013-03-21 14:06:31 -0700207 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700208 return false;
209 }
210
Jamie Gennis43122e72013-03-21 14:06:31 -0700211 close(traceFD);
212
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700213 return true;
214}
215
216static bool _writeStr(const char* filename, const char* str, int flags)
217{
218 int fd = open(filename, flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800219 if (fd == -1) {
220 fprintf(stderr, "error opening %s: %s (%d)\n", filename,
221 strerror(errno), errno);
222 return false;
223 }
224
225 bool ok = true;
226 ssize_t len = strlen(str);
227 if (write(fd, str, len) != len) {
228 fprintf(stderr, "error writing to %s: %s (%d)\n", filename,
229 strerror(errno), errno);
230 ok = false;
231 }
232
233 close(fd);
234
235 return ok;
236}
237
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700238// Write a string to a file, returning true if the write was successful.
239static bool writeStr(const char* filename, const char* str)
240{
241 return _writeStr(filename, str, O_WRONLY);
242}
243
244// Append a string to a file, returning true if the write was successful.
245static bool appendStr(const char* filename, const char* str)
246{
247 return _writeStr(filename, str, O_APPEND|O_WRONLY);
248}
249
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800250// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
251// file.
252static bool setKernelOptionEnable(const char* filename, bool enable)
253{
254 return writeStr(filename, enable ? "1" : "0");
255}
256
257// Check whether the category is supported on the device with the current
258// rootness. A category is supported only if all its required /sys/ files are
259// writable and if enabling the category will enable one or more tracing tags
260// or /sys/ files.
261static bool isCategorySupported(const TracingCategory& category)
262{
263 bool ok = category.tags != 0;
264 for (int i = 0; i < MAX_SYS_FILES; i++) {
265 const char* path = category.sysfiles[i].path;
266 bool req = category.sysfiles[i].required == REQ;
267 if (path != NULL) {
268 if (req) {
269 if (!fileIsWritable(path)) {
270 return false;
271 } else {
272 ok = true;
273 }
274 } else {
275 ok |= fileIsWritable(path);
276 }
277 }
278 }
279 return ok;
280}
281
282// Check whether the category would be supported on the device if the user
283// were root. This function assumes that root is able to write to any file
284// that exists. It performs the same logic as isCategorySupported, but it
285// uses file existance rather than writability in the /sys/ file checks.
286static bool isCategorySupportedForRoot(const TracingCategory& category)
287{
288 bool ok = category.tags != 0;
289 for (int i = 0; i < MAX_SYS_FILES; i++) {
290 const char* path = category.sysfiles[i].path;
291 bool req = category.sysfiles[i].required == REQ;
292 if (path != NULL) {
293 if (req) {
294 if (!fileExists(path)) {
295 return false;
296 } else {
297 ok = true;
298 }
299 } else {
300 ok |= fileExists(path);
301 }
302 }
303 }
304 return ok;
305}
306
307// Enable or disable overwriting of the kernel trace buffers. Disabling this
308// will cause tracing to stop once the trace buffers have filled up.
309static bool setTraceOverwriteEnable(bool enable)
310{
311 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
312}
313
314// Enable or disable kernel tracing.
315static bool setTracingEnabled(bool enable)
316{
317 return setKernelOptionEnable(k_tracingOnPath, enable);
318}
319
320// Clear the contents of the kernel trace.
321static bool clearTrace()
322{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700323 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800324}
325
326// Set the size of the kernel's trace buffer in kilobytes.
327static bool setTraceBufferSizeKB(int size)
328{
329 char str[32] = "1";
330 int len;
331 if (size < 1) {
332 size = 1;
333 }
334 snprintf(str, 32, "%d", size);
335 return writeStr(k_traceBufferSizePath, str);
336}
337
338// Enable or disable the kernel's use of the global clock. Disabling the global
339// clock will result in the kernel using a per-CPU local clock.
340static bool setGlobalClockEnable(bool enable)
341{
342 return writeStr(k_traceClockPath, enable ? "global" : "local");
343}
344
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700345static bool setPrintTgidEnableIfPresent(bool enable)
346{
347 if (fileExists(k_printTgidPath)) {
348 return setKernelOptionEnable(k_printTgidPath, enable);
349 }
350 return true;
351}
352
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800353// Poke all the binder-enabled processes in the system to get them to re-read
354// their system properties.
355static bool pokeBinderServices()
356{
357 sp<IServiceManager> sm = defaultServiceManager();
358 Vector<String16> services = sm->listServices();
359 for (size_t i = 0; i < services.size(); i++) {
360 sp<IBinder> obj = sm->checkService(services[i]);
361 if (obj != NULL) {
362 Parcel data;
363 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
364 NULL, 0) != OK) {
365 if (false) {
366 // XXX: For some reason this fails on tablets trying to
367 // poke the "phone" service. It's not clear whether some
368 // are expected to fail.
369 String8 svc(services[i]);
370 fprintf(stderr, "error poking binder service %s\n",
371 svc.string());
372 return false;
373 }
374 }
375 }
376 }
377 return true;
378}
379
380// Set the trace tags that userland tracing uses, and poke the running
381// processes to pick up the new value.
382static bool setTagsProperty(uint64_t tags)
383{
384 char buf[64];
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700385 snprintf(buf, 64, "%#" PRIx64, tags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800386 if (property_set(k_traceTagsProperty, buf) < 0) {
387 fprintf(stderr, "error setting trace tags system property\n");
388 return false;
389 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700390 return true;
391}
392
393// Set the system property that indicates which apps should perform
394// application-level tracing.
395static bool setAppCmdlineProperty(const char* cmdline)
396{
397 if (property_set(k_traceAppCmdlineProperty, cmdline) < 0) {
398 fprintf(stderr, "error setting trace app system property\n");
399 return false;
400 }
401 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800402}
403
404// Disable all /sys/ enable files.
405static bool disableKernelTraceEvents() {
406 bool ok = true;
407 for (int i = 0; i < NELEM(k_categories); i++) {
408 const TracingCategory &c = k_categories[i];
409 for (int j = 0; j < MAX_SYS_FILES; j++) {
410 const char* path = c.sysfiles[j].path;
411 if (path != NULL && fileIsWritable(path)) {
412 ok &= setKernelOptionEnable(path, false);
413 }
414 }
415 }
416 return ok;
417}
418
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700419// Verify that the comma separated list of functions are being traced by the
420// kernel.
421static bool verifyKernelTraceFuncs(const char* funcs)
422{
423 int fd = open(k_ftraceFilterPath, O_RDONLY);
424 if (fd == -1) {
425 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
426 strerror(errno), errno);
427 return false;
428 }
429
430 char buf[4097];
431 ssize_t n = read(fd, buf, 4096);
432 close(fd);
433 if (n == -1) {
434 fprintf(stderr, "error reading %s: %s (%d)\n", k_ftraceFilterPath,
435 strerror(errno), errno);
436 return false;
437 }
438
439 buf[n] = '\0';
440 String8 funcList = String8::format("\n%s", buf);
441
442 // Make sure that every function listed in funcs is in the list we just
443 // read from the kernel.
444 bool ok = true;
445 char* myFuncs = strdup(funcs);
446 char* func = strtok(myFuncs, ",");
447 while (func) {
448 String8 fancyFunc = String8::format("\n%s\n", func);
449 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
450 if (!found || func[0] == '\0') {
451 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
452 "to trace.\n", func);
453 ok = false;
454 }
455 func = strtok(NULL, ",");
456 }
457 free(myFuncs);
458
459 return ok;
460}
461
462// Set the comma separated list of functions that the kernel is to trace.
463static bool setKernelTraceFuncs(const char* funcs)
464{
465 bool ok = true;
466
467 if (funcs == NULL || funcs[0] == '\0') {
468 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700469 if (fileIsWritable(k_currentTracerPath)) {
470 ok &= writeStr(k_currentTracerPath, "nop");
471 }
472 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700473 ok &= truncateFile(k_ftraceFilterPath);
474 }
475 } else {
476 // Enable kernel function tracing.
477 ok &= writeStr(k_currentTracerPath, "function_graph");
478 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
479 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
480 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
481 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
482
483 // Set the requested filter functions.
484 ok &= truncateFile(k_ftraceFilterPath);
485 char* myFuncs = strdup(funcs);
486 char* func = strtok(myFuncs, ",");
487 while (func) {
488 ok &= appendStr(k_ftraceFilterPath, func);
489 func = strtok(NULL, ",");
490 }
491 free(myFuncs);
492
493 // Verify that the set functions are being traced.
494 if (ok) {
495 ok &= verifyKernelTraceFuncs(funcs);
496 }
497 }
498
499 return ok;
500}
501
502// Set all the kernel tracing settings to the desired state for this trace
503// capture.
504static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800505{
506 bool ok = true;
507
508 // Set up the tracing options.
509 ok &= setTraceOverwriteEnable(g_traceOverwrite);
510 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
511 ok &= setGlobalClockEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700512 ok &= setPrintTgidEnableIfPresent(true);
513 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800514
515 // Set up the tags property.
516 uint64_t tags = 0;
517 for (int i = 0; i < NELEM(k_categories); i++) {
518 if (g_categoryEnables[i]) {
519 const TracingCategory &c = k_categories[i];
520 tags |= c.tags;
521 }
522 }
523 ok &= setTagsProperty(tags);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700524 ok &= setAppCmdlineProperty(g_debugAppCmdLine);
525 ok &= pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800526
527 // Disable all the sysfs enables. This is done as a separate loop from
528 // the enables to allow the same enable to exist in multiple categories.
529 ok &= disableKernelTraceEvents();
530
531 // Enable all the sysfs enables that are in an enabled category.
532 for (int i = 0; i < NELEM(k_categories); i++) {
533 if (g_categoryEnables[i]) {
534 const TracingCategory &c = k_categories[i];
535 for (int j = 0; j < MAX_SYS_FILES; j++) {
536 const char* path = c.sysfiles[j].path;
537 bool required = c.sysfiles[j].required == REQ;
538 if (path != NULL) {
539 if (fileIsWritable(path)) {
540 ok &= setKernelOptionEnable(path, true);
541 } else if (required) {
542 fprintf(stderr, "error writing file %s\n", path);
543 ok = false;
544 }
545 }
546 }
547 }
548 }
549
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800550 return ok;
551}
552
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700553// Reset all the kernel tracing settings to their default state.
554static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800555{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800556 // Disable all tracing that we're able to.
557 disableKernelTraceEvents();
558
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700559 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800560 setTagsProperty(0);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700561 setAppCmdlineProperty("");
562 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800563
564 // Set the options back to their defaults.
565 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700566 setTraceBufferSizeKB(1);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800567 setGlobalClockEnable(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700568 setPrintTgidEnableIfPresent(false);
569 setKernelTraceFuncs(NULL);
570}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800571
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700572
573// Enable tracing in the kernel.
574static bool startTrace()
575{
576 return setTracingEnabled(true);
577}
578
579// Disable tracing in the kernel.
580static void stopTrace()
581{
582 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800583}
584
585// Read the current kernel trace and write it to stdout.
586static void dumpTrace()
587{
588 int traceFD = open(k_tracePath, O_RDWR);
589 if (traceFD == -1) {
590 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
591 strerror(errno), errno);
592 return;
593 }
594
595 if (g_compress) {
596 z_stream zs;
597 uint8_t *in, *out;
598 int result, flush;
599
600 bzero(&zs, sizeof(zs));
601 result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
602 if (result != Z_OK) {
603 fprintf(stderr, "error initializing zlib: %d\n", result);
604 close(traceFD);
605 return;
606 }
607
608 const size_t bufSize = 64*1024;
609 in = (uint8_t*)malloc(bufSize);
610 out = (uint8_t*)malloc(bufSize);
611 flush = Z_NO_FLUSH;
612
613 zs.next_out = out;
614 zs.avail_out = bufSize;
615
616 do {
617
618 if (zs.avail_in == 0) {
619 // More input is needed.
620 result = read(traceFD, in, bufSize);
621 if (result < 0) {
622 fprintf(stderr, "error reading trace: %s (%d)\n",
623 strerror(errno), errno);
624 result = Z_STREAM_END;
625 break;
626 } else if (result == 0) {
627 flush = Z_FINISH;
628 } else {
629 zs.next_in = in;
630 zs.avail_in = result;
631 }
632 }
633
634 if (zs.avail_out == 0) {
635 // Need to write the output.
636 result = write(STDOUT_FILENO, out, bufSize);
637 if ((size_t)result < bufSize) {
638 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
639 strerror(errno), errno);
640 result = Z_STREAM_END; // skip deflate error message
641 zs.avail_out = bufSize; // skip the final write
642 break;
643 }
644 zs.next_out = out;
645 zs.avail_out = bufSize;
646 }
647
648 } while ((result = deflate(&zs, flush)) == Z_OK);
649
650 if (result != Z_STREAM_END) {
651 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
652 }
653
654 if (zs.avail_out < bufSize) {
655 size_t bytes = bufSize - zs.avail_out;
656 result = write(STDOUT_FILENO, out, bytes);
657 if ((size_t)result < bytes) {
658 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
659 strerror(errno), errno);
660 }
661 }
662
663 result = deflateEnd(&zs);
664 if (result != Z_OK) {
665 fprintf(stderr, "error cleaning up zlib: %d\n", result);
666 }
667
668 free(in);
669 free(out);
670 } else {
671 ssize_t sent = 0;
672 while ((sent = sendfile(STDOUT_FILENO, traceFD, NULL, 64*1024*1024)) > 0);
673 if (sent == -1) {
674 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
675 errno);
676 }
677 }
678
679 close(traceFD);
680}
681
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700682static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800683{
684 if (!g_nohup) {
685 g_traceAborted = true;
686 }
687}
688
689static void registerSigHandler()
690{
691 struct sigaction sa;
692 sigemptyset(&sa.sa_mask);
693 sa.sa_flags = 0;
694 sa.sa_handler = handleSignal;
695 sigaction(SIGHUP, &sa, NULL);
696 sigaction(SIGINT, &sa, NULL);
697 sigaction(SIGQUIT, &sa, NULL);
698 sigaction(SIGTERM, &sa, NULL);
699}
700
701static bool setCategoryEnable(const char* name, bool enable)
702{
703 for (int i = 0; i < NELEM(k_categories); i++) {
704 const TracingCategory& c = k_categories[i];
705 if (strcmp(name, c.name) == 0) {
706 if (isCategorySupported(c)) {
707 g_categoryEnables[i] = enable;
708 return true;
709 } else {
710 if (isCategorySupportedForRoot(c)) {
711 fprintf(stderr, "error: category \"%s\" requires root "
712 "privileges.\n", name);
713 } else {
714 fprintf(stderr, "error: category \"%s\" is not supported "
715 "on this device.\n", name);
716 }
717 return false;
718 }
719 }
720 }
721 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
722 return false;
723}
724
725static void listSupportedCategories()
726{
727 for (int i = 0; i < NELEM(k_categories); i++) {
728 const TracingCategory& c = k_categories[i];
729 if (isCategorySupported(c)) {
730 printf(" %10s - %s\n", c.name, c.longname);
731 }
732 }
733}
734
735// Print the command usage help to stderr.
736static void showHelp(const char *cmd)
737{
738 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
739 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700740 " -a appname enable app-level tracing for a comma "
741 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800742 " -b N use a trace buffer size of N KB\n"
743 " -c trace into a circular buffer\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700744 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800745 " -n ignore signals\n"
746 " -s N sleep for N seconds before tracing [default 0]\n"
747 " -t N trace for N seconds [defualt 5]\n"
748 " -z compress the trace dump\n"
749 " --async_start start circular trace and return immediatly\n"
750 " --async_dump dump the current contents of circular trace buffer\n"
751 " --async_stop stop tracing and dump the current contents of circular\n"
752 " trace buffer\n"
Jamie Gennis92573f12012-12-07 16:29:03 -0800753 " --list_categories\n"
754 " list the available tracing categories\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800755 );
756}
757
758int main(int argc, char **argv)
759{
760 bool async = false;
761 bool traceStart = true;
762 bool traceStop = true;
763 bool traceDump = true;
764
765 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
766 showHelp(argv[0]);
767 exit(0);
768 }
769
770 for (;;) {
771 int ret;
772 int option_index = 0;
773 static struct option long_options[] = {
774 {"async_start", no_argument, 0, 0 },
775 {"async_stop", no_argument, 0, 0 },
776 {"async_dump", no_argument, 0, 0 },
777 {"list_categories", no_argument, 0, 0 },
778 { 0, 0, 0, 0 }
779 };
780
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700781 ret = getopt_long(argc, argv, "a:b:ck:ns:t:z",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800782 long_options, &option_index);
783
784 if (ret < 0) {
785 for (int i = optind; i < argc; i++) {
786 if (!setCategoryEnable(argv[i], true)) {
787 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
788 exit(1);
789 }
790 }
791 break;
792 }
793
794 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700795 case 'a':
796 g_debugAppCmdLine = optarg;
797 break;
798
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800799 case 'b':
800 g_traceBufferSizeKB = atoi(optarg);
801 break;
802
803 case 'c':
804 g_traceOverwrite = true;
805 break;
806
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700807 case 'k':
808 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700809 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700810
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800811 case 'n':
812 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700813 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800814
815 case 's':
816 g_initialSleepSecs = atoi(optarg);
817 break;
818
819 case 't':
820 g_traceDurationSeconds = atoi(optarg);
821 break;
822
823 case 'z':
824 g_compress = true;
825 break;
826
827 case 0:
828 if (!strcmp(long_options[option_index].name, "async_start")) {
829 async = true;
830 traceStop = false;
831 traceDump = false;
832 g_traceOverwrite = true;
833 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
834 async = true;
835 traceStop = false;
836 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
837 async = true;
838 traceStart = false;
839 traceStop = false;
840 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
841 listSupportedCategories();
842 exit(0);
843 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700844 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800845
846 default:
847 fprintf(stderr, "\n");
848 showHelp(argv[0]);
849 exit(-1);
850 break;
851 }
852 }
853
854 registerSigHandler();
855
856 if (g_initialSleepSecs > 0) {
857 sleep(g_initialSleepSecs);
858 }
859
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700860 bool ok = true;
861 ok &= setUpTrace();
862 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800863
864 if (ok && traceStart) {
865 printf("capturing trace...");
866 fflush(stdout);
867
868 // We clear the trace after starting it because tracing gets enabled for
869 // each CPU individually in the kernel. Having the beginning of the trace
870 // contain entries from only one CPU can cause "begin" entries without a
871 // matching "end" entry to show up if a task gets migrated from one CPU to
872 // another.
873 ok = clearTrace();
874
875 if (ok && !async) {
876 // Sleep to allow the trace to be captured.
877 struct timespec timeLeft;
878 timeLeft.tv_sec = g_traceDurationSeconds;
879 timeLeft.tv_nsec = 0;
880 do {
881 if (g_traceAborted) {
882 break;
883 }
884 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
885 }
886 }
887
888 // Stop the trace and restore the default settings.
889 if (traceStop)
890 stopTrace();
891
892 if (ok && traceDump) {
893 if (!g_traceAborted) {
894 printf(" done\nTRACE:\n");
895 fflush(stdout);
896 dumpTrace();
897 } else {
898 printf("\ntrace aborted.\n");
899 fflush(stdout);
900 }
901 clearTrace();
902 } else if (!ok) {
903 fprintf(stderr, "unable to start tracing\n");
904 }
905
906 // Reset the trace buffer size to 1.
907 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700908 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800909
910 return g_traceAborted ? 1 : 0;
911}