blob: 6e591fd99866177f8a675749384e54e2a83d4001 [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" },
Ruchi Kandoiffcc7112015-11-19 18:32:00 -0800106 { OPT, "/sys/kernel/debug/tracing/events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800107 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700108 { "membus", "Memory Bus Utilization", 0, {
109 { REQ, "/sys/kernel/debug/tracing/events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800110 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700111 { "idle", "CPU Idle", 0, {
112 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800113 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700114 { "disk", "Disk I/O", 0, {
Greg Hackmanne80d32c2014-11-20 12:59:44 -0800115 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_enter/enable" },
116 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_exit/enable" },
117 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_begin/enable" },
118 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_end/enable" },
119 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_begin/enable" },
120 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_end/enable" },
121 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable" },
122 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable" },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700123 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" },
124 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800125 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700126 { "mmc", "eMMC commands", 0, {
127 { REQ, "/sys/kernel/debug/tracing/events/mmc/enable" },
128 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700129 { "load", "CPU Load", 0, {
130 { REQ, "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800131 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700132 { "sync", "Synchronization", 0, {
133 { REQ, "/sys/kernel/debug/tracing/events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800134 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700135 { "workq", "Kernel Workqueues", 0, {
136 { REQ, "/sys/kernel/debug/tracing/events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800137 } },
Colin Cross580407f2014-08-18 15:22:13 -0700138 { "memreclaim", "Kernel Memory Reclaim", 0, {
139 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
140 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
141 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_wake/enable" },
142 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_sleep/enable" },
143 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800144 { "regulators", "Voltage and Current Regulators", 0, {
145 { REQ, "/sys/kernel/debug/tracing/events/regulator/enable" },
146 } },
Scott Bauerae473362015-06-08 16:32:36 -0700147 { "binder_driver", "Binder Kernel driver", 0, {
148 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction/enable" },
149 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction_received/enable" },
150 } },
151 { "binder_lock", "Binder global lock trace", 0, {
152 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_lock/enable" },
153 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_locked/enable" },
154 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_unlock/enable" },
155 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800156};
157
158/* Command line options */
159static int g_traceDurationSeconds = 5;
160static bool g_traceOverwrite = false;
161static int g_traceBufferSizeKB = 2048;
162static bool g_compress = false;
163static bool g_nohup = false;
164static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900165static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700166static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700167static const char* g_debugAppCmdLine = "";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800168
169/* Global state */
170static bool g_traceAborted = false;
171static bool g_categoryEnables[NELEM(k_categories)] = {};
172
173/* Sys file paths */
174static const char* k_traceClockPath =
175 "/sys/kernel/debug/tracing/trace_clock";
176
177static const char* k_traceBufferSizePath =
178 "/sys/kernel/debug/tracing/buffer_size_kb";
179
180static const char* k_tracingOverwriteEnablePath =
181 "/sys/kernel/debug/tracing/options/overwrite";
182
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700183static const char* k_currentTracerPath =
184 "/sys/kernel/debug/tracing/current_tracer";
185
186static const char* k_printTgidPath =
187 "/sys/kernel/debug/tracing/options/print-tgid";
188
189static const char* k_funcgraphAbsTimePath =
190 "/sys/kernel/debug/tracing/options/funcgraph-abstime";
191
192static const char* k_funcgraphCpuPath =
193 "/sys/kernel/debug/tracing/options/funcgraph-cpu";
194
195static const char* k_funcgraphProcPath =
196 "/sys/kernel/debug/tracing/options/funcgraph-proc";
197
198static const char* k_funcgraphFlatPath =
199 "/sys/kernel/debug/tracing/options/funcgraph-flat";
200
201static const char* k_funcgraphDurationPath =
202 "/sys/kernel/debug/tracing/options/funcgraph-duration";
203
204static const char* k_ftraceFilterPath =
205 "/sys/kernel/debug/tracing/set_ftrace_filter";
206
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800207static const char* k_tracingOnPath =
208 "/sys/kernel/debug/tracing/tracing_on";
209
210static const char* k_tracePath =
211 "/sys/kernel/debug/tracing/trace";
212
John Reck469a1942015-03-26 15:31:35 -0700213static const char* k_traceMarkerPath =
214 "/sys/kernel/debug/tracing/trace_marker";
215
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800216// Check whether a file exists.
217static bool fileExists(const char* filename) {
218 return access(filename, F_OK) != -1;
219}
220
221// Check whether a file is writable.
222static bool fileIsWritable(const char* filename) {
223 return access(filename, W_OK) != -1;
224}
225
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700226// Truncate a file.
227static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800228{
Jamie Gennis43122e72013-03-21 14:06:31 -0700229 // This uses creat rather than truncate because some of the debug kernel
230 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
231 // calls to truncate, but they are cleared by calls to creat.
232 int traceFD = creat(path, 0);
233 if (traceFD == -1) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700234 fprintf(stderr, "error truncating %s: %s (%d)\n", path,
Jamie Gennis43122e72013-03-21 14:06:31 -0700235 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700236 return false;
237 }
238
Jamie Gennis43122e72013-03-21 14:06:31 -0700239 close(traceFD);
240
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700241 return true;
242}
243
244static bool _writeStr(const char* filename, const char* str, int flags)
245{
246 int fd = open(filename, flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800247 if (fd == -1) {
248 fprintf(stderr, "error opening %s: %s (%d)\n", filename,
249 strerror(errno), errno);
250 return false;
251 }
252
253 bool ok = true;
254 ssize_t len = strlen(str);
255 if (write(fd, str, len) != len) {
256 fprintf(stderr, "error writing to %s: %s (%d)\n", filename,
257 strerror(errno), errno);
258 ok = false;
259 }
260
261 close(fd);
262
263 return ok;
264}
265
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700266// Write a string to a file, returning true if the write was successful.
267static bool writeStr(const char* filename, const char* str)
268{
269 return _writeStr(filename, str, O_WRONLY);
270}
271
272// Append a string to a file, returning true if the write was successful.
273static bool appendStr(const char* filename, const char* str)
274{
275 return _writeStr(filename, str, O_APPEND|O_WRONLY);
276}
277
John Reck469a1942015-03-26 15:31:35 -0700278static void writeClockSyncMarker()
279{
280 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200281 int len = 0;
282 int fd = open(k_traceMarkerPath, O_WRONLY);
283 if (fd == -1) {
284 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
285 strerror(errno), errno);
286 return;
287 }
John Reck469a1942015-03-26 15:31:35 -0700288 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200289
290 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
291 if (write(fd, buffer, len) != len) {
292 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
293 }
294
295 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
296 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
297 if (write(fd, buffer, len) != len) {
298 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
299 }
300
301 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700302}
303
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800304// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
305// file.
306static bool setKernelOptionEnable(const char* filename, bool enable)
307{
308 return writeStr(filename, enable ? "1" : "0");
309}
310
311// Check whether the category is supported on the device with the current
312// rootness. A category is supported only if all its required /sys/ files are
313// writable and if enabling the category will enable one or more tracing tags
314// or /sys/ files.
315static bool isCategorySupported(const TracingCategory& category)
316{
317 bool ok = category.tags != 0;
318 for (int i = 0; i < MAX_SYS_FILES; i++) {
319 const char* path = category.sysfiles[i].path;
320 bool req = category.sysfiles[i].required == REQ;
321 if (path != NULL) {
322 if (req) {
323 if (!fileIsWritable(path)) {
324 return false;
325 } else {
326 ok = true;
327 }
328 } else {
329 ok |= fileIsWritable(path);
330 }
331 }
332 }
333 return ok;
334}
335
336// Check whether the category would be supported on the device if the user
337// were root. This function assumes that root is able to write to any file
338// that exists. It performs the same logic as isCategorySupported, but it
339// uses file existance rather than writability in the /sys/ file checks.
340static bool isCategorySupportedForRoot(const TracingCategory& category)
341{
342 bool ok = category.tags != 0;
343 for (int i = 0; i < MAX_SYS_FILES; i++) {
344 const char* path = category.sysfiles[i].path;
345 bool req = category.sysfiles[i].required == REQ;
346 if (path != NULL) {
347 if (req) {
348 if (!fileExists(path)) {
349 return false;
350 } else {
351 ok = true;
352 }
353 } else {
354 ok |= fileExists(path);
355 }
356 }
357 }
358 return ok;
359}
360
361// Enable or disable overwriting of the kernel trace buffers. Disabling this
362// will cause tracing to stop once the trace buffers have filled up.
363static bool setTraceOverwriteEnable(bool enable)
364{
365 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
366}
367
368// Enable or disable kernel tracing.
369static bool setTracingEnabled(bool enable)
370{
371 return setKernelOptionEnable(k_tracingOnPath, enable);
372}
373
374// Clear the contents of the kernel trace.
375static bool clearTrace()
376{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700377 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800378}
379
380// Set the size of the kernel's trace buffer in kilobytes.
381static bool setTraceBufferSizeKB(int size)
382{
383 char str[32] = "1";
384 int len;
385 if (size < 1) {
386 size = 1;
387 }
388 snprintf(str, 32, "%d", size);
389 return writeStr(k_traceBufferSizePath, str);
390}
391
Colin Crossb1ce49b2014-08-20 14:28:47 -0700392// Read the trace_clock sysfs file and return true if it matches the requested
393// value. The trace_clock file format is:
394// local [global] counter uptime perf
395static bool isTraceClock(const char *mode)
396{
397 int fd = open(k_traceClockPath, O_RDONLY);
398 if (fd == -1) {
399 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceClockPath,
400 strerror(errno), errno);
401 return false;
402 }
403
404 char buf[4097];
405 ssize_t n = read(fd, buf, 4096);
406 close(fd);
407 if (n == -1) {
408 fprintf(stderr, "error reading %s: %s (%d)\n", k_traceClockPath,
409 strerror(errno), errno);
410 return false;
411 }
412 buf[n] = '\0';
413
414 char *start = strchr(buf, '[');
415 if (start == NULL) {
416 return false;
417 }
418 start++;
419
420 char *end = strchr(start, ']');
421 if (end == NULL) {
422 return false;
423 }
424 *end = '\0';
425
426 return strcmp(mode, start) == 0;
427}
428
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800429// Enable or disable the kernel's use of the global clock. Disabling the global
430// clock will result in the kernel using a per-CPU local clock.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700431// Any write to the trace_clock sysfs file will reset the buffer, so only
432// update it if the requested value is not the current value.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800433static bool setGlobalClockEnable(bool enable)
434{
Colin Crossb1ce49b2014-08-20 14:28:47 -0700435 const char *clock = enable ? "global" : "local";
436
437 if (isTraceClock(clock)) {
438 return true;
439 }
440
441 return writeStr(k_traceClockPath, clock);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800442}
443
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700444static bool setPrintTgidEnableIfPresent(bool enable)
445{
446 if (fileExists(k_printTgidPath)) {
447 return setKernelOptionEnable(k_printTgidPath, enable);
448 }
449 return true;
450}
451
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800452// Poke all the binder-enabled processes in the system to get them to re-read
453// their system properties.
454static bool pokeBinderServices()
455{
456 sp<IServiceManager> sm = defaultServiceManager();
457 Vector<String16> services = sm->listServices();
458 for (size_t i = 0; i < services.size(); i++) {
459 sp<IBinder> obj = sm->checkService(services[i]);
460 if (obj != NULL) {
461 Parcel data;
462 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
463 NULL, 0) != OK) {
464 if (false) {
465 // XXX: For some reason this fails on tablets trying to
466 // poke the "phone" service. It's not clear whether some
467 // are expected to fail.
468 String8 svc(services[i]);
469 fprintf(stderr, "error poking binder service %s\n",
470 svc.string());
471 return false;
472 }
473 }
474 }
475 }
476 return true;
477}
478
479// Set the trace tags that userland tracing uses, and poke the running
480// processes to pick up the new value.
481static bool setTagsProperty(uint64_t tags)
482{
483 char buf[64];
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700484 snprintf(buf, 64, "%#" PRIx64, tags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800485 if (property_set(k_traceTagsProperty, buf) < 0) {
486 fprintf(stderr, "error setting trace tags system property\n");
487 return false;
488 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700489 return true;
490}
491
492// Set the system property that indicates which apps should perform
493// application-level tracing.
494static bool setAppCmdlineProperty(const char* cmdline)
495{
496 if (property_set(k_traceAppCmdlineProperty, cmdline) < 0) {
497 fprintf(stderr, "error setting trace app system property\n");
498 return false;
499 }
500 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800501}
502
503// Disable all /sys/ enable files.
504static bool disableKernelTraceEvents() {
505 bool ok = true;
506 for (int i = 0; i < NELEM(k_categories); i++) {
507 const TracingCategory &c = k_categories[i];
508 for (int j = 0; j < MAX_SYS_FILES; j++) {
509 const char* path = c.sysfiles[j].path;
510 if (path != NULL && fileIsWritable(path)) {
511 ok &= setKernelOptionEnable(path, false);
512 }
513 }
514 }
515 return ok;
516}
517
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700518// Verify that the comma separated list of functions are being traced by the
519// kernel.
520static bool verifyKernelTraceFuncs(const char* funcs)
521{
522 int fd = open(k_ftraceFilterPath, O_RDONLY);
523 if (fd == -1) {
524 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
525 strerror(errno), errno);
526 return false;
527 }
528
529 char buf[4097];
530 ssize_t n = read(fd, buf, 4096);
531 close(fd);
532 if (n == -1) {
533 fprintf(stderr, "error reading %s: %s (%d)\n", k_ftraceFilterPath,
534 strerror(errno), errno);
535 return false;
536 }
537
538 buf[n] = '\0';
539 String8 funcList = String8::format("\n%s", buf);
540
541 // Make sure that every function listed in funcs is in the list we just
542 // read from the kernel.
543 bool ok = true;
544 char* myFuncs = strdup(funcs);
545 char* func = strtok(myFuncs, ",");
546 while (func) {
547 String8 fancyFunc = String8::format("\n%s\n", func);
548 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
549 if (!found || func[0] == '\0') {
550 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
551 "to trace.\n", func);
552 ok = false;
553 }
554 func = strtok(NULL, ",");
555 }
556 free(myFuncs);
557
558 return ok;
559}
560
561// Set the comma separated list of functions that the kernel is to trace.
562static bool setKernelTraceFuncs(const char* funcs)
563{
564 bool ok = true;
565
566 if (funcs == NULL || funcs[0] == '\0') {
567 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700568 if (fileIsWritable(k_currentTracerPath)) {
569 ok &= writeStr(k_currentTracerPath, "nop");
570 }
571 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700572 ok &= truncateFile(k_ftraceFilterPath);
573 }
574 } else {
575 // Enable kernel function tracing.
576 ok &= writeStr(k_currentTracerPath, "function_graph");
577 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
578 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
579 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
580 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
581
582 // Set the requested filter functions.
583 ok &= truncateFile(k_ftraceFilterPath);
584 char* myFuncs = strdup(funcs);
585 char* func = strtok(myFuncs, ",");
586 while (func) {
587 ok &= appendStr(k_ftraceFilterPath, func);
588 func = strtok(NULL, ",");
589 }
590 free(myFuncs);
591
592 // Verify that the set functions are being traced.
593 if (ok) {
594 ok &= verifyKernelTraceFuncs(funcs);
595 }
596 }
597
598 return ok;
599}
600
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900601static bool setCategoryEnable(const char* name, bool enable)
602{
603 for (int i = 0; i < NELEM(k_categories); i++) {
604 const TracingCategory& c = k_categories[i];
605 if (strcmp(name, c.name) == 0) {
606 if (isCategorySupported(c)) {
607 g_categoryEnables[i] = enable;
608 return true;
609 } else {
610 if (isCategorySupportedForRoot(c)) {
611 fprintf(stderr, "error: category \"%s\" requires root "
612 "privileges.\n", name);
613 } else {
614 fprintf(stderr, "error: category \"%s\" is not supported "
615 "on this device.\n", name);
616 }
617 return false;
618 }
619 }
620 }
621 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
622 return false;
623}
624
625static bool setCategoriesEnableFromFile(const char* categories_file)
626{
627 if (!categories_file) {
628 return true;
629 }
630 Tokenizer* tokenizer = NULL;
631 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
632 return false;
633 }
634 bool ok = true;
635 while (!tokenizer->isEol()) {
636 String8 token = tokenizer->nextToken(" ");
637 if (token.isEmpty()) {
638 tokenizer->skipDelimiters(" ");
639 continue;
640 }
641 ok &= setCategoryEnable(token.string(), true);
642 }
643 delete tokenizer;
644 return ok;
645}
646
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700647// Set all the kernel tracing settings to the desired state for this trace
648// capture.
649static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800650{
651 bool ok = true;
652
653 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900654 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800655 ok &= setTraceOverwriteEnable(g_traceOverwrite);
656 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
657 ok &= setGlobalClockEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700658 ok &= setPrintTgidEnableIfPresent(true);
659 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800660
661 // Set up the tags property.
662 uint64_t tags = 0;
663 for (int i = 0; i < NELEM(k_categories); i++) {
664 if (g_categoryEnables[i]) {
665 const TracingCategory &c = k_categories[i];
666 tags |= c.tags;
667 }
668 }
669 ok &= setTagsProperty(tags);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700670 ok &= setAppCmdlineProperty(g_debugAppCmdLine);
671 ok &= pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800672
673 // Disable all the sysfs enables. This is done as a separate loop from
674 // the enables to allow the same enable to exist in multiple categories.
675 ok &= disableKernelTraceEvents();
676
677 // Enable all the sysfs enables that are in an enabled category.
678 for (int i = 0; i < NELEM(k_categories); i++) {
679 if (g_categoryEnables[i]) {
680 const TracingCategory &c = k_categories[i];
681 for (int j = 0; j < MAX_SYS_FILES; j++) {
682 const char* path = c.sysfiles[j].path;
683 bool required = c.sysfiles[j].required == REQ;
684 if (path != NULL) {
685 if (fileIsWritable(path)) {
686 ok &= setKernelOptionEnable(path, true);
687 } else if (required) {
688 fprintf(stderr, "error writing file %s\n", path);
689 ok = false;
690 }
691 }
692 }
693 }
694 }
695
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800696 return ok;
697}
698
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700699// Reset all the kernel tracing settings to their default state.
700static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800701{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800702 // Disable all tracing that we're able to.
703 disableKernelTraceEvents();
704
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700705 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800706 setTagsProperty(0);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700707 setAppCmdlineProperty("");
708 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800709
710 // Set the options back to their defaults.
711 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700712 setTraceBufferSizeKB(1);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800713 setGlobalClockEnable(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700714 setPrintTgidEnableIfPresent(false);
715 setKernelTraceFuncs(NULL);
716}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800717
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700718
719// Enable tracing in the kernel.
720static bool startTrace()
721{
722 return setTracingEnabled(true);
723}
724
725// Disable tracing in the kernel.
726static void stopTrace()
727{
728 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800729}
730
731// Read the current kernel trace and write it to stdout.
732static void dumpTrace()
733{
734 int traceFD = open(k_tracePath, O_RDWR);
735 if (traceFD == -1) {
736 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
737 strerror(errno), errno);
738 return;
739 }
740
741 if (g_compress) {
742 z_stream zs;
743 uint8_t *in, *out;
744 int result, flush;
745
Elliott Hughes3da5d232015-01-25 08:35:20 -0800746 memset(&zs, 0, sizeof(zs));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800747 result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
748 if (result != Z_OK) {
749 fprintf(stderr, "error initializing zlib: %d\n", result);
750 close(traceFD);
751 return;
752 }
753
754 const size_t bufSize = 64*1024;
755 in = (uint8_t*)malloc(bufSize);
756 out = (uint8_t*)malloc(bufSize);
757 flush = Z_NO_FLUSH;
758
759 zs.next_out = out;
760 zs.avail_out = bufSize;
761
762 do {
763
764 if (zs.avail_in == 0) {
765 // More input is needed.
766 result = read(traceFD, in, bufSize);
767 if (result < 0) {
768 fprintf(stderr, "error reading trace: %s (%d)\n",
769 strerror(errno), errno);
770 result = Z_STREAM_END;
771 break;
772 } else if (result == 0) {
773 flush = Z_FINISH;
774 } else {
775 zs.next_in = in;
776 zs.avail_in = result;
777 }
778 }
779
780 if (zs.avail_out == 0) {
781 // Need to write the output.
782 result = write(STDOUT_FILENO, out, bufSize);
783 if ((size_t)result < bufSize) {
784 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
785 strerror(errno), errno);
786 result = Z_STREAM_END; // skip deflate error message
787 zs.avail_out = bufSize; // skip the final write
788 break;
789 }
790 zs.next_out = out;
791 zs.avail_out = bufSize;
792 }
793
794 } while ((result = deflate(&zs, flush)) == Z_OK);
795
796 if (result != Z_STREAM_END) {
797 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
798 }
799
800 if (zs.avail_out < bufSize) {
801 size_t bytes = bufSize - zs.avail_out;
802 result = write(STDOUT_FILENO, out, bytes);
803 if ((size_t)result < bytes) {
804 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
805 strerror(errno), errno);
806 }
807 }
808
809 result = deflateEnd(&zs);
810 if (result != Z_OK) {
811 fprintf(stderr, "error cleaning up zlib: %d\n", result);
812 }
813
814 free(in);
815 free(out);
816 } else {
817 ssize_t sent = 0;
818 while ((sent = sendfile(STDOUT_FILENO, traceFD, NULL, 64*1024*1024)) > 0);
819 if (sent == -1) {
820 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
821 errno);
822 }
823 }
824
825 close(traceFD);
826}
827
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700828static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800829{
830 if (!g_nohup) {
831 g_traceAborted = true;
832 }
833}
834
835static void registerSigHandler()
836{
837 struct sigaction sa;
838 sigemptyset(&sa.sa_mask);
839 sa.sa_flags = 0;
840 sa.sa_handler = handleSignal;
841 sigaction(SIGHUP, &sa, NULL);
842 sigaction(SIGINT, &sa, NULL);
843 sigaction(SIGQUIT, &sa, NULL);
844 sigaction(SIGTERM, &sa, NULL);
845}
846
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800847static void listSupportedCategories()
848{
849 for (int i = 0; i < NELEM(k_categories); i++) {
850 const TracingCategory& c = k_categories[i];
851 if (isCategorySupported(c)) {
852 printf(" %10s - %s\n", c.name, c.longname);
853 }
854 }
855}
856
857// Print the command usage help to stderr.
858static void showHelp(const char *cmd)
859{
860 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
861 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700862 " -a appname enable app-level tracing for a comma "
863 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800864 " -b N use a trace buffer size of N KB\n"
865 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900866 " -f filename use the categories written in a file as space-separated\n"
867 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700868 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800869 " -n ignore signals\n"
870 " -s N sleep for N seconds before tracing [default 0]\n"
871 " -t N trace for N seconds [defualt 5]\n"
872 " -z compress the trace dump\n"
873 " --async_start start circular trace and return immediatly\n"
874 " --async_dump dump the current contents of circular trace buffer\n"
875 " --async_stop stop tracing and dump the current contents of circular\n"
876 " trace buffer\n"
Jamie Gennis92573f12012-12-07 16:29:03 -0800877 " --list_categories\n"
878 " list the available tracing categories\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800879 );
880}
881
882int main(int argc, char **argv)
883{
884 bool async = false;
885 bool traceStart = true;
886 bool traceStop = true;
887 bool traceDump = true;
888
889 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
890 showHelp(argv[0]);
891 exit(0);
892 }
893
894 for (;;) {
895 int ret;
896 int option_index = 0;
897 static struct option long_options[] = {
898 {"async_start", no_argument, 0, 0 },
899 {"async_stop", no_argument, 0, 0 },
900 {"async_dump", no_argument, 0, 0 },
901 {"list_categories", no_argument, 0, 0 },
902 { 0, 0, 0, 0 }
903 };
904
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900905 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:z",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800906 long_options, &option_index);
907
908 if (ret < 0) {
909 for (int i = optind; i < argc; i++) {
910 if (!setCategoryEnable(argv[i], true)) {
911 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
912 exit(1);
913 }
914 }
915 break;
916 }
917
918 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700919 case 'a':
920 g_debugAppCmdLine = optarg;
921 break;
922
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800923 case 'b':
924 g_traceBufferSizeKB = atoi(optarg);
925 break;
926
927 case 'c':
928 g_traceOverwrite = true;
929 break;
930
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900931 case 'f':
932 g_categoriesFile = optarg;
933 break;
934
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700935 case 'k':
936 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700937 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700938
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800939 case 'n':
940 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700941 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800942
943 case 's':
944 g_initialSleepSecs = atoi(optarg);
945 break;
946
947 case 't':
948 g_traceDurationSeconds = atoi(optarg);
949 break;
950
951 case 'z':
952 g_compress = true;
953 break;
954
955 case 0:
956 if (!strcmp(long_options[option_index].name, "async_start")) {
957 async = true;
958 traceStop = false;
959 traceDump = false;
960 g_traceOverwrite = true;
961 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
962 async = true;
John Reck4ba2b632015-05-15 10:00:34 -0700963 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800964 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
965 async = true;
966 traceStart = false;
967 traceStop = false;
968 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
969 listSupportedCategories();
970 exit(0);
971 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700972 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800973
974 default:
975 fprintf(stderr, "\n");
976 showHelp(argv[0]);
977 exit(-1);
978 break;
979 }
980 }
981
982 registerSigHandler();
983
984 if (g_initialSleepSecs > 0) {
985 sleep(g_initialSleepSecs);
986 }
987
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700988 bool ok = true;
989 ok &= setUpTrace();
990 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800991
992 if (ok && traceStart) {
993 printf("capturing trace...");
994 fflush(stdout);
995
996 // We clear the trace after starting it because tracing gets enabled for
997 // each CPU individually in the kernel. Having the beginning of the trace
998 // contain entries from only one CPU can cause "begin" entries without a
999 // matching "end" entry to show up if a task gets migrated from one CPU to
1000 // another.
1001 ok = clearTrace();
1002
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001003 writeClockSyncMarker();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001004 if (ok && !async) {
1005 // Sleep to allow the trace to be captured.
1006 struct timespec timeLeft;
1007 timeLeft.tv_sec = g_traceDurationSeconds;
1008 timeLeft.tv_nsec = 0;
1009 do {
1010 if (g_traceAborted) {
1011 break;
1012 }
1013 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1014 }
1015 }
1016
1017 // Stop the trace and restore the default settings.
1018 if (traceStop)
1019 stopTrace();
1020
1021 if (ok && traceDump) {
1022 if (!g_traceAborted) {
1023 printf(" done\nTRACE:\n");
1024 fflush(stdout);
1025 dumpTrace();
1026 } else {
1027 printf("\ntrace aborted.\n");
1028 fflush(stdout);
1029 }
1030 clearTrace();
1031 } else if (!ok) {
1032 fprintf(stderr, "unable to start tracing\n");
1033 }
1034
1035 // Reset the trace buffer size to 1.
1036 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001037 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001038
1039 return g_traceAborted ? 1 : 0;
1040}