blob: 81c8967c84bf6be5fddb832ecd4ff5a6bae31fae [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>
Martijn Coenend9535872015-11-26 10:00:55 +010029#include <unistd.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080030#include <zlib.h>
31
32#include <binder/IBinder.h>
33#include <binder/IServiceManager.h>
34#include <binder/Parcel.h>
35
36#include <cutils/properties.h>
37
38#include <utils/String8.h>
John Reck469a1942015-03-26 15:31:35 -070039#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +090040#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080041#include <utils/Trace.h>
42
43using namespace android;
44
45#define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0])))
46
Mohamad Ayyash26dbcbe2014-04-08 15:24:11 -070047enum { MAX_SYS_FILES = 10 };
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080048
49const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
Jamie Gennisf7f29c82013-03-27 15:50:58 -070050const char* k_traceAppCmdlineProperty = "debug.atrace.app_cmdlines";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080051
52typedef enum { OPT, REQ } requiredness ;
53
54struct TracingCategory {
55 // The name identifying the category.
56 const char* name;
57
58 // A longer description of the category.
59 const char* longname;
60
61 // The userland tracing tags that the category enables.
62 uint64_t tags;
63
64 // The fname==NULL terminated list of /sys/ files that the category
65 // enables.
66 struct {
67 // Whether the file must be writable in order to enable the tracing
68 // category.
69 requiredness required;
70
71 // The path to the enable file.
72 const char* path;
73 } sysfiles[MAX_SYS_FILES];
74};
75
76/* Tracing categories */
77static const TracingCategory k_categories[] = {
Jamie Gennisb2a89e32013-03-11 19:37:53 -070078 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, { } },
79 { "input", "Input", ATRACE_TAG_INPUT, { } },
80 { "view", "View System", ATRACE_TAG_VIEW, { } },
81 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
82 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
83 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -050084 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070085 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
86 { "video", "Video", ATRACE_TAG_VIDEO, { } },
87 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
88 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -070089 { "app", "Application", ATRACE_TAG_APP, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -070090 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -070091 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -070092 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -070093 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -070094 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 14:36:20 -070095 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-07-01 01:46:25 +090096 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Greg Hackmannbbd7d992014-12-01 14:43:34 -080097 { "database", "Database", ATRACE_TAG_DATABASE, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070098 { "sched", "CPU Scheduling", 0, {
99 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_switch/enable" },
100 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_wakeup/enable" },
Riley Andrews5672bb72015-11-19 13:31:17 -0800101 { OPT, "/sys/kernel/debug/tracing/events/sched/sched_blocked_reason/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800102 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700103 { "irq", "IRQ Events", 0, {
104 { REQ, "/sys/kernel/debug/tracing/events/irq/enable" },
Riley Andrews412e4f62015-11-02 21:01:34 -0800105 { OPT, "/sys/kernel/debug/tracing/events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700106 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700107 { "freq", "CPU Frequency", 0, {
108 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_frequency/enable" },
109 { OPT, "/sys/kernel/debug/tracing/events/power/clock_set_rate/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800110 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700111 { "membus", "Memory Bus Utilization", 0, {
112 { REQ, "/sys/kernel/debug/tracing/events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800113 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700114 { "idle", "CPU Idle", 0, {
115 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800116 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700117 { "disk", "Disk I/O", 0, {
Greg Hackmanne80d32c2014-11-20 12:59:44 -0800118 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_enter/enable" },
119 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_exit/enable" },
120 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_begin/enable" },
121 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_end/enable" },
122 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_begin/enable" },
123 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_end/enable" },
124 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable" },
125 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable" },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700126 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" },
127 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800128 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700129 { "mmc", "eMMC commands", 0, {
130 { REQ, "/sys/kernel/debug/tracing/events/mmc/enable" },
131 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700132 { "load", "CPU Load", 0, {
133 { REQ, "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800134 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700135 { "sync", "Synchronization", 0, {
136 { REQ, "/sys/kernel/debug/tracing/events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800137 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700138 { "workq", "Kernel Workqueues", 0, {
139 { REQ, "/sys/kernel/debug/tracing/events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800140 } },
Colin Cross580407f2014-08-18 15:22:13 -0700141 { "memreclaim", "Kernel Memory Reclaim", 0, {
142 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
143 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
144 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_wake/enable" },
145 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_sleep/enable" },
146 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800147 { "regulators", "Voltage and Current Regulators", 0, {
148 { REQ, "/sys/kernel/debug/tracing/events/regulator/enable" },
149 } },
Scott Bauerae473362015-06-08 16:32:36 -0700150 { "binder_driver", "Binder Kernel driver", 0, {
151 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction/enable" },
152 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction_received/enable" },
153 } },
154 { "binder_lock", "Binder global lock trace", 0, {
155 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_lock/enable" },
156 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_locked/enable" },
157 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_unlock/enable" },
158 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800159};
160
161/* Command line options */
162static int g_traceDurationSeconds = 5;
163static bool g_traceOverwrite = false;
164static int g_traceBufferSizeKB = 2048;
165static bool g_compress = false;
166static bool g_nohup = false;
167static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900168static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700169static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700170static const char* g_debugAppCmdLine = "";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800171
172/* Global state */
173static bool g_traceAborted = false;
174static bool g_categoryEnables[NELEM(k_categories)] = {};
175
176/* Sys file paths */
177static const char* k_traceClockPath =
178 "/sys/kernel/debug/tracing/trace_clock";
179
180static const char* k_traceBufferSizePath =
181 "/sys/kernel/debug/tracing/buffer_size_kb";
182
183static const char* k_tracingOverwriteEnablePath =
184 "/sys/kernel/debug/tracing/options/overwrite";
185
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700186static const char* k_currentTracerPath =
187 "/sys/kernel/debug/tracing/current_tracer";
188
189static const char* k_printTgidPath =
190 "/sys/kernel/debug/tracing/options/print-tgid";
191
192static const char* k_funcgraphAbsTimePath =
193 "/sys/kernel/debug/tracing/options/funcgraph-abstime";
194
195static const char* k_funcgraphCpuPath =
196 "/sys/kernel/debug/tracing/options/funcgraph-cpu";
197
198static const char* k_funcgraphProcPath =
199 "/sys/kernel/debug/tracing/options/funcgraph-proc";
200
201static const char* k_funcgraphFlatPath =
202 "/sys/kernel/debug/tracing/options/funcgraph-flat";
203
204static const char* k_funcgraphDurationPath =
205 "/sys/kernel/debug/tracing/options/funcgraph-duration";
206
207static const char* k_ftraceFilterPath =
208 "/sys/kernel/debug/tracing/set_ftrace_filter";
209
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800210static const char* k_tracingOnPath =
211 "/sys/kernel/debug/tracing/tracing_on";
212
213static const char* k_tracePath =
214 "/sys/kernel/debug/tracing/trace";
215
Martijn Coenend9535872015-11-26 10:00:55 +0100216static const char* k_traceStreamPath =
217 "/sys/kernel/debug/tracing/trace_pipe";
218
John Reck469a1942015-03-26 15:31:35 -0700219static const char* k_traceMarkerPath =
220 "/sys/kernel/debug/tracing/trace_marker";
221
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800222// Check whether a file exists.
223static bool fileExists(const char* filename) {
224 return access(filename, F_OK) != -1;
225}
226
227// Check whether a file is writable.
228static bool fileIsWritable(const char* filename) {
229 return access(filename, W_OK) != -1;
230}
231
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700232// Truncate a file.
233static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800234{
Jamie Gennis43122e72013-03-21 14:06:31 -0700235 // This uses creat rather than truncate because some of the debug kernel
236 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
237 // calls to truncate, but they are cleared by calls to creat.
238 int traceFD = creat(path, 0);
239 if (traceFD == -1) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700240 fprintf(stderr, "error truncating %s: %s (%d)\n", path,
Jamie Gennis43122e72013-03-21 14:06:31 -0700241 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700242 return false;
243 }
244
Jamie Gennis43122e72013-03-21 14:06:31 -0700245 close(traceFD);
246
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700247 return true;
248}
249
250static bool _writeStr(const char* filename, const char* str, int flags)
251{
252 int fd = open(filename, flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800253 if (fd == -1) {
254 fprintf(stderr, "error opening %s: %s (%d)\n", filename,
255 strerror(errno), errno);
256 return false;
257 }
258
259 bool ok = true;
260 ssize_t len = strlen(str);
261 if (write(fd, str, len) != len) {
262 fprintf(stderr, "error writing to %s: %s (%d)\n", filename,
263 strerror(errno), errno);
264 ok = false;
265 }
266
267 close(fd);
268
269 return ok;
270}
271
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700272// Write a string to a file, returning true if the write was successful.
273static bool writeStr(const char* filename, const char* str)
274{
275 return _writeStr(filename, str, O_WRONLY);
276}
277
278// Append a string to a file, returning true if the write was successful.
279static bool appendStr(const char* filename, const char* str)
280{
281 return _writeStr(filename, str, O_APPEND|O_WRONLY);
282}
283
John Reck469a1942015-03-26 15:31:35 -0700284static void writeClockSyncMarker()
285{
286 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200287 int len = 0;
288 int fd = open(k_traceMarkerPath, O_WRONLY);
289 if (fd == -1) {
290 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
291 strerror(errno), errno);
292 return;
293 }
John Reck469a1942015-03-26 15:31:35 -0700294 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200295
296 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
297 if (write(fd, buffer, len) != len) {
298 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
299 }
300
301 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
302 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
303 if (write(fd, buffer, len) != len) {
304 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
305 }
306
307 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700308}
309
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800310// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
311// file.
312static bool setKernelOptionEnable(const char* filename, bool enable)
313{
314 return writeStr(filename, enable ? "1" : "0");
315}
316
317// Check whether the category is supported on the device with the current
318// rootness. A category is supported only if all its required /sys/ files are
319// writable and if enabling the category will enable one or more tracing tags
320// or /sys/ files.
321static bool isCategorySupported(const TracingCategory& category)
322{
323 bool ok = category.tags != 0;
324 for (int i = 0; i < MAX_SYS_FILES; i++) {
325 const char* path = category.sysfiles[i].path;
326 bool req = category.sysfiles[i].required == REQ;
327 if (path != NULL) {
328 if (req) {
329 if (!fileIsWritable(path)) {
330 return false;
331 } else {
332 ok = true;
333 }
334 } else {
335 ok |= fileIsWritable(path);
336 }
337 }
338 }
339 return ok;
340}
341
342// Check whether the category would be supported on the device if the user
343// were root. This function assumes that root is able to write to any file
344// that exists. It performs the same logic as isCategorySupported, but it
345// uses file existance rather than writability in the /sys/ file checks.
346static bool isCategorySupportedForRoot(const TracingCategory& category)
347{
348 bool ok = category.tags != 0;
349 for (int i = 0; i < MAX_SYS_FILES; i++) {
350 const char* path = category.sysfiles[i].path;
351 bool req = category.sysfiles[i].required == REQ;
352 if (path != NULL) {
353 if (req) {
354 if (!fileExists(path)) {
355 return false;
356 } else {
357 ok = true;
358 }
359 } else {
360 ok |= fileExists(path);
361 }
362 }
363 }
364 return ok;
365}
366
367// Enable or disable overwriting of the kernel trace buffers. Disabling this
368// will cause tracing to stop once the trace buffers have filled up.
369static bool setTraceOverwriteEnable(bool enable)
370{
371 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
372}
373
374// Enable or disable kernel tracing.
375static bool setTracingEnabled(bool enable)
376{
377 return setKernelOptionEnable(k_tracingOnPath, enable);
378}
379
380// Clear the contents of the kernel trace.
381static bool clearTrace()
382{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700383 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800384}
385
386// Set the size of the kernel's trace buffer in kilobytes.
387static bool setTraceBufferSizeKB(int size)
388{
389 char str[32] = "1";
390 int len;
391 if (size < 1) {
392 size = 1;
393 }
394 snprintf(str, 32, "%d", size);
395 return writeStr(k_traceBufferSizePath, str);
396}
397
Colin Crossb1ce49b2014-08-20 14:28:47 -0700398// Read the trace_clock sysfs file and return true if it matches the requested
399// value. The trace_clock file format is:
400// local [global] counter uptime perf
401static bool isTraceClock(const char *mode)
402{
403 int fd = open(k_traceClockPath, O_RDONLY);
404 if (fd == -1) {
405 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceClockPath,
406 strerror(errno), errno);
407 return false;
408 }
409
410 char buf[4097];
411 ssize_t n = read(fd, buf, 4096);
412 close(fd);
413 if (n == -1) {
414 fprintf(stderr, "error reading %s: %s (%d)\n", k_traceClockPath,
415 strerror(errno), errno);
416 return false;
417 }
418 buf[n] = '\0';
419
420 char *start = strchr(buf, '[');
421 if (start == NULL) {
422 return false;
423 }
424 start++;
425
426 char *end = strchr(start, ']');
427 if (end == NULL) {
428 return false;
429 }
430 *end = '\0';
431
432 return strcmp(mode, start) == 0;
433}
434
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800435// Enable or disable the kernel's use of the global clock. Disabling the global
436// clock will result in the kernel using a per-CPU local clock.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700437// Any write to the trace_clock sysfs file will reset the buffer, so only
438// update it if the requested value is not the current value.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800439static bool setGlobalClockEnable(bool enable)
440{
Colin Crossb1ce49b2014-08-20 14:28:47 -0700441 const char *clock = enable ? "global" : "local";
442
443 if (isTraceClock(clock)) {
444 return true;
445 }
446
447 return writeStr(k_traceClockPath, clock);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800448}
449
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700450static bool setPrintTgidEnableIfPresent(bool enable)
451{
452 if (fileExists(k_printTgidPath)) {
453 return setKernelOptionEnable(k_printTgidPath, enable);
454 }
455 return true;
456}
457
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800458// Poke all the binder-enabled processes in the system to get them to re-read
459// their system properties.
460static bool pokeBinderServices()
461{
462 sp<IServiceManager> sm = defaultServiceManager();
463 Vector<String16> services = sm->listServices();
464 for (size_t i = 0; i < services.size(); i++) {
465 sp<IBinder> obj = sm->checkService(services[i]);
466 if (obj != NULL) {
467 Parcel data;
468 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
469 NULL, 0) != OK) {
470 if (false) {
471 // XXX: For some reason this fails on tablets trying to
472 // poke the "phone" service. It's not clear whether some
473 // are expected to fail.
474 String8 svc(services[i]);
475 fprintf(stderr, "error poking binder service %s\n",
476 svc.string());
477 return false;
478 }
479 }
480 }
481 }
482 return true;
483}
484
485// Set the trace tags that userland tracing uses, and poke the running
486// processes to pick up the new value.
487static bool setTagsProperty(uint64_t tags)
488{
489 char buf[64];
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700490 snprintf(buf, 64, "%#" PRIx64, tags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800491 if (property_set(k_traceTagsProperty, buf) < 0) {
492 fprintf(stderr, "error setting trace tags system property\n");
493 return false;
494 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700495 return true;
496}
497
498// Set the system property that indicates which apps should perform
499// application-level tracing.
500static bool setAppCmdlineProperty(const char* cmdline)
501{
502 if (property_set(k_traceAppCmdlineProperty, cmdline) < 0) {
503 fprintf(stderr, "error setting trace app system property\n");
504 return false;
505 }
506 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800507}
508
509// Disable all /sys/ enable files.
510static bool disableKernelTraceEvents() {
511 bool ok = true;
512 for (int i = 0; i < NELEM(k_categories); i++) {
513 const TracingCategory &c = k_categories[i];
514 for (int j = 0; j < MAX_SYS_FILES; j++) {
515 const char* path = c.sysfiles[j].path;
516 if (path != NULL && fileIsWritable(path)) {
517 ok &= setKernelOptionEnable(path, false);
518 }
519 }
520 }
521 return ok;
522}
523
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700524// Verify that the comma separated list of functions are being traced by the
525// kernel.
526static bool verifyKernelTraceFuncs(const char* funcs)
527{
528 int fd = open(k_ftraceFilterPath, O_RDONLY);
529 if (fd == -1) {
530 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
531 strerror(errno), errno);
532 return false;
533 }
534
535 char buf[4097];
536 ssize_t n = read(fd, buf, 4096);
537 close(fd);
538 if (n == -1) {
539 fprintf(stderr, "error reading %s: %s (%d)\n", k_ftraceFilterPath,
540 strerror(errno), errno);
541 return false;
542 }
543
544 buf[n] = '\0';
545 String8 funcList = String8::format("\n%s", buf);
546
547 // Make sure that every function listed in funcs is in the list we just
548 // read from the kernel.
549 bool ok = true;
550 char* myFuncs = strdup(funcs);
551 char* func = strtok(myFuncs, ",");
552 while (func) {
553 String8 fancyFunc = String8::format("\n%s\n", func);
554 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
555 if (!found || func[0] == '\0') {
556 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
557 "to trace.\n", func);
558 ok = false;
559 }
560 func = strtok(NULL, ",");
561 }
562 free(myFuncs);
563
564 return ok;
565}
566
567// Set the comma separated list of functions that the kernel is to trace.
568static bool setKernelTraceFuncs(const char* funcs)
569{
570 bool ok = true;
571
572 if (funcs == NULL || funcs[0] == '\0') {
573 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700574 if (fileIsWritable(k_currentTracerPath)) {
575 ok &= writeStr(k_currentTracerPath, "nop");
576 }
577 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700578 ok &= truncateFile(k_ftraceFilterPath);
579 }
580 } else {
581 // Enable kernel function tracing.
582 ok &= writeStr(k_currentTracerPath, "function_graph");
583 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
584 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
585 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
586 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
587
588 // Set the requested filter functions.
589 ok &= truncateFile(k_ftraceFilterPath);
590 char* myFuncs = strdup(funcs);
591 char* func = strtok(myFuncs, ",");
592 while (func) {
593 ok &= appendStr(k_ftraceFilterPath, func);
594 func = strtok(NULL, ",");
595 }
596 free(myFuncs);
597
598 // Verify that the set functions are being traced.
599 if (ok) {
600 ok &= verifyKernelTraceFuncs(funcs);
601 }
602 }
603
604 return ok;
605}
606
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900607static bool setCategoryEnable(const char* name, bool enable)
608{
609 for (int i = 0; i < NELEM(k_categories); i++) {
610 const TracingCategory& c = k_categories[i];
611 if (strcmp(name, c.name) == 0) {
612 if (isCategorySupported(c)) {
613 g_categoryEnables[i] = enable;
614 return true;
615 } else {
616 if (isCategorySupportedForRoot(c)) {
617 fprintf(stderr, "error: category \"%s\" requires root "
618 "privileges.\n", name);
619 } else {
620 fprintf(stderr, "error: category \"%s\" is not supported "
621 "on this device.\n", name);
622 }
623 return false;
624 }
625 }
626 }
627 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
628 return false;
629}
630
631static bool setCategoriesEnableFromFile(const char* categories_file)
632{
633 if (!categories_file) {
634 return true;
635 }
636 Tokenizer* tokenizer = NULL;
637 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
638 return false;
639 }
640 bool ok = true;
641 while (!tokenizer->isEol()) {
642 String8 token = tokenizer->nextToken(" ");
643 if (token.isEmpty()) {
644 tokenizer->skipDelimiters(" ");
645 continue;
646 }
647 ok &= setCategoryEnable(token.string(), true);
648 }
649 delete tokenizer;
650 return ok;
651}
652
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700653// Set all the kernel tracing settings to the desired state for this trace
654// capture.
655static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800656{
657 bool ok = true;
658
659 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900660 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800661 ok &= setTraceOverwriteEnable(g_traceOverwrite);
662 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
663 ok &= setGlobalClockEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700664 ok &= setPrintTgidEnableIfPresent(true);
665 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800666
667 // Set up the tags property.
668 uint64_t tags = 0;
669 for (int i = 0; i < NELEM(k_categories); i++) {
670 if (g_categoryEnables[i]) {
671 const TracingCategory &c = k_categories[i];
672 tags |= c.tags;
673 }
674 }
675 ok &= setTagsProperty(tags);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700676 ok &= setAppCmdlineProperty(g_debugAppCmdLine);
677 ok &= pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800678
679 // Disable all the sysfs enables. This is done as a separate loop from
680 // the enables to allow the same enable to exist in multiple categories.
681 ok &= disableKernelTraceEvents();
682
683 // Enable all the sysfs enables that are in an enabled category.
684 for (int i = 0; i < NELEM(k_categories); i++) {
685 if (g_categoryEnables[i]) {
686 const TracingCategory &c = k_categories[i];
687 for (int j = 0; j < MAX_SYS_FILES; j++) {
688 const char* path = c.sysfiles[j].path;
689 bool required = c.sysfiles[j].required == REQ;
690 if (path != NULL) {
691 if (fileIsWritable(path)) {
692 ok &= setKernelOptionEnable(path, true);
693 } else if (required) {
694 fprintf(stderr, "error writing file %s\n", path);
695 ok = false;
696 }
697 }
698 }
699 }
700 }
701
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800702 return ok;
703}
704
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700705// Reset all the kernel tracing settings to their default state.
706static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800707{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800708 // Disable all tracing that we're able to.
709 disableKernelTraceEvents();
710
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700711 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800712 setTagsProperty(0);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700713 setAppCmdlineProperty("");
714 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800715
716 // Set the options back to their defaults.
717 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700718 setTraceBufferSizeKB(1);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800719 setGlobalClockEnable(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700720 setPrintTgidEnableIfPresent(false);
721 setKernelTraceFuncs(NULL);
722}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800723
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700724
725// Enable tracing in the kernel.
726static bool startTrace()
727{
728 return setTracingEnabled(true);
729}
730
731// Disable tracing in the kernel.
732static void stopTrace()
733{
734 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800735}
736
Martijn Coenend9535872015-11-26 10:00:55 +0100737// Read data from the tracing pipe and forward to stdout
738static void streamTrace()
739{
740 char trace_data[4096];
741 int traceFD = open(k_traceStreamPath, O_RDWR);
742 if (traceFD == -1) {
743 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
744 strerror(errno), errno);
745 return;
746 }
747 while (!g_traceAborted) {
748 ssize_t bytes_read = read(traceFD, trace_data, 4096);
749 if (bytes_read > 0) {
750 write(STDOUT_FILENO, trace_data, bytes_read);
751 fflush(stdout);
752 } else {
753 if (!g_traceAborted) {
754 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
755 bytes_read, errno, strerror(errno));
756 }
757 break;
758 }
759 }
760}
761
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800762// Read the current kernel trace and write it to stdout.
763static void dumpTrace()
764{
765 int traceFD = open(k_tracePath, O_RDWR);
766 if (traceFD == -1) {
767 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
768 strerror(errno), errno);
769 return;
770 }
771
772 if (g_compress) {
773 z_stream zs;
774 uint8_t *in, *out;
775 int result, flush;
776
Elliott Hughes3da5d232015-01-25 08:35:20 -0800777 memset(&zs, 0, sizeof(zs));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800778 result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
779 if (result != Z_OK) {
780 fprintf(stderr, "error initializing zlib: %d\n", result);
781 close(traceFD);
782 return;
783 }
784
785 const size_t bufSize = 64*1024;
786 in = (uint8_t*)malloc(bufSize);
787 out = (uint8_t*)malloc(bufSize);
788 flush = Z_NO_FLUSH;
789
790 zs.next_out = out;
791 zs.avail_out = bufSize;
792
793 do {
794
795 if (zs.avail_in == 0) {
796 // More input is needed.
797 result = read(traceFD, in, bufSize);
798 if (result < 0) {
799 fprintf(stderr, "error reading trace: %s (%d)\n",
800 strerror(errno), errno);
801 result = Z_STREAM_END;
802 break;
803 } else if (result == 0) {
804 flush = Z_FINISH;
805 } else {
806 zs.next_in = in;
807 zs.avail_in = result;
808 }
809 }
810
811 if (zs.avail_out == 0) {
812 // Need to write the output.
813 result = write(STDOUT_FILENO, out, bufSize);
814 if ((size_t)result < bufSize) {
815 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
816 strerror(errno), errno);
817 result = Z_STREAM_END; // skip deflate error message
818 zs.avail_out = bufSize; // skip the final write
819 break;
820 }
821 zs.next_out = out;
822 zs.avail_out = bufSize;
823 }
824
825 } while ((result = deflate(&zs, flush)) == Z_OK);
826
827 if (result != Z_STREAM_END) {
828 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
829 }
830
831 if (zs.avail_out < bufSize) {
832 size_t bytes = bufSize - zs.avail_out;
833 result = write(STDOUT_FILENO, out, bytes);
834 if ((size_t)result < bytes) {
835 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
836 strerror(errno), errno);
837 }
838 }
839
840 result = deflateEnd(&zs);
841 if (result != Z_OK) {
842 fprintf(stderr, "error cleaning up zlib: %d\n", result);
843 }
844
845 free(in);
846 free(out);
847 } else {
848 ssize_t sent = 0;
849 while ((sent = sendfile(STDOUT_FILENO, traceFD, NULL, 64*1024*1024)) > 0);
850 if (sent == -1) {
851 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
852 errno);
853 }
854 }
855
856 close(traceFD);
857}
858
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700859static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800860{
861 if (!g_nohup) {
862 g_traceAborted = true;
863 }
864}
865
866static void registerSigHandler()
867{
868 struct sigaction sa;
869 sigemptyset(&sa.sa_mask);
870 sa.sa_flags = 0;
871 sa.sa_handler = handleSignal;
872 sigaction(SIGHUP, &sa, NULL);
873 sigaction(SIGINT, &sa, NULL);
874 sigaction(SIGQUIT, &sa, NULL);
875 sigaction(SIGTERM, &sa, NULL);
876}
877
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800878static void listSupportedCategories()
879{
880 for (int i = 0; i < NELEM(k_categories); i++) {
881 const TracingCategory& c = k_categories[i];
882 if (isCategorySupported(c)) {
883 printf(" %10s - %s\n", c.name, c.longname);
884 }
885 }
886}
887
888// Print the command usage help to stderr.
889static void showHelp(const char *cmd)
890{
891 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
892 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700893 " -a appname enable app-level tracing for a comma "
894 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800895 " -b N use a trace buffer size of N KB\n"
896 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900897 " -f filename use the categories written in a file as space-separated\n"
898 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700899 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800900 " -n ignore signals\n"
901 " -s N sleep for N seconds before tracing [default 0]\n"
902 " -t N trace for N seconds [defualt 5]\n"
903 " -z compress the trace dump\n"
904 " --async_start start circular trace and return immediatly\n"
905 " --async_dump dump the current contents of circular trace buffer\n"
906 " --async_stop stop tracing and dump the current contents of circular\n"
907 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +0100908 " --stream stream trace to stdout as it enters the trace buffer\n"
909 " Note: this can take significant CPU time, and is best\n"
910 " used for measuring things that are not affected by\n"
911 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -0800912 " --list_categories\n"
913 " list the available tracing categories\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800914 );
915}
916
917int main(int argc, char **argv)
918{
919 bool async = false;
920 bool traceStart = true;
921 bool traceStop = true;
922 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +0100923 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800924
925 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
926 showHelp(argv[0]);
927 exit(0);
928 }
929
930 for (;;) {
931 int ret;
932 int option_index = 0;
933 static struct option long_options[] = {
934 {"async_start", no_argument, 0, 0 },
935 {"async_stop", no_argument, 0, 0 },
936 {"async_dump", no_argument, 0, 0 },
937 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +0100938 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800939 { 0, 0, 0, 0 }
940 };
941
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900942 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:z",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800943 long_options, &option_index);
944
945 if (ret < 0) {
946 for (int i = optind; i < argc; i++) {
947 if (!setCategoryEnable(argv[i], true)) {
948 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
949 exit(1);
950 }
951 }
952 break;
953 }
954
955 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700956 case 'a':
957 g_debugAppCmdLine = optarg;
958 break;
959
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800960 case 'b':
961 g_traceBufferSizeKB = atoi(optarg);
962 break;
963
964 case 'c':
965 g_traceOverwrite = true;
966 break;
967
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900968 case 'f':
969 g_categoriesFile = optarg;
970 break;
971
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700972 case 'k':
973 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700974 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700975
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800976 case 'n':
977 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700978 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800979
980 case 's':
981 g_initialSleepSecs = atoi(optarg);
982 break;
983
984 case 't':
985 g_traceDurationSeconds = atoi(optarg);
986 break;
987
988 case 'z':
989 g_compress = true;
990 break;
991
992 case 0:
993 if (!strcmp(long_options[option_index].name, "async_start")) {
994 async = true;
995 traceStop = false;
996 traceDump = false;
997 g_traceOverwrite = true;
998 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
999 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001000 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001001 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1002 async = true;
1003 traceStart = false;
1004 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001005 } else if (!strcmp(long_options[option_index].name, "stream")) {
1006 traceStream = true;
1007 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001008 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1009 listSupportedCategories();
1010 exit(0);
1011 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001012 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001013
1014 default:
1015 fprintf(stderr, "\n");
1016 showHelp(argv[0]);
1017 exit(-1);
1018 break;
1019 }
1020 }
1021
1022 registerSigHandler();
1023
1024 if (g_initialSleepSecs > 0) {
1025 sleep(g_initialSleepSecs);
1026 }
1027
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001028 bool ok = true;
1029 ok &= setUpTrace();
1030 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001031
1032 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001033 if (!traceStream) {
1034 printf("capturing trace...");
1035 fflush(stdout);
1036 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001037
1038 // We clear the trace after starting it because tracing gets enabled for
1039 // each CPU individually in the kernel. Having the beginning of the trace
1040 // contain entries from only one CPU can cause "begin" entries without a
1041 // matching "end" entry to show up if a task gets migrated from one CPU to
1042 // another.
1043 ok = clearTrace();
1044
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001045 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001046 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001047 // Sleep to allow the trace to be captured.
1048 struct timespec timeLeft;
1049 timeLeft.tv_sec = g_traceDurationSeconds;
1050 timeLeft.tv_nsec = 0;
1051 do {
1052 if (g_traceAborted) {
1053 break;
1054 }
1055 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1056 }
Martijn Coenend9535872015-11-26 10:00:55 +01001057
1058 if (traceStream) {
1059 streamTrace();
1060 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001061 }
1062
1063 // Stop the trace and restore the default settings.
1064 if (traceStop)
1065 stopTrace();
1066
1067 if (ok && traceDump) {
1068 if (!g_traceAborted) {
1069 printf(" done\nTRACE:\n");
1070 fflush(stdout);
1071 dumpTrace();
1072 } else {
1073 printf("\ntrace aborted.\n");
1074 fflush(stdout);
1075 }
1076 clearTrace();
1077 } else if (!ok) {
1078 fprintf(stderr, "unable to start tracing\n");
1079 }
1080
1081 // Reset the trace buffer size to 1.
1082 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001083 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001084
1085 return g_traceAborted ? 1 : 0;
1086}