blob: 6549dde29df6c818c8183de324b16f4bbff49f3e [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
Thomas Buhota2c22872016-01-27 09:44:31 +0100548 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700549 bool ok = true;
550 char* myFuncs = strdup(funcs);
551 char* func = strtok(myFuncs, ",");
552 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100553 if (!strchr(func, '*')) {
554 String8 fancyFunc = String8::format("\n%s\n", func);
555 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
556 if (!found || func[0] == '\0') {
557 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
558 "to trace.\n", func);
559 ok = false;
560 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700561 }
562 func = strtok(NULL, ",");
563 }
564 free(myFuncs);
565
566 return ok;
567}
568
569// Set the comma separated list of functions that the kernel is to trace.
570static bool setKernelTraceFuncs(const char* funcs)
571{
572 bool ok = true;
573
574 if (funcs == NULL || funcs[0] == '\0') {
575 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700576 if (fileIsWritable(k_currentTracerPath)) {
577 ok &= writeStr(k_currentTracerPath, "nop");
578 }
579 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700580 ok &= truncateFile(k_ftraceFilterPath);
581 }
582 } else {
583 // Enable kernel function tracing.
584 ok &= writeStr(k_currentTracerPath, "function_graph");
585 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
586 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
587 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
588 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
589
590 // Set the requested filter functions.
591 ok &= truncateFile(k_ftraceFilterPath);
592 char* myFuncs = strdup(funcs);
593 char* func = strtok(myFuncs, ",");
594 while (func) {
595 ok &= appendStr(k_ftraceFilterPath, func);
596 func = strtok(NULL, ",");
597 }
598 free(myFuncs);
599
600 // Verify that the set functions are being traced.
601 if (ok) {
602 ok &= verifyKernelTraceFuncs(funcs);
603 }
604 }
605
606 return ok;
607}
608
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900609static bool setCategoryEnable(const char* name, bool enable)
610{
611 for (int i = 0; i < NELEM(k_categories); i++) {
612 const TracingCategory& c = k_categories[i];
613 if (strcmp(name, c.name) == 0) {
614 if (isCategorySupported(c)) {
615 g_categoryEnables[i] = enable;
616 return true;
617 } else {
618 if (isCategorySupportedForRoot(c)) {
619 fprintf(stderr, "error: category \"%s\" requires root "
620 "privileges.\n", name);
621 } else {
622 fprintf(stderr, "error: category \"%s\" is not supported "
623 "on this device.\n", name);
624 }
625 return false;
626 }
627 }
628 }
629 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
630 return false;
631}
632
633static bool setCategoriesEnableFromFile(const char* categories_file)
634{
635 if (!categories_file) {
636 return true;
637 }
638 Tokenizer* tokenizer = NULL;
639 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
640 return false;
641 }
642 bool ok = true;
643 while (!tokenizer->isEol()) {
644 String8 token = tokenizer->nextToken(" ");
645 if (token.isEmpty()) {
646 tokenizer->skipDelimiters(" ");
647 continue;
648 }
649 ok &= setCategoryEnable(token.string(), true);
650 }
651 delete tokenizer;
652 return ok;
653}
654
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700655// Set all the kernel tracing settings to the desired state for this trace
656// capture.
657static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800658{
659 bool ok = true;
660
661 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900662 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800663 ok &= setTraceOverwriteEnable(g_traceOverwrite);
664 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
665 ok &= setGlobalClockEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700666 ok &= setPrintTgidEnableIfPresent(true);
667 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800668
669 // Set up the tags property.
670 uint64_t tags = 0;
671 for (int i = 0; i < NELEM(k_categories); i++) {
672 if (g_categoryEnables[i]) {
673 const TracingCategory &c = k_categories[i];
674 tags |= c.tags;
675 }
676 }
677 ok &= setTagsProperty(tags);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700678 ok &= setAppCmdlineProperty(g_debugAppCmdLine);
679 ok &= pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800680
681 // Disable all the sysfs enables. This is done as a separate loop from
682 // the enables to allow the same enable to exist in multiple categories.
683 ok &= disableKernelTraceEvents();
684
685 // Enable all the sysfs enables that are in an enabled category.
686 for (int i = 0; i < NELEM(k_categories); i++) {
687 if (g_categoryEnables[i]) {
688 const TracingCategory &c = k_categories[i];
689 for (int j = 0; j < MAX_SYS_FILES; j++) {
690 const char* path = c.sysfiles[j].path;
691 bool required = c.sysfiles[j].required == REQ;
692 if (path != NULL) {
693 if (fileIsWritable(path)) {
694 ok &= setKernelOptionEnable(path, true);
695 } else if (required) {
696 fprintf(stderr, "error writing file %s\n", path);
697 ok = false;
698 }
699 }
700 }
701 }
702 }
703
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800704 return ok;
705}
706
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700707// Reset all the kernel tracing settings to their default state.
708static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800709{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800710 // Disable all tracing that we're able to.
711 disableKernelTraceEvents();
712
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700713 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800714 setTagsProperty(0);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700715 setAppCmdlineProperty("");
716 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800717
718 // Set the options back to their defaults.
719 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700720 setTraceBufferSizeKB(1);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800721 setGlobalClockEnable(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700722 setPrintTgidEnableIfPresent(false);
723 setKernelTraceFuncs(NULL);
724}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800725
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700726
727// Enable tracing in the kernel.
728static bool startTrace()
729{
730 return setTracingEnabled(true);
731}
732
733// Disable tracing in the kernel.
734static void stopTrace()
735{
736 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800737}
738
Martijn Coenend9535872015-11-26 10:00:55 +0100739// Read data from the tracing pipe and forward to stdout
740static void streamTrace()
741{
742 char trace_data[4096];
743 int traceFD = open(k_traceStreamPath, O_RDWR);
744 if (traceFD == -1) {
745 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
746 strerror(errno), errno);
747 return;
748 }
749 while (!g_traceAborted) {
750 ssize_t bytes_read = read(traceFD, trace_data, 4096);
751 if (bytes_read > 0) {
752 write(STDOUT_FILENO, trace_data, bytes_read);
753 fflush(stdout);
754 } else {
755 if (!g_traceAborted) {
756 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
757 bytes_read, errno, strerror(errno));
758 }
759 break;
760 }
761 }
762}
763
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800764// Read the current kernel trace and write it to stdout.
765static void dumpTrace()
766{
767 int traceFD = open(k_tracePath, O_RDWR);
768 if (traceFD == -1) {
769 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
770 strerror(errno), errno);
771 return;
772 }
773
774 if (g_compress) {
775 z_stream zs;
776 uint8_t *in, *out;
777 int result, flush;
778
Elliott Hughes3da5d232015-01-25 08:35:20 -0800779 memset(&zs, 0, sizeof(zs));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800780 result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
781 if (result != Z_OK) {
782 fprintf(stderr, "error initializing zlib: %d\n", result);
783 close(traceFD);
784 return;
785 }
786
787 const size_t bufSize = 64*1024;
788 in = (uint8_t*)malloc(bufSize);
789 out = (uint8_t*)malloc(bufSize);
790 flush = Z_NO_FLUSH;
791
792 zs.next_out = out;
793 zs.avail_out = bufSize;
794
795 do {
796
797 if (zs.avail_in == 0) {
798 // More input is needed.
799 result = read(traceFD, in, bufSize);
800 if (result < 0) {
801 fprintf(stderr, "error reading trace: %s (%d)\n",
802 strerror(errno), errno);
803 result = Z_STREAM_END;
804 break;
805 } else if (result == 0) {
806 flush = Z_FINISH;
807 } else {
808 zs.next_in = in;
809 zs.avail_in = result;
810 }
811 }
812
813 if (zs.avail_out == 0) {
814 // Need to write the output.
815 result = write(STDOUT_FILENO, out, bufSize);
816 if ((size_t)result < bufSize) {
817 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
818 strerror(errno), errno);
819 result = Z_STREAM_END; // skip deflate error message
820 zs.avail_out = bufSize; // skip the final write
821 break;
822 }
823 zs.next_out = out;
824 zs.avail_out = bufSize;
825 }
826
827 } while ((result = deflate(&zs, flush)) == Z_OK);
828
829 if (result != Z_STREAM_END) {
830 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
831 }
832
833 if (zs.avail_out < bufSize) {
834 size_t bytes = bufSize - zs.avail_out;
835 result = write(STDOUT_FILENO, out, bytes);
836 if ((size_t)result < bytes) {
837 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
838 strerror(errno), errno);
839 }
840 }
841
842 result = deflateEnd(&zs);
843 if (result != Z_OK) {
844 fprintf(stderr, "error cleaning up zlib: %d\n", result);
845 }
846
847 free(in);
848 free(out);
849 } else {
850 ssize_t sent = 0;
851 while ((sent = sendfile(STDOUT_FILENO, traceFD, NULL, 64*1024*1024)) > 0);
852 if (sent == -1) {
853 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
854 errno);
855 }
856 }
857
858 close(traceFD);
859}
860
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700861static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800862{
863 if (!g_nohup) {
864 g_traceAborted = true;
865 }
866}
867
868static void registerSigHandler()
869{
870 struct sigaction sa;
871 sigemptyset(&sa.sa_mask);
872 sa.sa_flags = 0;
873 sa.sa_handler = handleSignal;
874 sigaction(SIGHUP, &sa, NULL);
875 sigaction(SIGINT, &sa, NULL);
876 sigaction(SIGQUIT, &sa, NULL);
877 sigaction(SIGTERM, &sa, NULL);
878}
879
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800880static void listSupportedCategories()
881{
882 for (int i = 0; i < NELEM(k_categories); i++) {
883 const TracingCategory& c = k_categories[i];
884 if (isCategorySupported(c)) {
885 printf(" %10s - %s\n", c.name, c.longname);
886 }
887 }
888}
889
890// Print the command usage help to stderr.
891static void showHelp(const char *cmd)
892{
893 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
894 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700895 " -a appname enable app-level tracing for a comma "
896 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800897 " -b N use a trace buffer size of N KB\n"
898 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900899 " -f filename use the categories written in a file as space-separated\n"
900 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700901 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800902 " -n ignore signals\n"
903 " -s N sleep for N seconds before tracing [default 0]\n"
904 " -t N trace for N seconds [defualt 5]\n"
905 " -z compress the trace dump\n"
906 " --async_start start circular trace and return immediatly\n"
907 " --async_dump dump the current contents of circular trace buffer\n"
908 " --async_stop stop tracing and dump the current contents of circular\n"
909 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +0100910 " --stream stream trace to stdout as it enters the trace buffer\n"
911 " Note: this can take significant CPU time, and is best\n"
912 " used for measuring things that are not affected by\n"
913 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -0800914 " --list_categories\n"
915 " list the available tracing categories\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800916 );
917}
918
919int main(int argc, char **argv)
920{
921 bool async = false;
922 bool traceStart = true;
923 bool traceStop = true;
924 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +0100925 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800926
927 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
928 showHelp(argv[0]);
929 exit(0);
930 }
931
932 for (;;) {
933 int ret;
934 int option_index = 0;
935 static struct option long_options[] = {
936 {"async_start", no_argument, 0, 0 },
937 {"async_stop", no_argument, 0, 0 },
938 {"async_dump", no_argument, 0, 0 },
939 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +0100940 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800941 { 0, 0, 0, 0 }
942 };
943
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900944 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:z",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800945 long_options, &option_index);
946
947 if (ret < 0) {
948 for (int i = optind; i < argc; i++) {
949 if (!setCategoryEnable(argv[i], true)) {
950 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
951 exit(1);
952 }
953 }
954 break;
955 }
956
957 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700958 case 'a':
959 g_debugAppCmdLine = optarg;
960 break;
961
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800962 case 'b':
963 g_traceBufferSizeKB = atoi(optarg);
964 break;
965
966 case 'c':
967 g_traceOverwrite = true;
968 break;
969
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900970 case 'f':
971 g_categoriesFile = optarg;
972 break;
973
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700974 case 'k':
975 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700976 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700977
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800978 case 'n':
979 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700980 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800981
982 case 's':
983 g_initialSleepSecs = atoi(optarg);
984 break;
985
986 case 't':
987 g_traceDurationSeconds = atoi(optarg);
988 break;
989
990 case 'z':
991 g_compress = true;
992 break;
993
994 case 0:
995 if (!strcmp(long_options[option_index].name, "async_start")) {
996 async = true;
997 traceStop = false;
998 traceDump = false;
999 g_traceOverwrite = true;
1000 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1001 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001002 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001003 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1004 async = true;
1005 traceStart = false;
1006 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001007 } else if (!strcmp(long_options[option_index].name, "stream")) {
1008 traceStream = true;
1009 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001010 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1011 listSupportedCategories();
1012 exit(0);
1013 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001014 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001015
1016 default:
1017 fprintf(stderr, "\n");
1018 showHelp(argv[0]);
1019 exit(-1);
1020 break;
1021 }
1022 }
1023
1024 registerSigHandler();
1025
1026 if (g_initialSleepSecs > 0) {
1027 sleep(g_initialSleepSecs);
1028 }
1029
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001030 bool ok = true;
1031 ok &= setUpTrace();
1032 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001033
1034 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001035 if (!traceStream) {
1036 printf("capturing trace...");
1037 fflush(stdout);
1038 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001039
1040 // We clear the trace after starting it because tracing gets enabled for
1041 // each CPU individually in the kernel. Having the beginning of the trace
1042 // contain entries from only one CPU can cause "begin" entries without a
1043 // matching "end" entry to show up if a task gets migrated from one CPU to
1044 // another.
1045 ok = clearTrace();
1046
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001047 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001048 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001049 // Sleep to allow the trace to be captured.
1050 struct timespec timeLeft;
1051 timeLeft.tv_sec = g_traceDurationSeconds;
1052 timeLeft.tv_nsec = 0;
1053 do {
1054 if (g_traceAborted) {
1055 break;
1056 }
1057 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1058 }
Martijn Coenend9535872015-11-26 10:00:55 +01001059
1060 if (traceStream) {
1061 streamTrace();
1062 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001063 }
1064
1065 // Stop the trace and restore the default settings.
1066 if (traceStop)
1067 stopTrace();
1068
1069 if (ok && traceDump) {
1070 if (!g_traceAborted) {
1071 printf(" done\nTRACE:\n");
1072 fflush(stdout);
1073 dumpTrace();
1074 } else {
1075 printf("\ntrace aborted.\n");
1076 fflush(stdout);
1077 }
1078 clearTrace();
1079 } else if (!ok) {
1080 fprintf(stderr, "unable to start tracing\n");
1081 }
1082
1083 // Reset the trace buffer size to 1.
1084 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001085 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001086
1087 return g_traceAborted ? 1 : 0;
1088}