blob: d63019b683edbf93528bec947b8883d49f224b8f [file] [log] [blame]
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <errno.h>
18#include <fcntl.h>
19#include <getopt.h>
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070020#include <inttypes.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080021#include <signal.h>
22#include <stdarg.h>
23#include <stdbool.h>
24#include <stdio.h>
25#include <stdlib.h>
Elliott Hughes3da5d232015-01-25 08:35:20 -080026#include <string.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080027#include <sys/sendfile.h>
28#include <time.h>
29#include <zlib.h>
30
31#include <binder/IBinder.h>
32#include <binder/IServiceManager.h>
33#include <binder/Parcel.h>
34
35#include <cutils/properties.h>
36
37#include <utils/String8.h>
John Reck469a1942015-03-26 15:31:35 -070038#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +090039#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080040#include <utils/Trace.h>
41
42using namespace android;
43
44#define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0])))
45
Mohamad Ayyash26dbcbe2014-04-08 15:24:11 -070046enum { MAX_SYS_FILES = 10 };
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080047
48const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
Jamie Gennisf7f29c82013-03-27 15:50:58 -070049const char* k_traceAppCmdlineProperty = "debug.atrace.app_cmdlines";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080050
51typedef enum { OPT, REQ } requiredness ;
52
53struct TracingCategory {
54 // The name identifying the category.
55 const char* name;
56
57 // A longer description of the category.
58 const char* longname;
59
60 // The userland tracing tags that the category enables.
61 uint64_t tags;
62
63 // The fname==NULL terminated list of /sys/ files that the category
64 // enables.
65 struct {
66 // Whether the file must be writable in order to enable the tracing
67 // category.
68 requiredness required;
69
70 // The path to the enable file.
71 const char* path;
72 } sysfiles[MAX_SYS_FILES];
73};
74
75/* Tracing categories */
76static const TracingCategory k_categories[] = {
Jamie Gennisb2a89e32013-03-11 19:37:53 -070077 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, { } },
78 { "input", "Input", ATRACE_TAG_INPUT, { } },
79 { "view", "View System", ATRACE_TAG_VIEW, { } },
80 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
81 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
82 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -050083 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070084 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
85 { "video", "Video", ATRACE_TAG_VIDEO, { } },
86 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
87 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -070088 { "app", "Application", ATRACE_TAG_APP, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -070089 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -070090 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -070091 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -070092 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -070093 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 14:36:20 -070094 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-07-01 01:46:25 +090095 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070096 { "sched", "CPU Scheduling", 0, {
97 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_switch/enable" },
98 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_wakeup/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080099 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700100 { "irq", "IRQ Events", 0, {
101 { REQ, "/sys/kernel/debug/tracing/events/irq/enable" },
102 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700103 { "freq", "CPU Frequency", 0, {
104 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_frequency/enable" },
105 { OPT, "/sys/kernel/debug/tracing/events/power/clock_set_rate/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800106 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700107 { "membus", "Memory Bus Utilization", 0, {
108 { REQ, "/sys/kernel/debug/tracing/events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800109 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700110 { "idle", "CPU Idle", 0, {
111 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800112 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700113 { "disk", "Disk I/O", 0, {
Greg Hackmanne80d32c2014-11-20 12:59:44 -0800114 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_enter/enable" },
115 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_exit/enable" },
116 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_begin/enable" },
117 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_end/enable" },
118 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_begin/enable" },
119 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_end/enable" },
120 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable" },
121 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable" },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700122 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" },
123 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800124 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700125 { "mmc", "eMMC commands", 0, {
126 { REQ, "/sys/kernel/debug/tracing/events/mmc/enable" },
127 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700128 { "load", "CPU Load", 0, {
129 { REQ, "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800130 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700131 { "sync", "Synchronization", 0, {
132 { REQ, "/sys/kernel/debug/tracing/events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800133 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700134 { "workq", "Kernel Workqueues", 0, {
135 { REQ, "/sys/kernel/debug/tracing/events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800136 } },
Colin Cross580407f2014-08-18 15:22:13 -0700137 { "memreclaim", "Kernel Memory Reclaim", 0, {
138 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
139 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
140 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_wake/enable" },
141 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_sleep/enable" },
142 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800143 { "regulators", "Voltage and Current Regulators", 0, {
144 { REQ, "/sys/kernel/debug/tracing/events/regulator/enable" },
145 } },
Scott Bauerae473362015-06-08 16:32:36 -0700146 { "binder_driver", "Binder Kernel driver", 0, {
147 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction/enable" },
148 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction_received/enable" },
149 } },
150 { "binder_lock", "Binder global lock trace", 0, {
151 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_lock/enable" },
152 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_locked/enable" },
153 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_unlock/enable" },
154 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800155};
156
157/* Command line options */
158static int g_traceDurationSeconds = 5;
159static bool g_traceOverwrite = false;
160static int g_traceBufferSizeKB = 2048;
161static bool g_compress = false;
162static bool g_nohup = false;
163static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900164static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700165static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700166static const char* g_debugAppCmdLine = "";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800167
168/* Global state */
169static bool g_traceAborted = false;
170static bool g_categoryEnables[NELEM(k_categories)] = {};
171
172/* Sys file paths */
173static const char* k_traceClockPath =
174 "/sys/kernel/debug/tracing/trace_clock";
175
176static const char* k_traceBufferSizePath =
177 "/sys/kernel/debug/tracing/buffer_size_kb";
178
179static const char* k_tracingOverwriteEnablePath =
180 "/sys/kernel/debug/tracing/options/overwrite";
181
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700182static const char* k_currentTracerPath =
183 "/sys/kernel/debug/tracing/current_tracer";
184
185static const char* k_printTgidPath =
186 "/sys/kernel/debug/tracing/options/print-tgid";
187
188static const char* k_funcgraphAbsTimePath =
189 "/sys/kernel/debug/tracing/options/funcgraph-abstime";
190
191static const char* k_funcgraphCpuPath =
192 "/sys/kernel/debug/tracing/options/funcgraph-cpu";
193
194static const char* k_funcgraphProcPath =
195 "/sys/kernel/debug/tracing/options/funcgraph-proc";
196
197static const char* k_funcgraphFlatPath =
198 "/sys/kernel/debug/tracing/options/funcgraph-flat";
199
200static const char* k_funcgraphDurationPath =
201 "/sys/kernel/debug/tracing/options/funcgraph-duration";
202
203static const char* k_ftraceFilterPath =
204 "/sys/kernel/debug/tracing/set_ftrace_filter";
205
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800206static const char* k_tracingOnPath =
207 "/sys/kernel/debug/tracing/tracing_on";
208
209static const char* k_tracePath =
210 "/sys/kernel/debug/tracing/trace";
211
John Reck469a1942015-03-26 15:31:35 -0700212static const char* k_traceMarkerPath =
213 "/sys/kernel/debug/tracing/trace_marker";
214
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800215// Check whether a file exists.
216static bool fileExists(const char* filename) {
217 return access(filename, F_OK) != -1;
218}
219
220// Check whether a file is writable.
221static bool fileIsWritable(const char* filename) {
222 return access(filename, W_OK) != -1;
223}
224
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700225// Truncate a file.
226static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800227{
Jamie Gennis43122e72013-03-21 14:06:31 -0700228 // This uses creat rather than truncate because some of the debug kernel
229 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
230 // calls to truncate, but they are cleared by calls to creat.
231 int traceFD = creat(path, 0);
232 if (traceFD == -1) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700233 fprintf(stderr, "error truncating %s: %s (%d)\n", path,
Jamie Gennis43122e72013-03-21 14:06:31 -0700234 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700235 return false;
236 }
237
Jamie Gennis43122e72013-03-21 14:06:31 -0700238 close(traceFD);
239
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700240 return true;
241}
242
243static bool _writeStr(const char* filename, const char* str, int flags)
244{
245 int fd = open(filename, flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800246 if (fd == -1) {
247 fprintf(stderr, "error opening %s: %s (%d)\n", filename,
248 strerror(errno), errno);
249 return false;
250 }
251
252 bool ok = true;
253 ssize_t len = strlen(str);
254 if (write(fd, str, len) != len) {
255 fprintf(stderr, "error writing to %s: %s (%d)\n", filename,
256 strerror(errno), errno);
257 ok = false;
258 }
259
260 close(fd);
261
262 return ok;
263}
264
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700265// Write a string to a file, returning true if the write was successful.
266static bool writeStr(const char* filename, const char* str)
267{
268 return _writeStr(filename, str, O_WRONLY);
269}
270
271// Append a string to a file, returning true if the write was successful.
272static bool appendStr(const char* filename, const char* str)
273{
274 return _writeStr(filename, str, O_APPEND|O_WRONLY);
275}
276
John Reck469a1942015-03-26 15:31:35 -0700277static void writeClockSyncMarker()
278{
279 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200280 int len = 0;
281 int fd = open(k_traceMarkerPath, O_WRONLY);
282 if (fd == -1) {
283 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
284 strerror(errno), errno);
285 return;
286 }
John Reck469a1942015-03-26 15:31:35 -0700287 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200288
289 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
290 if (write(fd, buffer, len) != len) {
291 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
292 }
293
294 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
295 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
296 if (write(fd, buffer, len) != len) {
297 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
298 }
299
300 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700301}
302
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800303// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
304// file.
305static bool setKernelOptionEnable(const char* filename, bool enable)
306{
307 return writeStr(filename, enable ? "1" : "0");
308}
309
310// Check whether the category is supported on the device with the current
311// rootness. A category is supported only if all its required /sys/ files are
312// writable and if enabling the category will enable one or more tracing tags
313// or /sys/ files.
314static bool isCategorySupported(const TracingCategory& category)
315{
316 bool ok = category.tags != 0;
317 for (int i = 0; i < MAX_SYS_FILES; i++) {
318 const char* path = category.sysfiles[i].path;
319 bool req = category.sysfiles[i].required == REQ;
320 if (path != NULL) {
321 if (req) {
322 if (!fileIsWritable(path)) {
323 return false;
324 } else {
325 ok = true;
326 }
327 } else {
328 ok |= fileIsWritable(path);
329 }
330 }
331 }
332 return ok;
333}
334
335// Check whether the category would be supported on the device if the user
336// were root. This function assumes that root is able to write to any file
337// that exists. It performs the same logic as isCategorySupported, but it
338// uses file existance rather than writability in the /sys/ file checks.
339static bool isCategorySupportedForRoot(const TracingCategory& category)
340{
341 bool ok = category.tags != 0;
342 for (int i = 0; i < MAX_SYS_FILES; i++) {
343 const char* path = category.sysfiles[i].path;
344 bool req = category.sysfiles[i].required == REQ;
345 if (path != NULL) {
346 if (req) {
347 if (!fileExists(path)) {
348 return false;
349 } else {
350 ok = true;
351 }
352 } else {
353 ok |= fileExists(path);
354 }
355 }
356 }
357 return ok;
358}
359
360// Enable or disable overwriting of the kernel trace buffers. Disabling this
361// will cause tracing to stop once the trace buffers have filled up.
362static bool setTraceOverwriteEnable(bool enable)
363{
364 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
365}
366
367// Enable or disable kernel tracing.
368static bool setTracingEnabled(bool enable)
369{
370 return setKernelOptionEnable(k_tracingOnPath, enable);
371}
372
373// Clear the contents of the kernel trace.
374static bool clearTrace()
375{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700376 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800377}
378
379// Set the size of the kernel's trace buffer in kilobytes.
380static bool setTraceBufferSizeKB(int size)
381{
382 char str[32] = "1";
383 int len;
384 if (size < 1) {
385 size = 1;
386 }
387 snprintf(str, 32, "%d", size);
388 return writeStr(k_traceBufferSizePath, str);
389}
390
Colin Crossb1ce49b2014-08-20 14:28:47 -0700391// Read the trace_clock sysfs file and return true if it matches the requested
392// value. The trace_clock file format is:
393// local [global] counter uptime perf
394static bool isTraceClock(const char *mode)
395{
396 int fd = open(k_traceClockPath, O_RDONLY);
397 if (fd == -1) {
398 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceClockPath,
399 strerror(errno), errno);
400 return false;
401 }
402
403 char buf[4097];
404 ssize_t n = read(fd, buf, 4096);
405 close(fd);
406 if (n == -1) {
407 fprintf(stderr, "error reading %s: %s (%d)\n", k_traceClockPath,
408 strerror(errno), errno);
409 return false;
410 }
411 buf[n] = '\0';
412
413 char *start = strchr(buf, '[');
414 if (start == NULL) {
415 return false;
416 }
417 start++;
418
419 char *end = strchr(start, ']');
420 if (end == NULL) {
421 return false;
422 }
423 *end = '\0';
424
425 return strcmp(mode, start) == 0;
426}
427
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800428// Enable or disable the kernel's use of the global clock. Disabling the global
429// clock will result in the kernel using a per-CPU local clock.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700430// Any write to the trace_clock sysfs file will reset the buffer, so only
431// update it if the requested value is not the current value.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800432static bool setGlobalClockEnable(bool enable)
433{
Colin Crossb1ce49b2014-08-20 14:28:47 -0700434 const char *clock = enable ? "global" : "local";
435
436 if (isTraceClock(clock)) {
437 return true;
438 }
439
440 return writeStr(k_traceClockPath, clock);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800441}
442
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700443static bool setPrintTgidEnableIfPresent(bool enable)
444{
445 if (fileExists(k_printTgidPath)) {
446 return setKernelOptionEnable(k_printTgidPath, enable);
447 }
448 return true;
449}
450
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800451// Poke all the binder-enabled processes in the system to get them to re-read
452// their system properties.
453static bool pokeBinderServices()
454{
455 sp<IServiceManager> sm = defaultServiceManager();
456 Vector<String16> services = sm->listServices();
457 for (size_t i = 0; i < services.size(); i++) {
458 sp<IBinder> obj = sm->checkService(services[i]);
459 if (obj != NULL) {
460 Parcel data;
461 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
462 NULL, 0) != OK) {
463 if (false) {
464 // XXX: For some reason this fails on tablets trying to
465 // poke the "phone" service. It's not clear whether some
466 // are expected to fail.
467 String8 svc(services[i]);
468 fprintf(stderr, "error poking binder service %s\n",
469 svc.string());
470 return false;
471 }
472 }
473 }
474 }
475 return true;
476}
477
478// Set the trace tags that userland tracing uses, and poke the running
479// processes to pick up the new value.
480static bool setTagsProperty(uint64_t tags)
481{
482 char buf[64];
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700483 snprintf(buf, 64, "%#" PRIx64, tags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800484 if (property_set(k_traceTagsProperty, buf) < 0) {
485 fprintf(stderr, "error setting trace tags system property\n");
486 return false;
487 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700488 return true;
489}
490
491// Set the system property that indicates which apps should perform
492// application-level tracing.
493static bool setAppCmdlineProperty(const char* cmdline)
494{
495 if (property_set(k_traceAppCmdlineProperty, cmdline) < 0) {
496 fprintf(stderr, "error setting trace app system property\n");
497 return false;
498 }
499 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800500}
501
502// Disable all /sys/ enable files.
503static bool disableKernelTraceEvents() {
504 bool ok = true;
505 for (int i = 0; i < NELEM(k_categories); i++) {
506 const TracingCategory &c = k_categories[i];
507 for (int j = 0; j < MAX_SYS_FILES; j++) {
508 const char* path = c.sysfiles[j].path;
509 if (path != NULL && fileIsWritable(path)) {
510 ok &= setKernelOptionEnable(path, false);
511 }
512 }
513 }
514 return ok;
515}
516
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700517// Verify that the comma separated list of functions are being traced by the
518// kernel.
519static bool verifyKernelTraceFuncs(const char* funcs)
520{
521 int fd = open(k_ftraceFilterPath, O_RDONLY);
522 if (fd == -1) {
523 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
524 strerror(errno), errno);
525 return false;
526 }
527
528 char buf[4097];
529 ssize_t n = read(fd, buf, 4096);
530 close(fd);
531 if (n == -1) {
532 fprintf(stderr, "error reading %s: %s (%d)\n", k_ftraceFilterPath,
533 strerror(errno), errno);
534 return false;
535 }
536
537 buf[n] = '\0';
538 String8 funcList = String8::format("\n%s", buf);
539
540 // Make sure that every function listed in funcs is in the list we just
541 // read from the kernel.
542 bool ok = true;
543 char* myFuncs = strdup(funcs);
544 char* func = strtok(myFuncs, ",");
545 while (func) {
546 String8 fancyFunc = String8::format("\n%s\n", func);
547 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
548 if (!found || func[0] == '\0') {
549 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
550 "to trace.\n", func);
551 ok = false;
552 }
553 func = strtok(NULL, ",");
554 }
555 free(myFuncs);
556
557 return ok;
558}
559
560// Set the comma separated list of functions that the kernel is to trace.
561static bool setKernelTraceFuncs(const char* funcs)
562{
563 bool ok = true;
564
565 if (funcs == NULL || funcs[0] == '\0') {
566 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700567 if (fileIsWritable(k_currentTracerPath)) {
568 ok &= writeStr(k_currentTracerPath, "nop");
569 }
570 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700571 ok &= truncateFile(k_ftraceFilterPath);
572 }
573 } else {
574 // Enable kernel function tracing.
575 ok &= writeStr(k_currentTracerPath, "function_graph");
576 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
577 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
578 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
579 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
580
581 // Set the requested filter functions.
582 ok &= truncateFile(k_ftraceFilterPath);
583 char* myFuncs = strdup(funcs);
584 char* func = strtok(myFuncs, ",");
585 while (func) {
586 ok &= appendStr(k_ftraceFilterPath, func);
587 func = strtok(NULL, ",");
588 }
589 free(myFuncs);
590
591 // Verify that the set functions are being traced.
592 if (ok) {
593 ok &= verifyKernelTraceFuncs(funcs);
594 }
595 }
596
597 return ok;
598}
599
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900600static bool setCategoryEnable(const char* name, bool enable)
601{
602 for (int i = 0; i < NELEM(k_categories); i++) {
603 const TracingCategory& c = k_categories[i];
604 if (strcmp(name, c.name) == 0) {
605 if (isCategorySupported(c)) {
606 g_categoryEnables[i] = enable;
607 return true;
608 } else {
609 if (isCategorySupportedForRoot(c)) {
610 fprintf(stderr, "error: category \"%s\" requires root "
611 "privileges.\n", name);
612 } else {
613 fprintf(stderr, "error: category \"%s\" is not supported "
614 "on this device.\n", name);
615 }
616 return false;
617 }
618 }
619 }
620 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
621 return false;
622}
623
624static bool setCategoriesEnableFromFile(const char* categories_file)
625{
626 if (!categories_file) {
627 return true;
628 }
629 Tokenizer* tokenizer = NULL;
630 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
631 return false;
632 }
633 bool ok = true;
634 while (!tokenizer->isEol()) {
635 String8 token = tokenizer->nextToken(" ");
636 if (token.isEmpty()) {
637 tokenizer->skipDelimiters(" ");
638 continue;
639 }
640 ok &= setCategoryEnable(token.string(), true);
641 }
642 delete tokenizer;
643 return ok;
644}
645
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700646// Set all the kernel tracing settings to the desired state for this trace
647// capture.
648static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800649{
650 bool ok = true;
651
652 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900653 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800654 ok &= setTraceOverwriteEnable(g_traceOverwrite);
655 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
656 ok &= setGlobalClockEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700657 ok &= setPrintTgidEnableIfPresent(true);
658 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800659
660 // Set up the tags property.
661 uint64_t tags = 0;
662 for (int i = 0; i < NELEM(k_categories); i++) {
663 if (g_categoryEnables[i]) {
664 const TracingCategory &c = k_categories[i];
665 tags |= c.tags;
666 }
667 }
668 ok &= setTagsProperty(tags);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700669 ok &= setAppCmdlineProperty(g_debugAppCmdLine);
670 ok &= pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800671
672 // Disable all the sysfs enables. This is done as a separate loop from
673 // the enables to allow the same enable to exist in multiple categories.
674 ok &= disableKernelTraceEvents();
675
676 // Enable all the sysfs enables that are in an enabled category.
677 for (int i = 0; i < NELEM(k_categories); i++) {
678 if (g_categoryEnables[i]) {
679 const TracingCategory &c = k_categories[i];
680 for (int j = 0; j < MAX_SYS_FILES; j++) {
681 const char* path = c.sysfiles[j].path;
682 bool required = c.sysfiles[j].required == REQ;
683 if (path != NULL) {
684 if (fileIsWritable(path)) {
685 ok &= setKernelOptionEnable(path, true);
686 } else if (required) {
687 fprintf(stderr, "error writing file %s\n", path);
688 ok = false;
689 }
690 }
691 }
692 }
693 }
694
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800695 return ok;
696}
697
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700698// Reset all the kernel tracing settings to their default state.
699static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800700{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800701 // Disable all tracing that we're able to.
702 disableKernelTraceEvents();
703
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700704 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800705 setTagsProperty(0);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700706 setAppCmdlineProperty("");
707 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800708
709 // Set the options back to their defaults.
710 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700711 setTraceBufferSizeKB(1);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800712 setGlobalClockEnable(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700713 setPrintTgidEnableIfPresent(false);
714 setKernelTraceFuncs(NULL);
715}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800716
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700717
718// Enable tracing in the kernel.
719static bool startTrace()
720{
721 return setTracingEnabled(true);
722}
723
724// Disable tracing in the kernel.
725static void stopTrace()
726{
727 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800728}
729
730// Read the current kernel trace and write it to stdout.
731static void dumpTrace()
732{
733 int traceFD = open(k_tracePath, O_RDWR);
734 if (traceFD == -1) {
735 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
736 strerror(errno), errno);
737 return;
738 }
739
740 if (g_compress) {
741 z_stream zs;
742 uint8_t *in, *out;
743 int result, flush;
744
Elliott Hughes3da5d232015-01-25 08:35:20 -0800745 memset(&zs, 0, sizeof(zs));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800746 result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
747 if (result != Z_OK) {
748 fprintf(stderr, "error initializing zlib: %d\n", result);
749 close(traceFD);
750 return;
751 }
752
753 const size_t bufSize = 64*1024;
754 in = (uint8_t*)malloc(bufSize);
755 out = (uint8_t*)malloc(bufSize);
756 flush = Z_NO_FLUSH;
757
758 zs.next_out = out;
759 zs.avail_out = bufSize;
760
761 do {
762
763 if (zs.avail_in == 0) {
764 // More input is needed.
765 result = read(traceFD, in, bufSize);
766 if (result < 0) {
767 fprintf(stderr, "error reading trace: %s (%d)\n",
768 strerror(errno), errno);
769 result = Z_STREAM_END;
770 break;
771 } else if (result == 0) {
772 flush = Z_FINISH;
773 } else {
774 zs.next_in = in;
775 zs.avail_in = result;
776 }
777 }
778
779 if (zs.avail_out == 0) {
780 // Need to write the output.
781 result = write(STDOUT_FILENO, out, bufSize);
782 if ((size_t)result < bufSize) {
783 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
784 strerror(errno), errno);
785 result = Z_STREAM_END; // skip deflate error message
786 zs.avail_out = bufSize; // skip the final write
787 break;
788 }
789 zs.next_out = out;
790 zs.avail_out = bufSize;
791 }
792
793 } while ((result = deflate(&zs, flush)) == Z_OK);
794
795 if (result != Z_STREAM_END) {
796 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
797 }
798
799 if (zs.avail_out < bufSize) {
800 size_t bytes = bufSize - zs.avail_out;
801 result = write(STDOUT_FILENO, out, bytes);
802 if ((size_t)result < bytes) {
803 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
804 strerror(errno), errno);
805 }
806 }
807
808 result = deflateEnd(&zs);
809 if (result != Z_OK) {
810 fprintf(stderr, "error cleaning up zlib: %d\n", result);
811 }
812
813 free(in);
814 free(out);
815 } else {
816 ssize_t sent = 0;
817 while ((sent = sendfile(STDOUT_FILENO, traceFD, NULL, 64*1024*1024)) > 0);
818 if (sent == -1) {
819 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
820 errno);
821 }
822 }
823
824 close(traceFD);
825}
826
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700827static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800828{
829 if (!g_nohup) {
830 g_traceAborted = true;
831 }
832}
833
834static void registerSigHandler()
835{
836 struct sigaction sa;
837 sigemptyset(&sa.sa_mask);
838 sa.sa_flags = 0;
839 sa.sa_handler = handleSignal;
840 sigaction(SIGHUP, &sa, NULL);
841 sigaction(SIGINT, &sa, NULL);
842 sigaction(SIGQUIT, &sa, NULL);
843 sigaction(SIGTERM, &sa, NULL);
844}
845
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800846static void listSupportedCategories()
847{
848 for (int i = 0; i < NELEM(k_categories); i++) {
849 const TracingCategory& c = k_categories[i];
850 if (isCategorySupported(c)) {
851 printf(" %10s - %s\n", c.name, c.longname);
852 }
853 }
854}
855
856// Print the command usage help to stderr.
857static void showHelp(const char *cmd)
858{
859 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
860 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700861 " -a appname enable app-level tracing for a comma "
862 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800863 " -b N use a trace buffer size of N KB\n"
864 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900865 " -f filename use the categories written in a file as space-separated\n"
866 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700867 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800868 " -n ignore signals\n"
869 " -s N sleep for N seconds before tracing [default 0]\n"
870 " -t N trace for N seconds [defualt 5]\n"
871 " -z compress the trace dump\n"
872 " --async_start start circular trace and return immediatly\n"
873 " --async_dump dump the current contents of circular trace buffer\n"
874 " --async_stop stop tracing and dump the current contents of circular\n"
875 " trace buffer\n"
Jamie Gennis92573f12012-12-07 16:29:03 -0800876 " --list_categories\n"
877 " list the available tracing categories\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800878 );
879}
880
881int main(int argc, char **argv)
882{
883 bool async = false;
884 bool traceStart = true;
885 bool traceStop = true;
886 bool traceDump = true;
887
888 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
889 showHelp(argv[0]);
890 exit(0);
891 }
892
893 for (;;) {
894 int ret;
895 int option_index = 0;
896 static struct option long_options[] = {
897 {"async_start", no_argument, 0, 0 },
898 {"async_stop", no_argument, 0, 0 },
899 {"async_dump", no_argument, 0, 0 },
900 {"list_categories", no_argument, 0, 0 },
901 { 0, 0, 0, 0 }
902 };
903
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900904 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:z",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800905 long_options, &option_index);
906
907 if (ret < 0) {
908 for (int i = optind; i < argc; i++) {
909 if (!setCategoryEnable(argv[i], true)) {
910 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
911 exit(1);
912 }
913 }
914 break;
915 }
916
917 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700918 case 'a':
919 g_debugAppCmdLine = optarg;
920 break;
921
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800922 case 'b':
923 g_traceBufferSizeKB = atoi(optarg);
924 break;
925
926 case 'c':
927 g_traceOverwrite = true;
928 break;
929
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900930 case 'f':
931 g_categoriesFile = optarg;
932 break;
933
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700934 case 'k':
935 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700936 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700937
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800938 case 'n':
939 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700940 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800941
942 case 's':
943 g_initialSleepSecs = atoi(optarg);
944 break;
945
946 case 't':
947 g_traceDurationSeconds = atoi(optarg);
948 break;
949
950 case 'z':
951 g_compress = true;
952 break;
953
954 case 0:
955 if (!strcmp(long_options[option_index].name, "async_start")) {
956 async = true;
957 traceStop = false;
958 traceDump = false;
959 g_traceOverwrite = true;
960 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
961 async = true;
John Reck4ba2b632015-05-15 10:00:34 -0700962 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800963 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
964 async = true;
965 traceStart = false;
966 traceStop = false;
967 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
968 listSupportedCategories();
969 exit(0);
970 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700971 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800972
973 default:
974 fprintf(stderr, "\n");
975 showHelp(argv[0]);
976 exit(-1);
977 break;
978 }
979 }
980
981 registerSigHandler();
982
983 if (g_initialSleepSecs > 0) {
984 sleep(g_initialSleepSecs);
985 }
986
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700987 bool ok = true;
988 ok &= setUpTrace();
989 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800990
991 if (ok && traceStart) {
992 printf("capturing trace...");
993 fflush(stdout);
994
995 // We clear the trace after starting it because tracing gets enabled for
996 // each CPU individually in the kernel. Having the beginning of the trace
997 // contain entries from only one CPU can cause "begin" entries without a
998 // matching "end" entry to show up if a task gets migrated from one CPU to
999 // another.
1000 ok = clearTrace();
1001
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001002 writeClockSyncMarker();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001003 if (ok && !async) {
1004 // Sleep to allow the trace to be captured.
1005 struct timespec timeLeft;
1006 timeLeft.tv_sec = g_traceDurationSeconds;
1007 timeLeft.tv_nsec = 0;
1008 do {
1009 if (g_traceAborted) {
1010 break;
1011 }
1012 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1013 }
1014 }
1015
1016 // Stop the trace and restore the default settings.
1017 if (traceStop)
1018 stopTrace();
1019
1020 if (ok && traceDump) {
1021 if (!g_traceAborted) {
1022 printf(" done\nTRACE:\n");
1023 fflush(stdout);
1024 dumpTrace();
1025 } else {
1026 printf("\ntrace aborted.\n");
1027 fflush(stdout);
1028 }
1029 clearTrace();
1030 } else if (!ok) {
1031 fprintf(stderr, "unable to start tracing\n");
1032 }
1033
1034 // Reset the trace buffer size to 1.
1035 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001036 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001037
1038 return g_traceAborted ? 1 : 0;
1039}