blob: 9a5a81e59a36913e5f42ed0f0b5ffe446b3cd37d [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>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080039#include <utils/Trace.h>
40
41using namespace android;
42
43#define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0])))
44
Mohamad Ayyash26dbcbe2014-04-08 15:24:11 -070045enum { MAX_SYS_FILES = 10 };
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080046
47const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
Jamie Gennisf7f29c82013-03-27 15:50:58 -070048const char* k_traceAppCmdlineProperty = "debug.atrace.app_cmdlines";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080049
50typedef enum { OPT, REQ } requiredness ;
51
52struct TracingCategory {
53 // The name identifying the category.
54 const char* name;
55
56 // A longer description of the category.
57 const char* longname;
58
59 // The userland tracing tags that the category enables.
60 uint64_t tags;
61
62 // The fname==NULL terminated list of /sys/ files that the category
63 // enables.
64 struct {
65 // Whether the file must be writable in order to enable the tracing
66 // category.
67 requiredness required;
68
69 // The path to the enable file.
70 const char* path;
71 } sysfiles[MAX_SYS_FILES];
72};
73
74/* Tracing categories */
75static const TracingCategory k_categories[] = {
Jamie Gennisb2a89e32013-03-11 19:37:53 -070076 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, { } },
77 { "input", "Input", ATRACE_TAG_INPUT, { } },
78 { "view", "View System", ATRACE_TAG_VIEW, { } },
79 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
80 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
81 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -050082 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070083 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
84 { "video", "Video", ATRACE_TAG_VIDEO, { } },
85 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
86 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -070087 { "app", "Application", ATRACE_TAG_APP, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -070088 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -070089 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -070090 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -070091 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -070092 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070093 { "sched", "CPU Scheduling", 0, {
94 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_switch/enable" },
95 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_wakeup/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080096 } },
Dan Willemsenf440d392014-04-11 15:44:09 -070097 { "irq", "IRQ Events", 0, {
98 { REQ, "/sys/kernel/debug/tracing/events/irq/enable" },
99 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700100 { "freq", "CPU Frequency", 0, {
101 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_frequency/enable" },
102 { OPT, "/sys/kernel/debug/tracing/events/power/clock_set_rate/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800103 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700104 { "membus", "Memory Bus Utilization", 0, {
105 { REQ, "/sys/kernel/debug/tracing/events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800106 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700107 { "idle", "CPU Idle", 0, {
108 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800109 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700110 { "disk", "Disk I/O", 0, {
Greg Hackmanne80d32c2014-11-20 12:59:44 -0800111 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_enter/enable" },
112 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_exit/enable" },
113 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_begin/enable" },
114 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_end/enable" },
115 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_begin/enable" },
116 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_end/enable" },
117 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable" },
118 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable" },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700119 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" },
120 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800121 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700122 { "mmc", "eMMC commands", 0, {
123 { REQ, "/sys/kernel/debug/tracing/events/mmc/enable" },
124 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700125 { "load", "CPU Load", 0, {
126 { REQ, "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800127 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700128 { "sync", "Synchronization", 0, {
129 { REQ, "/sys/kernel/debug/tracing/events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800130 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700131 { "workq", "Kernel Workqueues", 0, {
132 { REQ, "/sys/kernel/debug/tracing/events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800133 } },
Colin Cross580407f2014-08-18 15:22:13 -0700134 { "memreclaim", "Kernel Memory Reclaim", 0, {
135 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
136 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
137 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_wake/enable" },
138 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_sleep/enable" },
139 } },
Aaron Schulmancbe13ef2015-02-25 08:37:09 -0800140 { "regulators", "Voltage and Current Regulators", 0, {
141 { REQ, "/sys/kernel/debug/tracing/events/regulator/enable" },
142 } },
Scott Bauer97e5be32015-06-08 16:32:36 -0700143 { "binder_driver", "Binder Kernel driver", 0, {
144 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction/enable" },
145 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction_received/enable" },
146 } },
147 { "binder_lock", "Binder global lock trace", 0, {
148 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_lock/enable" },
149 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_locked/enable" },
150 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_unlock/enable" },
151 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800152};
153
154/* Command line options */
155static int g_traceDurationSeconds = 5;
156static bool g_traceOverwrite = false;
157static int g_traceBufferSizeKB = 2048;
158static bool g_compress = false;
159static bool g_nohup = false;
160static int g_initialSleepSecs = 0;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700161static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700162static const char* g_debugAppCmdLine = "";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800163
164/* Global state */
165static bool g_traceAborted = false;
166static bool g_categoryEnables[NELEM(k_categories)] = {};
167
168/* Sys file paths */
169static const char* k_traceClockPath =
170 "/sys/kernel/debug/tracing/trace_clock";
171
172static const char* k_traceBufferSizePath =
173 "/sys/kernel/debug/tracing/buffer_size_kb";
174
175static const char* k_tracingOverwriteEnablePath =
176 "/sys/kernel/debug/tracing/options/overwrite";
177
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700178static const char* k_currentTracerPath =
179 "/sys/kernel/debug/tracing/current_tracer";
180
181static const char* k_printTgidPath =
182 "/sys/kernel/debug/tracing/options/print-tgid";
183
184static const char* k_funcgraphAbsTimePath =
185 "/sys/kernel/debug/tracing/options/funcgraph-abstime";
186
187static const char* k_funcgraphCpuPath =
188 "/sys/kernel/debug/tracing/options/funcgraph-cpu";
189
190static const char* k_funcgraphProcPath =
191 "/sys/kernel/debug/tracing/options/funcgraph-proc";
192
193static const char* k_funcgraphFlatPath =
194 "/sys/kernel/debug/tracing/options/funcgraph-flat";
195
196static const char* k_funcgraphDurationPath =
197 "/sys/kernel/debug/tracing/options/funcgraph-duration";
198
199static const char* k_ftraceFilterPath =
200 "/sys/kernel/debug/tracing/set_ftrace_filter";
201
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800202static const char* k_tracingOnPath =
203 "/sys/kernel/debug/tracing/tracing_on";
204
205static const char* k_tracePath =
206 "/sys/kernel/debug/tracing/trace";
207
John Reck469a1942015-03-26 15:31:35 -0700208static const char* k_traceMarkerPath =
209 "/sys/kernel/debug/tracing/trace_marker";
210
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800211// Check whether a file exists.
212static bool fileExists(const char* filename) {
213 return access(filename, F_OK) != -1;
214}
215
216// Check whether a file is writable.
217static bool fileIsWritable(const char* filename) {
218 return access(filename, W_OK) != -1;
219}
220
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700221// Truncate a file.
222static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800223{
Jamie Gennis43122e72013-03-21 14:06:31 -0700224 // This uses creat rather than truncate because some of the debug kernel
225 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
226 // calls to truncate, but they are cleared by calls to creat.
227 int traceFD = creat(path, 0);
228 if (traceFD == -1) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700229 fprintf(stderr, "error truncating %s: %s (%d)\n", path,
Jamie Gennis43122e72013-03-21 14:06:31 -0700230 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700231 return false;
232 }
233
Jamie Gennis43122e72013-03-21 14:06:31 -0700234 close(traceFD);
235
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700236 return true;
237}
238
239static bool _writeStr(const char* filename, const char* str, int flags)
240{
241 int fd = open(filename, flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800242 if (fd == -1) {
243 fprintf(stderr, "error opening %s: %s (%d)\n", filename,
244 strerror(errno), errno);
245 return false;
246 }
247
248 bool ok = true;
249 ssize_t len = strlen(str);
250 if (write(fd, str, len) != len) {
251 fprintf(stderr, "error writing to %s: %s (%d)\n", filename,
252 strerror(errno), errno);
253 ok = false;
254 }
255
256 close(fd);
257
258 return ok;
259}
260
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700261// Write a string to a file, returning true if the write was successful.
262static bool writeStr(const char* filename, const char* str)
263{
264 return _writeStr(filename, str, O_WRONLY);
265}
266
267// Append a string to a file, returning true if the write was successful.
268static bool appendStr(const char* filename, const char* str)
269{
270 return _writeStr(filename, str, O_APPEND|O_WRONLY);
271}
272
John Reck469a1942015-03-26 15:31:35 -0700273static void writeClockSyncMarker()
274{
275 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200276 int len = 0;
277 int fd = open(k_traceMarkerPath, O_WRONLY);
278 if (fd == -1) {
279 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
280 strerror(errno), errno);
281 return;
282 }
John Reck469a1942015-03-26 15:31:35 -0700283 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200284
285 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
286 if (write(fd, buffer, len) != len) {
287 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
288 }
289
290 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
291 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
292 if (write(fd, buffer, len) != len) {
293 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
294 }
295
296 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700297}
298
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800299// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
300// file.
301static bool setKernelOptionEnable(const char* filename, bool enable)
302{
303 return writeStr(filename, enable ? "1" : "0");
304}
305
306// Check whether the category is supported on the device with the current
307// rootness. A category is supported only if all its required /sys/ files are
308// writable and if enabling the category will enable one or more tracing tags
309// or /sys/ files.
310static bool isCategorySupported(const TracingCategory& category)
311{
312 bool ok = category.tags != 0;
313 for (int i = 0; i < MAX_SYS_FILES; i++) {
314 const char* path = category.sysfiles[i].path;
315 bool req = category.sysfiles[i].required == REQ;
316 if (path != NULL) {
317 if (req) {
318 if (!fileIsWritable(path)) {
319 return false;
320 } else {
321 ok = true;
322 }
323 } else {
324 ok |= fileIsWritable(path);
325 }
326 }
327 }
328 return ok;
329}
330
331// Check whether the category would be supported on the device if the user
332// were root. This function assumes that root is able to write to any file
333// that exists. It performs the same logic as isCategorySupported, but it
334// uses file existance rather than writability in the /sys/ file checks.
335static bool isCategorySupportedForRoot(const TracingCategory& category)
336{
337 bool ok = category.tags != 0;
338 for (int i = 0; i < MAX_SYS_FILES; i++) {
339 const char* path = category.sysfiles[i].path;
340 bool req = category.sysfiles[i].required == REQ;
341 if (path != NULL) {
342 if (req) {
343 if (!fileExists(path)) {
344 return false;
345 } else {
346 ok = true;
347 }
348 } else {
349 ok |= fileExists(path);
350 }
351 }
352 }
353 return ok;
354}
355
356// Enable or disable overwriting of the kernel trace buffers. Disabling this
357// will cause tracing to stop once the trace buffers have filled up.
358static bool setTraceOverwriteEnable(bool enable)
359{
360 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
361}
362
363// Enable or disable kernel tracing.
364static bool setTracingEnabled(bool enable)
365{
366 return setKernelOptionEnable(k_tracingOnPath, enable);
367}
368
369// Clear the contents of the kernel trace.
370static bool clearTrace()
371{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700372 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800373}
374
375// Set the size of the kernel's trace buffer in kilobytes.
376static bool setTraceBufferSizeKB(int size)
377{
378 char str[32] = "1";
379 int len;
380 if (size < 1) {
381 size = 1;
382 }
383 snprintf(str, 32, "%d", size);
384 return writeStr(k_traceBufferSizePath, str);
385}
386
Colin Crossb1ce49b2014-08-20 14:28:47 -0700387// Read the trace_clock sysfs file and return true if it matches the requested
388// value. The trace_clock file format is:
389// local [global] counter uptime perf
390static bool isTraceClock(const char *mode)
391{
392 int fd = open(k_traceClockPath, O_RDONLY);
393 if (fd == -1) {
394 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceClockPath,
395 strerror(errno), errno);
396 return false;
397 }
398
399 char buf[4097];
400 ssize_t n = read(fd, buf, 4096);
401 close(fd);
402 if (n == -1) {
403 fprintf(stderr, "error reading %s: %s (%d)\n", k_traceClockPath,
404 strerror(errno), errno);
405 return false;
406 }
407 buf[n] = '\0';
408
409 char *start = strchr(buf, '[');
410 if (start == NULL) {
411 return false;
412 }
413 start++;
414
415 char *end = strchr(start, ']');
416 if (end == NULL) {
417 return false;
418 }
419 *end = '\0';
420
421 return strcmp(mode, start) == 0;
422}
423
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800424// Enable or disable the kernel's use of the global clock. Disabling the global
425// clock will result in the kernel using a per-CPU local clock.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700426// Any write to the trace_clock sysfs file will reset the buffer, so only
427// update it if the requested value is not the current value.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800428static bool setGlobalClockEnable(bool enable)
429{
Colin Crossb1ce49b2014-08-20 14:28:47 -0700430 const char *clock = enable ? "global" : "local";
431
432 if (isTraceClock(clock)) {
433 return true;
434 }
435
436 return writeStr(k_traceClockPath, clock);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800437}
438
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700439static bool setPrintTgidEnableIfPresent(bool enable)
440{
441 if (fileExists(k_printTgidPath)) {
442 return setKernelOptionEnable(k_printTgidPath, enable);
443 }
444 return true;
445}
446
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800447// Poke all the binder-enabled processes in the system to get them to re-read
448// their system properties.
449static bool pokeBinderServices()
450{
451 sp<IServiceManager> sm = defaultServiceManager();
452 Vector<String16> services = sm->listServices();
453 for (size_t i = 0; i < services.size(); i++) {
454 sp<IBinder> obj = sm->checkService(services[i]);
455 if (obj != NULL) {
456 Parcel data;
457 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
458 NULL, 0) != OK) {
459 if (false) {
460 // XXX: For some reason this fails on tablets trying to
461 // poke the "phone" service. It's not clear whether some
462 // are expected to fail.
463 String8 svc(services[i]);
464 fprintf(stderr, "error poking binder service %s\n",
465 svc.string());
466 return false;
467 }
468 }
469 }
470 }
471 return true;
472}
473
474// Set the trace tags that userland tracing uses, and poke the running
475// processes to pick up the new value.
476static bool setTagsProperty(uint64_t tags)
477{
478 char buf[64];
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700479 snprintf(buf, 64, "%#" PRIx64, tags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800480 if (property_set(k_traceTagsProperty, buf) < 0) {
481 fprintf(stderr, "error setting trace tags system property\n");
482 return false;
483 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700484 return true;
485}
486
487// Set the system property that indicates which apps should perform
488// application-level tracing.
489static bool setAppCmdlineProperty(const char* cmdline)
490{
491 if (property_set(k_traceAppCmdlineProperty, cmdline) < 0) {
492 fprintf(stderr, "error setting trace app system property\n");
493 return false;
494 }
495 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800496}
497
498// Disable all /sys/ enable files.
499static bool disableKernelTraceEvents() {
500 bool ok = true;
501 for (int i = 0; i < NELEM(k_categories); i++) {
502 const TracingCategory &c = k_categories[i];
503 for (int j = 0; j < MAX_SYS_FILES; j++) {
504 const char* path = c.sysfiles[j].path;
505 if (path != NULL && fileIsWritable(path)) {
506 ok &= setKernelOptionEnable(path, false);
507 }
508 }
509 }
510 return ok;
511}
512
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700513// Verify that the comma separated list of functions are being traced by the
514// kernel.
515static bool verifyKernelTraceFuncs(const char* funcs)
516{
517 int fd = open(k_ftraceFilterPath, O_RDONLY);
518 if (fd == -1) {
519 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
520 strerror(errno), errno);
521 return false;
522 }
523
524 char buf[4097];
525 ssize_t n = read(fd, buf, 4096);
526 close(fd);
527 if (n == -1) {
528 fprintf(stderr, "error reading %s: %s (%d)\n", k_ftraceFilterPath,
529 strerror(errno), errno);
530 return false;
531 }
532
533 buf[n] = '\0';
534 String8 funcList = String8::format("\n%s", buf);
535
536 // Make sure that every function listed in funcs is in the list we just
537 // read from the kernel.
538 bool ok = true;
539 char* myFuncs = strdup(funcs);
540 char* func = strtok(myFuncs, ",");
541 while (func) {
542 String8 fancyFunc = String8::format("\n%s\n", func);
543 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
544 if (!found || func[0] == '\0') {
545 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
546 "to trace.\n", func);
547 ok = false;
548 }
549 func = strtok(NULL, ",");
550 }
551 free(myFuncs);
552
553 return ok;
554}
555
556// Set the comma separated list of functions that the kernel is to trace.
557static bool setKernelTraceFuncs(const char* funcs)
558{
559 bool ok = true;
560
561 if (funcs == NULL || funcs[0] == '\0') {
562 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700563 if (fileIsWritable(k_currentTracerPath)) {
564 ok &= writeStr(k_currentTracerPath, "nop");
565 }
566 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700567 ok &= truncateFile(k_ftraceFilterPath);
568 }
569 } else {
570 // Enable kernel function tracing.
571 ok &= writeStr(k_currentTracerPath, "function_graph");
572 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
573 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
574 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
575 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
576
577 // Set the requested filter functions.
578 ok &= truncateFile(k_ftraceFilterPath);
579 char* myFuncs = strdup(funcs);
580 char* func = strtok(myFuncs, ",");
581 while (func) {
582 ok &= appendStr(k_ftraceFilterPath, func);
583 func = strtok(NULL, ",");
584 }
585 free(myFuncs);
586
587 // Verify that the set functions are being traced.
588 if (ok) {
589 ok &= verifyKernelTraceFuncs(funcs);
590 }
591 }
592
593 return ok;
594}
595
596// Set all the kernel tracing settings to the desired state for this trace
597// capture.
598static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800599{
600 bool ok = true;
601
602 // Set up the tracing options.
603 ok &= setTraceOverwriteEnable(g_traceOverwrite);
604 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
605 ok &= setGlobalClockEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700606 ok &= setPrintTgidEnableIfPresent(true);
607 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800608
609 // Set up the tags property.
610 uint64_t tags = 0;
611 for (int i = 0; i < NELEM(k_categories); i++) {
612 if (g_categoryEnables[i]) {
613 const TracingCategory &c = k_categories[i];
614 tags |= c.tags;
615 }
616 }
617 ok &= setTagsProperty(tags);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700618 ok &= setAppCmdlineProperty(g_debugAppCmdLine);
619 ok &= pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800620
621 // Disable all the sysfs enables. This is done as a separate loop from
622 // the enables to allow the same enable to exist in multiple categories.
623 ok &= disableKernelTraceEvents();
624
625 // Enable all the sysfs enables that are in an enabled category.
626 for (int i = 0; i < NELEM(k_categories); i++) {
627 if (g_categoryEnables[i]) {
628 const TracingCategory &c = k_categories[i];
629 for (int j = 0; j < MAX_SYS_FILES; j++) {
630 const char* path = c.sysfiles[j].path;
631 bool required = c.sysfiles[j].required == REQ;
632 if (path != NULL) {
633 if (fileIsWritable(path)) {
634 ok &= setKernelOptionEnable(path, true);
635 } else if (required) {
636 fprintf(stderr, "error writing file %s\n", path);
637 ok = false;
638 }
639 }
640 }
641 }
642 }
643
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800644 return ok;
645}
646
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700647// Reset all the kernel tracing settings to their default state.
648static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800649{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800650 // Disable all tracing that we're able to.
651 disableKernelTraceEvents();
652
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700653 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800654 setTagsProperty(0);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700655 setAppCmdlineProperty("");
656 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800657
658 // Set the options back to their defaults.
659 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700660 setTraceBufferSizeKB(1);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800661 setGlobalClockEnable(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700662 setPrintTgidEnableIfPresent(false);
663 setKernelTraceFuncs(NULL);
664}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800665
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700666
667// Enable tracing in the kernel.
668static bool startTrace()
669{
670 return setTracingEnabled(true);
671}
672
673// Disable tracing in the kernel.
674static void stopTrace()
675{
676 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800677}
678
679// Read the current kernel trace and write it to stdout.
680static void dumpTrace()
681{
682 int traceFD = open(k_tracePath, O_RDWR);
683 if (traceFD == -1) {
684 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
685 strerror(errno), errno);
686 return;
687 }
688
689 if (g_compress) {
690 z_stream zs;
691 uint8_t *in, *out;
692 int result, flush;
693
Elliott Hughes3da5d232015-01-25 08:35:20 -0800694 memset(&zs, 0, sizeof(zs));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800695 result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
696 if (result != Z_OK) {
697 fprintf(stderr, "error initializing zlib: %d\n", result);
698 close(traceFD);
699 return;
700 }
701
702 const size_t bufSize = 64*1024;
703 in = (uint8_t*)malloc(bufSize);
704 out = (uint8_t*)malloc(bufSize);
705 flush = Z_NO_FLUSH;
706
707 zs.next_out = out;
708 zs.avail_out = bufSize;
709
710 do {
711
712 if (zs.avail_in == 0) {
713 // More input is needed.
714 result = read(traceFD, in, bufSize);
715 if (result < 0) {
716 fprintf(stderr, "error reading trace: %s (%d)\n",
717 strerror(errno), errno);
718 result = Z_STREAM_END;
719 break;
720 } else if (result == 0) {
721 flush = Z_FINISH;
722 } else {
723 zs.next_in = in;
724 zs.avail_in = result;
725 }
726 }
727
728 if (zs.avail_out == 0) {
729 // Need to write the output.
730 result = write(STDOUT_FILENO, out, bufSize);
731 if ((size_t)result < bufSize) {
732 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
733 strerror(errno), errno);
734 result = Z_STREAM_END; // skip deflate error message
735 zs.avail_out = bufSize; // skip the final write
736 break;
737 }
738 zs.next_out = out;
739 zs.avail_out = bufSize;
740 }
741
742 } while ((result = deflate(&zs, flush)) == Z_OK);
743
744 if (result != Z_STREAM_END) {
745 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
746 }
747
748 if (zs.avail_out < bufSize) {
749 size_t bytes = bufSize - zs.avail_out;
750 result = write(STDOUT_FILENO, out, bytes);
751 if ((size_t)result < bytes) {
752 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
753 strerror(errno), errno);
754 }
755 }
756
757 result = deflateEnd(&zs);
758 if (result != Z_OK) {
759 fprintf(stderr, "error cleaning up zlib: %d\n", result);
760 }
761
762 free(in);
763 free(out);
764 } else {
765 ssize_t sent = 0;
766 while ((sent = sendfile(STDOUT_FILENO, traceFD, NULL, 64*1024*1024)) > 0);
767 if (sent == -1) {
768 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
769 errno);
770 }
771 }
772
773 close(traceFD);
774}
775
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700776static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800777{
778 if (!g_nohup) {
779 g_traceAborted = true;
780 }
781}
782
783static void registerSigHandler()
784{
785 struct sigaction sa;
786 sigemptyset(&sa.sa_mask);
787 sa.sa_flags = 0;
788 sa.sa_handler = handleSignal;
789 sigaction(SIGHUP, &sa, NULL);
790 sigaction(SIGINT, &sa, NULL);
791 sigaction(SIGQUIT, &sa, NULL);
792 sigaction(SIGTERM, &sa, NULL);
793}
794
795static bool setCategoryEnable(const char* name, bool enable)
796{
797 for (int i = 0; i < NELEM(k_categories); i++) {
798 const TracingCategory& c = k_categories[i];
799 if (strcmp(name, c.name) == 0) {
800 if (isCategorySupported(c)) {
801 g_categoryEnables[i] = enable;
802 return true;
803 } else {
804 if (isCategorySupportedForRoot(c)) {
805 fprintf(stderr, "error: category \"%s\" requires root "
806 "privileges.\n", name);
807 } else {
808 fprintf(stderr, "error: category \"%s\" is not supported "
809 "on this device.\n", name);
810 }
811 return false;
812 }
813 }
814 }
815 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
816 return false;
817}
818
819static void listSupportedCategories()
820{
821 for (int i = 0; i < NELEM(k_categories); i++) {
822 const TracingCategory& c = k_categories[i];
823 if (isCategorySupported(c)) {
824 printf(" %10s - %s\n", c.name, c.longname);
825 }
826 }
827}
828
829// Print the command usage help to stderr.
830static void showHelp(const char *cmd)
831{
832 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
833 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700834 " -a appname enable app-level tracing for a comma "
835 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800836 " -b N use a trace buffer size of N KB\n"
837 " -c trace into a circular buffer\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700838 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800839 " -n ignore signals\n"
840 " -s N sleep for N seconds before tracing [default 0]\n"
841 " -t N trace for N seconds [defualt 5]\n"
842 " -z compress the trace dump\n"
843 " --async_start start circular trace and return immediatly\n"
844 " --async_dump dump the current contents of circular trace buffer\n"
845 " --async_stop stop tracing and dump the current contents of circular\n"
846 " trace buffer\n"
Jamie Gennis92573f12012-12-07 16:29:03 -0800847 " --list_categories\n"
848 " list the available tracing categories\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800849 );
850}
851
852int main(int argc, char **argv)
853{
854 bool async = false;
855 bool traceStart = true;
856 bool traceStop = true;
857 bool traceDump = true;
858
859 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
860 showHelp(argv[0]);
861 exit(0);
862 }
863
864 for (;;) {
865 int ret;
866 int option_index = 0;
867 static struct option long_options[] = {
868 {"async_start", no_argument, 0, 0 },
869 {"async_stop", no_argument, 0, 0 },
870 {"async_dump", no_argument, 0, 0 },
871 {"list_categories", no_argument, 0, 0 },
872 { 0, 0, 0, 0 }
873 };
874
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700875 ret = getopt_long(argc, argv, "a:b:ck:ns:t:z",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800876 long_options, &option_index);
877
878 if (ret < 0) {
879 for (int i = optind; i < argc; i++) {
880 if (!setCategoryEnable(argv[i], true)) {
881 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
882 exit(1);
883 }
884 }
885 break;
886 }
887
888 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700889 case 'a':
890 g_debugAppCmdLine = optarg;
891 break;
892
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800893 case 'b':
894 g_traceBufferSizeKB = atoi(optarg);
895 break;
896
897 case 'c':
898 g_traceOverwrite = true;
899 break;
900
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700901 case 'k':
902 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700903 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700904
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800905 case 'n':
906 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700907 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800908
909 case 's':
910 g_initialSleepSecs = atoi(optarg);
911 break;
912
913 case 't':
914 g_traceDurationSeconds = atoi(optarg);
915 break;
916
917 case 'z':
918 g_compress = true;
919 break;
920
921 case 0:
922 if (!strcmp(long_options[option_index].name, "async_start")) {
923 async = true;
924 traceStop = false;
925 traceDump = false;
926 g_traceOverwrite = true;
927 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
928 async = true;
John Reck2c237ee2015-05-15 10:00:34 -0700929 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800930 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
931 async = true;
932 traceStart = false;
933 traceStop = false;
934 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
935 listSupportedCategories();
936 exit(0);
937 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700938 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800939
940 default:
941 fprintf(stderr, "\n");
942 showHelp(argv[0]);
943 exit(-1);
944 break;
945 }
946 }
947
948 registerSigHandler();
949
950 if (g_initialSleepSecs > 0) {
951 sleep(g_initialSleepSecs);
952 }
953
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700954 bool ok = true;
955 ok &= setUpTrace();
956 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800957
958 if (ok && traceStart) {
959 printf("capturing trace...");
960 fflush(stdout);
961
962 // We clear the trace after starting it because tracing gets enabled for
963 // each CPU individually in the kernel. Having the beginning of the trace
964 // contain entries from only one CPU can cause "begin" entries without a
965 // matching "end" entry to show up if a task gets migrated from one CPU to
966 // another.
967 ok = clearTrace();
968
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200969 writeClockSyncMarker();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800970 if (ok && !async) {
971 // Sleep to allow the trace to be captured.
972 struct timespec timeLeft;
973 timeLeft.tv_sec = g_traceDurationSeconds;
974 timeLeft.tv_nsec = 0;
975 do {
976 if (g_traceAborted) {
977 break;
978 }
979 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
980 }
981 }
982
983 // Stop the trace and restore the default settings.
984 if (traceStop)
985 stopTrace();
986
987 if (ok && traceDump) {
988 if (!g_traceAborted) {
989 printf(" done\nTRACE:\n");
990 fflush(stdout);
991 dumpTrace();
992 } else {
993 printf("\ntrace aborted.\n");
994 fflush(stdout);
995 }
996 clearTrace();
997 } else if (!ok) {
998 fprintf(stderr, "unable to start tracing\n");
999 }
1000
1001 // Reset the trace buffer size to 1.
1002 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001003 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001004
1005 return g_traceAborted ? 1 : 0;
1006}