blob: 7201e77ca532bf5ad1b486854494701e63b6ef09 [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" },
Tim Murraybd651612015-11-30 10:59:55 -080096 { OPT, "/sys/kernel/debug/tracing/events/sched/sched_blocked_reason/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080097 } },
Dan Willemsenf440d392014-04-11 15:44:09 -070098 { "irq", "IRQ Events", 0, {
99 { REQ, "/sys/kernel/debug/tracing/events/irq/enable" },
100 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700101 { "freq", "CPU Frequency", 0, {
102 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_frequency/enable" },
103 { OPT, "/sys/kernel/debug/tracing/events/power/clock_set_rate/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800104 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700105 { "membus", "Memory Bus Utilization", 0, {
106 { REQ, "/sys/kernel/debug/tracing/events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800107 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700108 { "idle", "CPU Idle", 0, {
109 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800110 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700111 { "disk", "Disk I/O", 0, {
Greg Hackmanne80d32c2014-11-20 12:59:44 -0800112 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_enter/enable" },
113 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_exit/enable" },
114 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_begin/enable" },
115 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_end/enable" },
116 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_begin/enable" },
117 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_end/enable" },
118 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable" },
119 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable" },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700120 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" },
121 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800122 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700123 { "mmc", "eMMC commands", 0, {
124 { REQ, "/sys/kernel/debug/tracing/events/mmc/enable" },
125 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700126 { "load", "CPU Load", 0, {
127 { REQ, "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800128 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700129 { "sync", "Synchronization", 0, {
130 { REQ, "/sys/kernel/debug/tracing/events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800131 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700132 { "workq", "Kernel Workqueues", 0, {
133 { REQ, "/sys/kernel/debug/tracing/events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800134 } },
Colin Cross580407f2014-08-18 15:22:13 -0700135 { "memreclaim", "Kernel Memory Reclaim", 0, {
136 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
137 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
138 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_wake/enable" },
139 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_sleep/enable" },
140 } },
Aaron Schulmancbe13ef2015-02-25 08:37:09 -0800141 { "regulators", "Voltage and Current Regulators", 0, {
142 { REQ, "/sys/kernel/debug/tracing/events/regulator/enable" },
143 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800144};
145
146/* Command line options */
147static int g_traceDurationSeconds = 5;
148static bool g_traceOverwrite = false;
149static int g_traceBufferSizeKB = 2048;
150static bool g_compress = false;
151static bool g_nohup = false;
152static int g_initialSleepSecs = 0;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700153static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700154static const char* g_debugAppCmdLine = "";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800155
156/* Global state */
157static bool g_traceAborted = false;
158static bool g_categoryEnables[NELEM(k_categories)] = {};
159
160/* Sys file paths */
161static const char* k_traceClockPath =
162 "/sys/kernel/debug/tracing/trace_clock";
163
164static const char* k_traceBufferSizePath =
165 "/sys/kernel/debug/tracing/buffer_size_kb";
166
167static const char* k_tracingOverwriteEnablePath =
168 "/sys/kernel/debug/tracing/options/overwrite";
169
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700170static const char* k_currentTracerPath =
171 "/sys/kernel/debug/tracing/current_tracer";
172
173static const char* k_printTgidPath =
174 "/sys/kernel/debug/tracing/options/print-tgid";
175
176static const char* k_funcgraphAbsTimePath =
177 "/sys/kernel/debug/tracing/options/funcgraph-abstime";
178
179static const char* k_funcgraphCpuPath =
180 "/sys/kernel/debug/tracing/options/funcgraph-cpu";
181
182static const char* k_funcgraphProcPath =
183 "/sys/kernel/debug/tracing/options/funcgraph-proc";
184
185static const char* k_funcgraphFlatPath =
186 "/sys/kernel/debug/tracing/options/funcgraph-flat";
187
188static const char* k_funcgraphDurationPath =
189 "/sys/kernel/debug/tracing/options/funcgraph-duration";
190
191static const char* k_ftraceFilterPath =
192 "/sys/kernel/debug/tracing/set_ftrace_filter";
193
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800194static const char* k_tracingOnPath =
195 "/sys/kernel/debug/tracing/tracing_on";
196
197static const char* k_tracePath =
198 "/sys/kernel/debug/tracing/trace";
199
John Reck469a1942015-03-26 15:31:35 -0700200static const char* k_traceMarkerPath =
201 "/sys/kernel/debug/tracing/trace_marker";
202
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800203// Check whether a file exists.
204static bool fileExists(const char* filename) {
205 return access(filename, F_OK) != -1;
206}
207
208// Check whether a file is writable.
209static bool fileIsWritable(const char* filename) {
210 return access(filename, W_OK) != -1;
211}
212
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700213// Truncate a file.
214static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800215{
Jamie Gennis43122e72013-03-21 14:06:31 -0700216 // This uses creat rather than truncate because some of the debug kernel
217 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
218 // calls to truncate, but they are cleared by calls to creat.
219 int traceFD = creat(path, 0);
220 if (traceFD == -1) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700221 fprintf(stderr, "error truncating %s: %s (%d)\n", path,
Jamie Gennis43122e72013-03-21 14:06:31 -0700222 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700223 return false;
224 }
225
Jamie Gennis43122e72013-03-21 14:06:31 -0700226 close(traceFD);
227
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700228 return true;
229}
230
231static bool _writeStr(const char* filename, const char* str, int flags)
232{
233 int fd = open(filename, flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800234 if (fd == -1) {
235 fprintf(stderr, "error opening %s: %s (%d)\n", filename,
236 strerror(errno), errno);
237 return false;
238 }
239
240 bool ok = true;
241 ssize_t len = strlen(str);
242 if (write(fd, str, len) != len) {
243 fprintf(stderr, "error writing to %s: %s (%d)\n", filename,
244 strerror(errno), errno);
245 ok = false;
246 }
247
248 close(fd);
249
250 return ok;
251}
252
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700253// Write a string to a file, returning true if the write was successful.
254static bool writeStr(const char* filename, const char* str)
255{
256 return _writeStr(filename, str, O_WRONLY);
257}
258
259// Append a string to a file, returning true if the write was successful.
260static bool appendStr(const char* filename, const char* str)
261{
262 return _writeStr(filename, str, O_APPEND|O_WRONLY);
263}
264
John Reck469a1942015-03-26 15:31:35 -0700265static void writeClockSyncMarker()
266{
267 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200268 int len = 0;
269 int fd = open(k_traceMarkerPath, O_WRONLY);
270 if (fd == -1) {
271 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
272 strerror(errno), errno);
273 return;
274 }
John Reck469a1942015-03-26 15:31:35 -0700275 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200276
277 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
278 if (write(fd, buffer, len) != len) {
279 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
280 }
281
282 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
283 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
284 if (write(fd, buffer, len) != len) {
285 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
286 }
287
288 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700289}
290
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800291// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
292// file.
293static bool setKernelOptionEnable(const char* filename, bool enable)
294{
295 return writeStr(filename, enable ? "1" : "0");
296}
297
298// Check whether the category is supported on the device with the current
299// rootness. A category is supported only if all its required /sys/ files are
300// writable and if enabling the category will enable one or more tracing tags
301// or /sys/ files.
302static bool isCategorySupported(const TracingCategory& category)
303{
304 bool ok = category.tags != 0;
305 for (int i = 0; i < MAX_SYS_FILES; i++) {
306 const char* path = category.sysfiles[i].path;
307 bool req = category.sysfiles[i].required == REQ;
308 if (path != NULL) {
309 if (req) {
310 if (!fileIsWritable(path)) {
311 return false;
312 } else {
313 ok = true;
314 }
315 } else {
316 ok |= fileIsWritable(path);
317 }
318 }
319 }
320 return ok;
321}
322
323// Check whether the category would be supported on the device if the user
324// were root. This function assumes that root is able to write to any file
325// that exists. It performs the same logic as isCategorySupported, but it
326// uses file existance rather than writability in the /sys/ file checks.
327static bool isCategorySupportedForRoot(const TracingCategory& category)
328{
329 bool ok = category.tags != 0;
330 for (int i = 0; i < MAX_SYS_FILES; i++) {
331 const char* path = category.sysfiles[i].path;
332 bool req = category.sysfiles[i].required == REQ;
333 if (path != NULL) {
334 if (req) {
335 if (!fileExists(path)) {
336 return false;
337 } else {
338 ok = true;
339 }
340 } else {
341 ok |= fileExists(path);
342 }
343 }
344 }
345 return ok;
346}
347
348// Enable or disable overwriting of the kernel trace buffers. Disabling this
349// will cause tracing to stop once the trace buffers have filled up.
350static bool setTraceOverwriteEnable(bool enable)
351{
352 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
353}
354
355// Enable or disable kernel tracing.
356static bool setTracingEnabled(bool enable)
357{
358 return setKernelOptionEnable(k_tracingOnPath, enable);
359}
360
361// Clear the contents of the kernel trace.
362static bool clearTrace()
363{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700364 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800365}
366
367// Set the size of the kernel's trace buffer in kilobytes.
368static bool setTraceBufferSizeKB(int size)
369{
370 char str[32] = "1";
371 int len;
372 if (size < 1) {
373 size = 1;
374 }
375 snprintf(str, 32, "%d", size);
376 return writeStr(k_traceBufferSizePath, str);
377}
378
Colin Crossb1ce49b2014-08-20 14:28:47 -0700379// Read the trace_clock sysfs file and return true if it matches the requested
380// value. The trace_clock file format is:
381// local [global] counter uptime perf
382static bool isTraceClock(const char *mode)
383{
384 int fd = open(k_traceClockPath, O_RDONLY);
385 if (fd == -1) {
386 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceClockPath,
387 strerror(errno), errno);
388 return false;
389 }
390
391 char buf[4097];
392 ssize_t n = read(fd, buf, 4096);
393 close(fd);
394 if (n == -1) {
395 fprintf(stderr, "error reading %s: %s (%d)\n", k_traceClockPath,
396 strerror(errno), errno);
397 return false;
398 }
399 buf[n] = '\0';
400
401 char *start = strchr(buf, '[');
402 if (start == NULL) {
403 return false;
404 }
405 start++;
406
407 char *end = strchr(start, ']');
408 if (end == NULL) {
409 return false;
410 }
411 *end = '\0';
412
413 return strcmp(mode, start) == 0;
414}
415
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800416// Enable or disable the kernel's use of the global clock. Disabling the global
417// clock will result in the kernel using a per-CPU local clock.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700418// Any write to the trace_clock sysfs file will reset the buffer, so only
419// update it if the requested value is not the current value.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800420static bool setGlobalClockEnable(bool enable)
421{
Colin Crossb1ce49b2014-08-20 14:28:47 -0700422 const char *clock = enable ? "global" : "local";
423
424 if (isTraceClock(clock)) {
425 return true;
426 }
427
428 return writeStr(k_traceClockPath, clock);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800429}
430
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700431static bool setPrintTgidEnableIfPresent(bool enable)
432{
433 if (fileExists(k_printTgidPath)) {
434 return setKernelOptionEnable(k_printTgidPath, enable);
435 }
436 return true;
437}
438
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800439// Poke all the binder-enabled processes in the system to get them to re-read
440// their system properties.
441static bool pokeBinderServices()
442{
443 sp<IServiceManager> sm = defaultServiceManager();
444 Vector<String16> services = sm->listServices();
445 for (size_t i = 0; i < services.size(); i++) {
446 sp<IBinder> obj = sm->checkService(services[i]);
447 if (obj != NULL) {
448 Parcel data;
449 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
450 NULL, 0) != OK) {
451 if (false) {
452 // XXX: For some reason this fails on tablets trying to
453 // poke the "phone" service. It's not clear whether some
454 // are expected to fail.
455 String8 svc(services[i]);
456 fprintf(stderr, "error poking binder service %s\n",
457 svc.string());
458 return false;
459 }
460 }
461 }
462 }
463 return true;
464}
465
466// Set the trace tags that userland tracing uses, and poke the running
467// processes to pick up the new value.
468static bool setTagsProperty(uint64_t tags)
469{
470 char buf[64];
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700471 snprintf(buf, 64, "%#" PRIx64, tags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800472 if (property_set(k_traceTagsProperty, buf) < 0) {
473 fprintf(stderr, "error setting trace tags system property\n");
474 return false;
475 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700476 return true;
477}
478
479// Set the system property that indicates which apps should perform
480// application-level tracing.
481static bool setAppCmdlineProperty(const char* cmdline)
482{
483 if (property_set(k_traceAppCmdlineProperty, cmdline) < 0) {
484 fprintf(stderr, "error setting trace app system property\n");
485 return false;
486 }
487 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800488}
489
490// Disable all /sys/ enable files.
491static bool disableKernelTraceEvents() {
492 bool ok = true;
493 for (int i = 0; i < NELEM(k_categories); i++) {
494 const TracingCategory &c = k_categories[i];
495 for (int j = 0; j < MAX_SYS_FILES; j++) {
496 const char* path = c.sysfiles[j].path;
497 if (path != NULL && fileIsWritable(path)) {
498 ok &= setKernelOptionEnable(path, false);
499 }
500 }
501 }
502 return ok;
503}
504
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700505// Verify that the comma separated list of functions are being traced by the
506// kernel.
507static bool verifyKernelTraceFuncs(const char* funcs)
508{
509 int fd = open(k_ftraceFilterPath, O_RDONLY);
510 if (fd == -1) {
511 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
512 strerror(errno), errno);
513 return false;
514 }
515
516 char buf[4097];
517 ssize_t n = read(fd, buf, 4096);
518 close(fd);
519 if (n == -1) {
520 fprintf(stderr, "error reading %s: %s (%d)\n", k_ftraceFilterPath,
521 strerror(errno), errno);
522 return false;
523 }
524
525 buf[n] = '\0';
526 String8 funcList = String8::format("\n%s", buf);
527
528 // Make sure that every function listed in funcs is in the list we just
529 // read from the kernel.
530 bool ok = true;
531 char* myFuncs = strdup(funcs);
532 char* func = strtok(myFuncs, ",");
533 while (func) {
534 String8 fancyFunc = String8::format("\n%s\n", func);
535 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
536 if (!found || func[0] == '\0') {
537 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
538 "to trace.\n", func);
539 ok = false;
540 }
541 func = strtok(NULL, ",");
542 }
543 free(myFuncs);
544
545 return ok;
546}
547
548// Set the comma separated list of functions that the kernel is to trace.
549static bool setKernelTraceFuncs(const char* funcs)
550{
551 bool ok = true;
552
553 if (funcs == NULL || funcs[0] == '\0') {
554 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700555 if (fileIsWritable(k_currentTracerPath)) {
556 ok &= writeStr(k_currentTracerPath, "nop");
557 }
558 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700559 ok &= truncateFile(k_ftraceFilterPath);
560 }
561 } else {
562 // Enable kernel function tracing.
563 ok &= writeStr(k_currentTracerPath, "function_graph");
564 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
565 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
566 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
567 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
568
569 // Set the requested filter functions.
570 ok &= truncateFile(k_ftraceFilterPath);
571 char* myFuncs = strdup(funcs);
572 char* func = strtok(myFuncs, ",");
573 while (func) {
574 ok &= appendStr(k_ftraceFilterPath, func);
575 func = strtok(NULL, ",");
576 }
577 free(myFuncs);
578
579 // Verify that the set functions are being traced.
580 if (ok) {
581 ok &= verifyKernelTraceFuncs(funcs);
582 }
583 }
584
585 return ok;
586}
587
588// Set all the kernel tracing settings to the desired state for this trace
589// capture.
590static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800591{
592 bool ok = true;
593
594 // Set up the tracing options.
595 ok &= setTraceOverwriteEnable(g_traceOverwrite);
596 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
597 ok &= setGlobalClockEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700598 ok &= setPrintTgidEnableIfPresent(true);
599 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800600
601 // Set up the tags property.
602 uint64_t tags = 0;
603 for (int i = 0; i < NELEM(k_categories); i++) {
604 if (g_categoryEnables[i]) {
605 const TracingCategory &c = k_categories[i];
606 tags |= c.tags;
607 }
608 }
609 ok &= setTagsProperty(tags);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700610 ok &= setAppCmdlineProperty(g_debugAppCmdLine);
611 ok &= pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800612
613 // Disable all the sysfs enables. This is done as a separate loop from
614 // the enables to allow the same enable to exist in multiple categories.
615 ok &= disableKernelTraceEvents();
616
617 // Enable all the sysfs enables that are in an enabled category.
618 for (int i = 0; i < NELEM(k_categories); i++) {
619 if (g_categoryEnables[i]) {
620 const TracingCategory &c = k_categories[i];
621 for (int j = 0; j < MAX_SYS_FILES; j++) {
622 const char* path = c.sysfiles[j].path;
623 bool required = c.sysfiles[j].required == REQ;
624 if (path != NULL) {
625 if (fileIsWritable(path)) {
626 ok &= setKernelOptionEnable(path, true);
627 } else if (required) {
628 fprintf(stderr, "error writing file %s\n", path);
629 ok = false;
630 }
631 }
632 }
633 }
634 }
635
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800636 return ok;
637}
638
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700639// Reset all the kernel tracing settings to their default state.
640static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800641{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800642 // Disable all tracing that we're able to.
643 disableKernelTraceEvents();
644
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700645 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800646 setTagsProperty(0);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700647 setAppCmdlineProperty("");
648 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800649
650 // Set the options back to their defaults.
651 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700652 setTraceBufferSizeKB(1);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800653 setGlobalClockEnable(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700654 setPrintTgidEnableIfPresent(false);
655 setKernelTraceFuncs(NULL);
656}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800657
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700658
659// Enable tracing in the kernel.
660static bool startTrace()
661{
662 return setTracingEnabled(true);
663}
664
665// Disable tracing in the kernel.
666static void stopTrace()
667{
668 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800669}
670
671// Read the current kernel trace and write it to stdout.
672static void dumpTrace()
673{
674 int traceFD = open(k_tracePath, O_RDWR);
675 if (traceFD == -1) {
676 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
677 strerror(errno), errno);
678 return;
679 }
680
681 if (g_compress) {
682 z_stream zs;
683 uint8_t *in, *out;
684 int result, flush;
685
Elliott Hughes3da5d232015-01-25 08:35:20 -0800686 memset(&zs, 0, sizeof(zs));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800687 result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
688 if (result != Z_OK) {
689 fprintf(stderr, "error initializing zlib: %d\n", result);
690 close(traceFD);
691 return;
692 }
693
694 const size_t bufSize = 64*1024;
695 in = (uint8_t*)malloc(bufSize);
696 out = (uint8_t*)malloc(bufSize);
697 flush = Z_NO_FLUSH;
698
699 zs.next_out = out;
700 zs.avail_out = bufSize;
701
702 do {
703
704 if (zs.avail_in == 0) {
705 // More input is needed.
706 result = read(traceFD, in, bufSize);
707 if (result < 0) {
708 fprintf(stderr, "error reading trace: %s (%d)\n",
709 strerror(errno), errno);
710 result = Z_STREAM_END;
711 break;
712 } else if (result == 0) {
713 flush = Z_FINISH;
714 } else {
715 zs.next_in = in;
716 zs.avail_in = result;
717 }
718 }
719
720 if (zs.avail_out == 0) {
721 // Need to write the output.
722 result = write(STDOUT_FILENO, out, bufSize);
723 if ((size_t)result < bufSize) {
724 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
725 strerror(errno), errno);
726 result = Z_STREAM_END; // skip deflate error message
727 zs.avail_out = bufSize; // skip the final write
728 break;
729 }
730 zs.next_out = out;
731 zs.avail_out = bufSize;
732 }
733
734 } while ((result = deflate(&zs, flush)) == Z_OK);
735
736 if (result != Z_STREAM_END) {
737 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
738 }
739
740 if (zs.avail_out < bufSize) {
741 size_t bytes = bufSize - zs.avail_out;
742 result = write(STDOUT_FILENO, out, bytes);
743 if ((size_t)result < bytes) {
744 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
745 strerror(errno), errno);
746 }
747 }
748
749 result = deflateEnd(&zs);
750 if (result != Z_OK) {
751 fprintf(stderr, "error cleaning up zlib: %d\n", result);
752 }
753
754 free(in);
755 free(out);
756 } else {
757 ssize_t sent = 0;
758 while ((sent = sendfile(STDOUT_FILENO, traceFD, NULL, 64*1024*1024)) > 0);
759 if (sent == -1) {
760 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
761 errno);
762 }
763 }
764
765 close(traceFD);
766}
767
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700768static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800769{
770 if (!g_nohup) {
771 g_traceAborted = true;
772 }
773}
774
775static void registerSigHandler()
776{
777 struct sigaction sa;
778 sigemptyset(&sa.sa_mask);
779 sa.sa_flags = 0;
780 sa.sa_handler = handleSignal;
781 sigaction(SIGHUP, &sa, NULL);
782 sigaction(SIGINT, &sa, NULL);
783 sigaction(SIGQUIT, &sa, NULL);
784 sigaction(SIGTERM, &sa, NULL);
785}
786
787static bool setCategoryEnable(const char* name, bool enable)
788{
789 for (int i = 0; i < NELEM(k_categories); i++) {
790 const TracingCategory& c = k_categories[i];
791 if (strcmp(name, c.name) == 0) {
792 if (isCategorySupported(c)) {
793 g_categoryEnables[i] = enable;
794 return true;
795 } else {
796 if (isCategorySupportedForRoot(c)) {
797 fprintf(stderr, "error: category \"%s\" requires root "
798 "privileges.\n", name);
799 } else {
800 fprintf(stderr, "error: category \"%s\" is not supported "
801 "on this device.\n", name);
802 }
803 return false;
804 }
805 }
806 }
807 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
808 return false;
809}
810
811static void listSupportedCategories()
812{
813 for (int i = 0; i < NELEM(k_categories); i++) {
814 const TracingCategory& c = k_categories[i];
815 if (isCategorySupported(c)) {
816 printf(" %10s - %s\n", c.name, c.longname);
817 }
818 }
819}
820
821// Print the command usage help to stderr.
822static void showHelp(const char *cmd)
823{
824 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
825 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700826 " -a appname enable app-level tracing for a comma "
827 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800828 " -b N use a trace buffer size of N KB\n"
829 " -c trace into a circular buffer\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700830 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800831 " -n ignore signals\n"
832 " -s N sleep for N seconds before tracing [default 0]\n"
833 " -t N trace for N seconds [defualt 5]\n"
834 " -z compress the trace dump\n"
835 " --async_start start circular trace and return immediatly\n"
836 " --async_dump dump the current contents of circular trace buffer\n"
837 " --async_stop stop tracing and dump the current contents of circular\n"
838 " trace buffer\n"
Jamie Gennis92573f12012-12-07 16:29:03 -0800839 " --list_categories\n"
840 " list the available tracing categories\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800841 );
842}
843
844int main(int argc, char **argv)
845{
846 bool async = false;
847 bool traceStart = true;
848 bool traceStop = true;
849 bool traceDump = true;
850
851 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
852 showHelp(argv[0]);
853 exit(0);
854 }
855
856 for (;;) {
857 int ret;
858 int option_index = 0;
859 static struct option long_options[] = {
860 {"async_start", no_argument, 0, 0 },
861 {"async_stop", no_argument, 0, 0 },
862 {"async_dump", no_argument, 0, 0 },
863 {"list_categories", no_argument, 0, 0 },
864 { 0, 0, 0, 0 }
865 };
866
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700867 ret = getopt_long(argc, argv, "a:b:ck:ns:t:z",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800868 long_options, &option_index);
869
870 if (ret < 0) {
871 for (int i = optind; i < argc; i++) {
872 if (!setCategoryEnable(argv[i], true)) {
873 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
874 exit(1);
875 }
876 }
877 break;
878 }
879
880 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700881 case 'a':
882 g_debugAppCmdLine = optarg;
883 break;
884
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800885 case 'b':
886 g_traceBufferSizeKB = atoi(optarg);
887 break;
888
889 case 'c':
890 g_traceOverwrite = true;
891 break;
892
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700893 case 'k':
894 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700895 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700896
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800897 case 'n':
898 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700899 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800900
901 case 's':
902 g_initialSleepSecs = atoi(optarg);
903 break;
904
905 case 't':
906 g_traceDurationSeconds = atoi(optarg);
907 break;
908
909 case 'z':
910 g_compress = true;
911 break;
912
913 case 0:
914 if (!strcmp(long_options[option_index].name, "async_start")) {
915 async = true;
916 traceStop = false;
917 traceDump = false;
918 g_traceOverwrite = true;
919 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
920 async = true;
John Reck2c237ee2015-05-15 10:00:34 -0700921 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800922 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
923 async = true;
924 traceStart = false;
925 traceStop = false;
926 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
927 listSupportedCategories();
928 exit(0);
929 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700930 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800931
932 default:
933 fprintf(stderr, "\n");
934 showHelp(argv[0]);
935 exit(-1);
936 break;
937 }
938 }
939
940 registerSigHandler();
941
942 if (g_initialSleepSecs > 0) {
943 sleep(g_initialSleepSecs);
944 }
945
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700946 bool ok = true;
947 ok &= setUpTrace();
948 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800949
950 if (ok && traceStart) {
951 printf("capturing trace...");
952 fflush(stdout);
953
954 // We clear the trace after starting it because tracing gets enabled for
955 // each CPU individually in the kernel. Having the beginning of the trace
956 // contain entries from only one CPU can cause "begin" entries without a
957 // matching "end" entry to show up if a task gets migrated from one CPU to
958 // another.
959 ok = clearTrace();
960
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200961 writeClockSyncMarker();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800962 if (ok && !async) {
963 // Sleep to allow the trace to be captured.
964 struct timespec timeLeft;
965 timeLeft.tv_sec = g_traceDurationSeconds;
966 timeLeft.tv_nsec = 0;
967 do {
968 if (g_traceAborted) {
969 break;
970 }
971 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
972 }
973 }
974
975 // Stop the trace and restore the default settings.
976 if (traceStop)
977 stopTrace();
978
979 if (ok && traceDump) {
980 if (!g_traceAborted) {
981 printf(" done\nTRACE:\n");
982 fflush(stdout);
983 dumpTrace();
984 } else {
985 printf("\ntrace aborted.\n");
986 fflush(stdout);
987 }
988 clearTrace();
989 } else if (!ok) {
990 fprintf(stderr, "unable to start tracing\n");
991 }
992
993 // Reset the trace buffer size to 1.
994 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700995 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800996
997 return g_traceAborted ? 1 : 0;
998}