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