blob: e01aa3f1ec16801e6640732cce5d470ad29e5777 [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
John Reck40b26b42016-03-30 09:44:36 -070017 #define LOG_TAG "atrace"
18
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080019#include <errno.h>
20#include <fcntl.h>
21#include <getopt.h>
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070022#include <inttypes.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080023#include <signal.h>
24#include <stdarg.h>
25#include <stdbool.h>
26#include <stdio.h>
27#include <stdlib.h>
Elliott Hughes3da5d232015-01-25 08:35:20 -080028#include <string.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080029#include <sys/sendfile.h>
30#include <time.h>
Martijn Coenend9535872015-11-26 10:00:55 +010031#include <unistd.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080032#include <zlib.h>
33
34#include <binder/IBinder.h>
35#include <binder/IServiceManager.h>
36#include <binder/Parcel.h>
37
38#include <cutils/properties.h>
39
40#include <utils/String8.h>
John Reck469a1942015-03-26 15:31:35 -070041#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +090042#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080043#include <utils/Trace.h>
44
45using namespace android;
46
47#define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0])))
48
sergeyv4144eff2016-04-28 11:40:04 -070049#define MAX_SYS_FILES 10
50#define MAX_PACKAGES 16
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080051
52const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
sergeyv4144eff2016-04-28 11:40:04 -070053
54const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
55const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080056
57typedef enum { OPT, REQ } requiredness ;
58
59struct TracingCategory {
60 // The name identifying the category.
61 const char* name;
62
63 // A longer description of the category.
64 const char* longname;
65
66 // The userland tracing tags that the category enables.
67 uint64_t tags;
68
69 // The fname==NULL terminated list of /sys/ files that the category
70 // enables.
71 struct {
72 // Whether the file must be writable in order to enable the tracing
73 // category.
74 requiredness required;
75
76 // The path to the enable file.
77 const char* path;
78 } sysfiles[MAX_SYS_FILES];
79};
80
81/* Tracing categories */
82static const TracingCategory k_categories[] = {
Jamie Gennisb2a89e32013-03-11 19:37:53 -070083 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, { } },
84 { "input", "Input", ATRACE_TAG_INPUT, { } },
85 { "view", "View System", ATRACE_TAG_VIEW, { } },
86 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
87 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
88 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -050089 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070090 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
91 { "video", "Video", ATRACE_TAG_VIDEO, { } },
92 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
93 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -070094 { "app", "Application", ATRACE_TAG_APP, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -070095 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -070096 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -070097 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -070098 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -070099 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 14:36:20 -0700100 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-07-01 01:46:25 +0900101 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Greg Hackmannbbd7d992014-12-01 14:43:34 -0800102 { "database", "Database", ATRACE_TAG_DATABASE, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700103 { "sched", "CPU Scheduling", 0, {
104 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_switch/enable" },
105 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_wakeup/enable" },
Riley Andrews5672bb72015-11-19 13:31:17 -0800106 { OPT, "/sys/kernel/debug/tracing/events/sched/sched_blocked_reason/enable" },
Ruchi Kandoicfe500d2015-11-23 13:47:20 -0800107 { OPT, "/sys/kernel/debug/tracing/events/sched/sched_cpu_hotplug/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800108 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700109 { "irq", "IRQ Events", 0, {
110 { REQ, "/sys/kernel/debug/tracing/events/irq/enable" },
Riley Andrews412e4f62015-11-02 21:01:34 -0800111 { OPT, "/sys/kernel/debug/tracing/events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700112 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700113 { "freq", "CPU Frequency", 0, {
114 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_frequency/enable" },
115 { OPT, "/sys/kernel/debug/tracing/events/power/clock_set_rate/enable" },
Ruchi Kandoiffcc7112015-11-19 18:32:00 -0800116 { OPT, "/sys/kernel/debug/tracing/events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800117 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700118 { "membus", "Memory Bus Utilization", 0, {
119 { REQ, "/sys/kernel/debug/tracing/events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800120 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700121 { "idle", "CPU Idle", 0, {
122 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800123 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700124 { "disk", "Disk I/O", 0, {
Greg Hackmanne80d32c2014-11-20 12:59:44 -0800125 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_enter/enable" },
126 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_exit/enable" },
127 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_begin/enable" },
128 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_end/enable" },
129 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_begin/enable" },
130 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_end/enable" },
131 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable" },
132 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable" },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700133 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" },
134 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800135 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700136 { "mmc", "eMMC commands", 0, {
137 { REQ, "/sys/kernel/debug/tracing/events/mmc/enable" },
138 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700139 { "load", "CPU Load", 0, {
140 { REQ, "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800141 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700142 { "sync", "Synchronization", 0, {
143 { REQ, "/sys/kernel/debug/tracing/events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800144 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700145 { "workq", "Kernel Workqueues", 0, {
146 { REQ, "/sys/kernel/debug/tracing/events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800147 } },
Colin Cross580407f2014-08-18 15:22:13 -0700148 { "memreclaim", "Kernel Memory Reclaim", 0, {
149 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
150 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
151 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_wake/enable" },
152 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_sleep/enable" },
153 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800154 { "regulators", "Voltage and Current Regulators", 0, {
155 { REQ, "/sys/kernel/debug/tracing/events/regulator/enable" },
156 } },
Scott Bauerae473362015-06-08 16:32:36 -0700157 { "binder_driver", "Binder Kernel driver", 0, {
158 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction/enable" },
159 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction_received/enable" },
160 } },
161 { "binder_lock", "Binder global lock trace", 0, {
162 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_lock/enable" },
163 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_locked/enable" },
164 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_unlock/enable" },
165 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200166 { "pagecache", "Page cache", 0, {
167 { REQ, "/sys/kernel/debug/tracing/events/filemap/enable" },
168 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800169};
170
171/* Command line options */
172static int g_traceDurationSeconds = 5;
173static bool g_traceOverwrite = false;
174static int g_traceBufferSizeKB = 2048;
175static bool g_compress = false;
176static bool g_nohup = false;
177static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900178static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700179static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700180static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700181static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800182
183/* Global state */
184static bool g_traceAborted = false;
185static bool g_categoryEnables[NELEM(k_categories)] = {};
186
187/* Sys file paths */
188static const char* k_traceClockPath =
189 "/sys/kernel/debug/tracing/trace_clock";
190
191static const char* k_traceBufferSizePath =
192 "/sys/kernel/debug/tracing/buffer_size_kb";
193
194static const char* k_tracingOverwriteEnablePath =
195 "/sys/kernel/debug/tracing/options/overwrite";
196
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700197static const char* k_currentTracerPath =
198 "/sys/kernel/debug/tracing/current_tracer";
199
200static const char* k_printTgidPath =
201 "/sys/kernel/debug/tracing/options/print-tgid";
202
203static const char* k_funcgraphAbsTimePath =
204 "/sys/kernel/debug/tracing/options/funcgraph-abstime";
205
206static const char* k_funcgraphCpuPath =
207 "/sys/kernel/debug/tracing/options/funcgraph-cpu";
208
209static const char* k_funcgraphProcPath =
210 "/sys/kernel/debug/tracing/options/funcgraph-proc";
211
212static const char* k_funcgraphFlatPath =
213 "/sys/kernel/debug/tracing/options/funcgraph-flat";
214
215static const char* k_funcgraphDurationPath =
216 "/sys/kernel/debug/tracing/options/funcgraph-duration";
217
218static const char* k_ftraceFilterPath =
219 "/sys/kernel/debug/tracing/set_ftrace_filter";
220
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800221static const char* k_tracingOnPath =
222 "/sys/kernel/debug/tracing/tracing_on";
223
224static const char* k_tracePath =
225 "/sys/kernel/debug/tracing/trace";
226
Martijn Coenend9535872015-11-26 10:00:55 +0100227static const char* k_traceStreamPath =
228 "/sys/kernel/debug/tracing/trace_pipe";
229
John Reck469a1942015-03-26 15:31:35 -0700230static const char* k_traceMarkerPath =
231 "/sys/kernel/debug/tracing/trace_marker";
232
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800233// Check whether a file exists.
234static bool fileExists(const char* filename) {
235 return access(filename, F_OK) != -1;
236}
237
238// Check whether a file is writable.
239static bool fileIsWritable(const char* filename) {
240 return access(filename, W_OK) != -1;
241}
242
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700243// Truncate a file.
244static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800245{
Jamie Gennis43122e72013-03-21 14:06:31 -0700246 // This uses creat rather than truncate because some of the debug kernel
247 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
248 // calls to truncate, but they are cleared by calls to creat.
249 int traceFD = creat(path, 0);
250 if (traceFD == -1) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700251 fprintf(stderr, "error truncating %s: %s (%d)\n", path,
Jamie Gennis43122e72013-03-21 14:06:31 -0700252 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700253 return false;
254 }
255
Jamie Gennis43122e72013-03-21 14:06:31 -0700256 close(traceFD);
257
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700258 return true;
259}
260
261static bool _writeStr(const char* filename, const char* str, int flags)
262{
263 int fd = open(filename, flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800264 if (fd == -1) {
265 fprintf(stderr, "error opening %s: %s (%d)\n", filename,
266 strerror(errno), errno);
267 return false;
268 }
269
270 bool ok = true;
271 ssize_t len = strlen(str);
272 if (write(fd, str, len) != len) {
273 fprintf(stderr, "error writing to %s: %s (%d)\n", filename,
274 strerror(errno), errno);
275 ok = false;
276 }
277
278 close(fd);
279
280 return ok;
281}
282
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700283// Write a string to a file, returning true if the write was successful.
284static bool writeStr(const char* filename, const char* str)
285{
286 return _writeStr(filename, str, O_WRONLY);
287}
288
289// Append a string to a file, returning true if the write was successful.
290static bool appendStr(const char* filename, const char* str)
291{
292 return _writeStr(filename, str, O_APPEND|O_WRONLY);
293}
294
John Reck469a1942015-03-26 15:31:35 -0700295static void writeClockSyncMarker()
296{
297 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200298 int len = 0;
299 int fd = open(k_traceMarkerPath, O_WRONLY);
300 if (fd == -1) {
301 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
302 strerror(errno), errno);
303 return;
304 }
John Reck469a1942015-03-26 15:31:35 -0700305 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200306
307 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
308 if (write(fd, buffer, len) != len) {
309 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
310 }
311
312 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
313 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
314 if (write(fd, buffer, len) != len) {
315 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
316 }
317
318 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700319}
320
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800321// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
322// file.
323static bool setKernelOptionEnable(const char* filename, bool enable)
324{
325 return writeStr(filename, enable ? "1" : "0");
326}
327
328// Check whether the category is supported on the device with the current
329// rootness. A category is supported only if all its required /sys/ files are
330// writable and if enabling the category will enable one or more tracing tags
331// or /sys/ files.
332static bool isCategorySupported(const TracingCategory& category)
333{
334 bool ok = category.tags != 0;
335 for (int i = 0; i < MAX_SYS_FILES; i++) {
336 const char* path = category.sysfiles[i].path;
337 bool req = category.sysfiles[i].required == REQ;
338 if (path != NULL) {
339 if (req) {
340 if (!fileIsWritable(path)) {
341 return false;
342 } else {
343 ok = true;
344 }
345 } else {
346 ok |= fileIsWritable(path);
347 }
348 }
349 }
350 return ok;
351}
352
353// Check whether the category would be supported on the device if the user
354// were root. This function assumes that root is able to write to any file
355// that exists. It performs the same logic as isCategorySupported, but it
356// uses file existance rather than writability in the /sys/ file checks.
357static bool isCategorySupportedForRoot(const TracingCategory& category)
358{
359 bool ok = category.tags != 0;
360 for (int i = 0; i < MAX_SYS_FILES; i++) {
361 const char* path = category.sysfiles[i].path;
362 bool req = category.sysfiles[i].required == REQ;
363 if (path != NULL) {
364 if (req) {
365 if (!fileExists(path)) {
366 return false;
367 } else {
368 ok = true;
369 }
370 } else {
371 ok |= fileExists(path);
372 }
373 }
374 }
375 return ok;
376}
377
378// Enable or disable overwriting of the kernel trace buffers. Disabling this
379// will cause tracing to stop once the trace buffers have filled up.
380static bool setTraceOverwriteEnable(bool enable)
381{
382 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
383}
384
385// Enable or disable kernel tracing.
386static bool setTracingEnabled(bool enable)
387{
388 return setKernelOptionEnable(k_tracingOnPath, enable);
389}
390
391// Clear the contents of the kernel trace.
392static bool clearTrace()
393{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700394 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800395}
396
397// Set the size of the kernel's trace buffer in kilobytes.
398static bool setTraceBufferSizeKB(int size)
399{
400 char str[32] = "1";
401 int len;
402 if (size < 1) {
403 size = 1;
404 }
405 snprintf(str, 32, "%d", size);
406 return writeStr(k_traceBufferSizePath, str);
407}
408
Colin Crossb1ce49b2014-08-20 14:28:47 -0700409// Read the trace_clock sysfs file and return true if it matches the requested
410// value. The trace_clock file format is:
411// local [global] counter uptime perf
412static bool isTraceClock(const char *mode)
413{
414 int fd = open(k_traceClockPath, O_RDONLY);
415 if (fd == -1) {
416 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceClockPath,
417 strerror(errno), errno);
418 return false;
419 }
420
421 char buf[4097];
422 ssize_t n = read(fd, buf, 4096);
423 close(fd);
424 if (n == -1) {
425 fprintf(stderr, "error reading %s: %s (%d)\n", k_traceClockPath,
426 strerror(errno), errno);
427 return false;
428 }
429 buf[n] = '\0';
430
431 char *start = strchr(buf, '[');
432 if (start == NULL) {
433 return false;
434 }
435 start++;
436
437 char *end = strchr(start, ']');
438 if (end == NULL) {
439 return false;
440 }
441 *end = '\0';
442
443 return strcmp(mode, start) == 0;
444}
445
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800446// Enable or disable the kernel's use of the global clock. Disabling the global
447// clock will result in the kernel using a per-CPU local clock.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700448// Any write to the trace_clock sysfs file will reset the buffer, so only
449// update it if the requested value is not the current value.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800450static bool setGlobalClockEnable(bool enable)
451{
Colin Crossb1ce49b2014-08-20 14:28:47 -0700452 const char *clock = enable ? "global" : "local";
453
454 if (isTraceClock(clock)) {
455 return true;
456 }
457
458 return writeStr(k_traceClockPath, clock);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800459}
460
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700461static bool setPrintTgidEnableIfPresent(bool enable)
462{
463 if (fileExists(k_printTgidPath)) {
464 return setKernelOptionEnable(k_printTgidPath, enable);
465 }
466 return true;
467}
468
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800469// Poke all the binder-enabled processes in the system to get them to re-read
470// their system properties.
471static bool pokeBinderServices()
472{
473 sp<IServiceManager> sm = defaultServiceManager();
474 Vector<String16> services = sm->listServices();
475 for (size_t i = 0; i < services.size(); i++) {
476 sp<IBinder> obj = sm->checkService(services[i]);
477 if (obj != NULL) {
478 Parcel data;
479 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
480 NULL, 0) != OK) {
481 if (false) {
482 // XXX: For some reason this fails on tablets trying to
483 // poke the "phone" service. It's not clear whether some
484 // are expected to fail.
485 String8 svc(services[i]);
486 fprintf(stderr, "error poking binder service %s\n",
487 svc.string());
488 return false;
489 }
490 }
491 }
492 }
493 return true;
494}
495
496// Set the trace tags that userland tracing uses, and poke the running
497// processes to pick up the new value.
498static bool setTagsProperty(uint64_t tags)
499{
sergeyv4144eff2016-04-28 11:40:04 -0700500 char buf[PROPERTY_VALUE_MAX];
501 snprintf(buf, sizeof(buf), "%#" PRIx64, tags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800502 if (property_set(k_traceTagsProperty, buf) < 0) {
503 fprintf(stderr, "error setting trace tags system property\n");
504 return false;
505 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700506 return true;
507}
508
sergeyv4144eff2016-04-28 11:40:04 -0700509static void clearAppProperties()
510{
511 char buf[PROPERTY_KEY_MAX];
512 for (int i = 0; i < MAX_PACKAGES; i++) {
513 snprintf(buf, sizeof(buf), k_traceAppsPropertyTemplate, i);
514 if (property_set(buf, "") < 0) {
515 fprintf(stderr, "failed to clear system property: %s\n", buf);
516 }
517 }
518 if (property_set(k_traceAppsNumberProperty, "") < 0) {
519 fprintf(stderr, "failed to clear system property: %s",
520 k_traceAppsNumberProperty);
521 }
522}
523
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700524// Set the system property that indicates which apps should perform
525// application-level tracing.
526static bool setAppCmdlineProperty(const char* cmdline)
527{
sergeyv4144eff2016-04-28 11:40:04 -0700528 char buf[PROPERTY_KEY_MAX];
529 int i = 0;
530 const char* start = cmdline;
531 while (start != NULL) {
532 if (i == MAX_PACKAGES) {
533 fprintf(stderr, "error: only 16 packages could be traced at once\n");
534 clearAppProperties();
535 return false;
536 }
537 char* end = strchr(start, ',');
538 if (end != NULL) {
539 *end = '\0';
540 end++;
541 }
542 snprintf(buf, sizeof(buf), k_traceAppsPropertyTemplate, i);
543 if (property_set(buf, start) < 0) {
544 fprintf(stderr, "error setting trace app %d property to %s\n", i, buf);
545 clearAppProperties();
546 return false;
547 }
548 start = end;
549 i++;
550 }
551
552 snprintf(buf, sizeof(buf), "%d", i);
553 if (property_set(k_traceAppsNumberProperty, buf) < 0) {
554 fprintf(stderr, "error setting trace app number property to %s\n", buf);
555 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700556 return false;
557 }
558 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800559}
560
561// Disable all /sys/ enable files.
562static bool disableKernelTraceEvents() {
563 bool ok = true;
564 for (int i = 0; i < NELEM(k_categories); i++) {
565 const TracingCategory &c = k_categories[i];
566 for (int j = 0; j < MAX_SYS_FILES; j++) {
567 const char* path = c.sysfiles[j].path;
568 if (path != NULL && fileIsWritable(path)) {
569 ok &= setKernelOptionEnable(path, false);
570 }
571 }
572 }
573 return ok;
574}
575
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700576// Verify that the comma separated list of functions are being traced by the
577// kernel.
578static bool verifyKernelTraceFuncs(const char* funcs)
579{
580 int fd = open(k_ftraceFilterPath, O_RDONLY);
581 if (fd == -1) {
582 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
583 strerror(errno), errno);
584 return false;
585 }
586
587 char buf[4097];
588 ssize_t n = read(fd, buf, 4096);
589 close(fd);
590 if (n == -1) {
591 fprintf(stderr, "error reading %s: %s (%d)\n", k_ftraceFilterPath,
592 strerror(errno), errno);
593 return false;
594 }
595
596 buf[n] = '\0';
597 String8 funcList = String8::format("\n%s", buf);
598
599 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100600 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700601 bool ok = true;
602 char* myFuncs = strdup(funcs);
603 char* func = strtok(myFuncs, ",");
604 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100605 if (!strchr(func, '*')) {
606 String8 fancyFunc = String8::format("\n%s\n", func);
607 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
608 if (!found || func[0] == '\0') {
609 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
610 "to trace.\n", func);
611 ok = false;
612 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700613 }
614 func = strtok(NULL, ",");
615 }
616 free(myFuncs);
617
618 return ok;
619}
620
621// Set the comma separated list of functions that the kernel is to trace.
622static bool setKernelTraceFuncs(const char* funcs)
623{
624 bool ok = true;
625
626 if (funcs == NULL || funcs[0] == '\0') {
627 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700628 if (fileIsWritable(k_currentTracerPath)) {
629 ok &= writeStr(k_currentTracerPath, "nop");
630 }
631 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700632 ok &= truncateFile(k_ftraceFilterPath);
633 }
634 } else {
635 // Enable kernel function tracing.
636 ok &= writeStr(k_currentTracerPath, "function_graph");
637 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
638 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
639 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
640 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
641
642 // Set the requested filter functions.
643 ok &= truncateFile(k_ftraceFilterPath);
644 char* myFuncs = strdup(funcs);
645 char* func = strtok(myFuncs, ",");
646 while (func) {
647 ok &= appendStr(k_ftraceFilterPath, func);
648 func = strtok(NULL, ",");
649 }
650 free(myFuncs);
651
652 // Verify that the set functions are being traced.
653 if (ok) {
654 ok &= verifyKernelTraceFuncs(funcs);
655 }
656 }
657
658 return ok;
659}
660
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900661static bool setCategoryEnable(const char* name, bool enable)
662{
663 for (int i = 0; i < NELEM(k_categories); i++) {
664 const TracingCategory& c = k_categories[i];
665 if (strcmp(name, c.name) == 0) {
666 if (isCategorySupported(c)) {
667 g_categoryEnables[i] = enable;
668 return true;
669 } else {
670 if (isCategorySupportedForRoot(c)) {
671 fprintf(stderr, "error: category \"%s\" requires root "
672 "privileges.\n", name);
673 } else {
674 fprintf(stderr, "error: category \"%s\" is not supported "
675 "on this device.\n", name);
676 }
677 return false;
678 }
679 }
680 }
681 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
682 return false;
683}
684
685static bool setCategoriesEnableFromFile(const char* categories_file)
686{
687 if (!categories_file) {
688 return true;
689 }
690 Tokenizer* tokenizer = NULL;
691 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
692 return false;
693 }
694 bool ok = true;
695 while (!tokenizer->isEol()) {
696 String8 token = tokenizer->nextToken(" ");
697 if (token.isEmpty()) {
698 tokenizer->skipDelimiters(" ");
699 continue;
700 }
701 ok &= setCategoryEnable(token.string(), true);
702 }
703 delete tokenizer;
704 return ok;
705}
706
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700707// Set all the kernel tracing settings to the desired state for this trace
708// capture.
709static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800710{
711 bool ok = true;
712
713 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900714 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800715 ok &= setTraceOverwriteEnable(g_traceOverwrite);
716 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
717 ok &= setGlobalClockEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700718 ok &= setPrintTgidEnableIfPresent(true);
719 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800720
721 // Set up the tags property.
722 uint64_t tags = 0;
723 for (int i = 0; i < NELEM(k_categories); i++) {
724 if (g_categoryEnables[i]) {
725 const TracingCategory &c = k_categories[i];
726 tags |= c.tags;
727 }
728 }
729 ok &= setTagsProperty(tags);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700730 ok &= setAppCmdlineProperty(g_debugAppCmdLine);
731 ok &= pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800732
733 // Disable all the sysfs enables. This is done as a separate loop from
734 // the enables to allow the same enable to exist in multiple categories.
735 ok &= disableKernelTraceEvents();
736
737 // Enable all the sysfs enables that are in an enabled category.
738 for (int i = 0; i < NELEM(k_categories); i++) {
739 if (g_categoryEnables[i]) {
740 const TracingCategory &c = k_categories[i];
741 for (int j = 0; j < MAX_SYS_FILES; j++) {
742 const char* path = c.sysfiles[j].path;
743 bool required = c.sysfiles[j].required == REQ;
744 if (path != NULL) {
745 if (fileIsWritable(path)) {
746 ok &= setKernelOptionEnable(path, true);
747 } else if (required) {
748 fprintf(stderr, "error writing file %s\n", path);
749 ok = false;
750 }
751 }
752 }
753 }
754 }
755
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800756 return ok;
757}
758
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700759// Reset all the kernel tracing settings to their default state.
760static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800761{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800762 // Disable all tracing that we're able to.
763 disableKernelTraceEvents();
764
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700765 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800766 setTagsProperty(0);
sergeyv4144eff2016-04-28 11:40:04 -0700767 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700768 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800769
770 // Set the options back to their defaults.
771 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700772 setTraceBufferSizeKB(1);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800773 setGlobalClockEnable(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700774 setPrintTgidEnableIfPresent(false);
775 setKernelTraceFuncs(NULL);
776}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800777
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700778
779// Enable tracing in the kernel.
780static bool startTrace()
781{
782 return setTracingEnabled(true);
783}
784
785// Disable tracing in the kernel.
786static void stopTrace()
787{
788 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800789}
790
Martijn Coenend9535872015-11-26 10:00:55 +0100791// Read data from the tracing pipe and forward to stdout
792static void streamTrace()
793{
794 char trace_data[4096];
795 int traceFD = open(k_traceStreamPath, O_RDWR);
796 if (traceFD == -1) {
797 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
798 strerror(errno), errno);
799 return;
800 }
801 while (!g_traceAborted) {
802 ssize_t bytes_read = read(traceFD, trace_data, 4096);
803 if (bytes_read > 0) {
804 write(STDOUT_FILENO, trace_data, bytes_read);
805 fflush(stdout);
806 } else {
807 if (!g_traceAborted) {
808 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
809 bytes_read, errno, strerror(errno));
810 }
811 break;
812 }
813 }
814}
815
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800816// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700817static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800818{
John Reck6c8ac922016-03-28 11:25:30 -0700819 ALOGI("Dumping trace");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800820 int traceFD = open(k_tracePath, O_RDWR);
821 if (traceFD == -1) {
822 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
823 strerror(errno), errno);
824 return;
825 }
826
827 if (g_compress) {
828 z_stream zs;
829 uint8_t *in, *out;
830 int result, flush;
831
Elliott Hughes3da5d232015-01-25 08:35:20 -0800832 memset(&zs, 0, sizeof(zs));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800833 result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
834 if (result != Z_OK) {
835 fprintf(stderr, "error initializing zlib: %d\n", result);
836 close(traceFD);
837 return;
838 }
839
840 const size_t bufSize = 64*1024;
841 in = (uint8_t*)malloc(bufSize);
842 out = (uint8_t*)malloc(bufSize);
843 flush = Z_NO_FLUSH;
844
845 zs.next_out = out;
846 zs.avail_out = bufSize;
847
848 do {
849
850 if (zs.avail_in == 0) {
851 // More input is needed.
852 result = read(traceFD, in, bufSize);
853 if (result < 0) {
854 fprintf(stderr, "error reading trace: %s (%d)\n",
855 strerror(errno), errno);
856 result = Z_STREAM_END;
857 break;
858 } else if (result == 0) {
859 flush = Z_FINISH;
860 } else {
861 zs.next_in = in;
862 zs.avail_in = result;
863 }
864 }
865
866 if (zs.avail_out == 0) {
867 // Need to write the output.
John Reck40b26b42016-03-30 09:44:36 -0700868 result = write(outFd, out, bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800869 if ((size_t)result < bufSize) {
870 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
871 strerror(errno), errno);
872 result = Z_STREAM_END; // skip deflate error message
873 zs.avail_out = bufSize; // skip the final write
874 break;
875 }
876 zs.next_out = out;
877 zs.avail_out = bufSize;
878 }
879
880 } while ((result = deflate(&zs, flush)) == Z_OK);
881
882 if (result != Z_STREAM_END) {
883 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
884 }
885
886 if (zs.avail_out < bufSize) {
887 size_t bytes = bufSize - zs.avail_out;
John Reck40b26b42016-03-30 09:44:36 -0700888 result = write(outFd, out, bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800889 if ((size_t)result < bytes) {
890 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
891 strerror(errno), errno);
892 }
893 }
894
895 result = deflateEnd(&zs);
896 if (result != Z_OK) {
897 fprintf(stderr, "error cleaning up zlib: %d\n", result);
898 }
899
900 free(in);
901 free(out);
902 } else {
903 ssize_t sent = 0;
John Reck40b26b42016-03-30 09:44:36 -0700904 while ((sent = sendfile(outFd, traceFD, NULL, 64*1024*1024)) > 0);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800905 if (sent == -1) {
906 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
907 errno);
908 }
909 }
910
911 close(traceFD);
912}
913
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700914static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800915{
916 if (!g_nohup) {
917 g_traceAborted = true;
918 }
919}
920
921static void registerSigHandler()
922{
923 struct sigaction sa;
924 sigemptyset(&sa.sa_mask);
925 sa.sa_flags = 0;
926 sa.sa_handler = handleSignal;
927 sigaction(SIGHUP, &sa, NULL);
928 sigaction(SIGINT, &sa, NULL);
929 sigaction(SIGQUIT, &sa, NULL);
930 sigaction(SIGTERM, &sa, NULL);
931}
932
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800933static void listSupportedCategories()
934{
935 for (int i = 0; i < NELEM(k_categories); i++) {
936 const TracingCategory& c = k_categories[i];
937 if (isCategorySupported(c)) {
938 printf(" %10s - %s\n", c.name, c.longname);
939 }
940 }
941}
942
943// Print the command usage help to stderr.
944static void showHelp(const char *cmd)
945{
946 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
947 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700948 " -a appname enable app-level tracing for a comma "
949 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800950 " -b N use a trace buffer size of N KB\n"
951 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900952 " -f filename use the categories written in a file as space-separated\n"
953 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700954 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800955 " -n ignore signals\n"
956 " -s N sleep for N seconds before tracing [default 0]\n"
957 " -t N trace for N seconds [defualt 5]\n"
958 " -z compress the trace dump\n"
959 " --async_start start circular trace and return immediatly\n"
960 " --async_dump dump the current contents of circular trace buffer\n"
961 " --async_stop stop tracing and dump the current contents of circular\n"
962 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +0100963 " --stream stream trace to stdout as it enters the trace buffer\n"
964 " Note: this can take significant CPU time, and is best\n"
965 " used for measuring things that are not affected by\n"
966 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -0800967 " --list_categories\n"
968 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -0700969 " -o filename write the trace to the specified file instead\n"
970 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800971 );
972}
973
974int main(int argc, char **argv)
975{
976 bool async = false;
977 bool traceStart = true;
978 bool traceStop = true;
979 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +0100980 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800981
982 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
983 showHelp(argv[0]);
984 exit(0);
985 }
986
987 for (;;) {
988 int ret;
989 int option_index = 0;
990 static struct option long_options[] = {
991 {"async_start", no_argument, 0, 0 },
992 {"async_stop", no_argument, 0, 0 },
993 {"async_dump", no_argument, 0, 0 },
994 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +0100995 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800996 { 0, 0, 0, 0 }
997 };
998
John Reck40b26b42016-03-30 09:44:36 -0700999 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001000 long_options, &option_index);
1001
1002 if (ret < 0) {
1003 for (int i = optind; i < argc; i++) {
1004 if (!setCategoryEnable(argv[i], true)) {
1005 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1006 exit(1);
1007 }
1008 }
1009 break;
1010 }
1011
1012 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001013 case 'a':
1014 g_debugAppCmdLine = optarg;
1015 break;
1016
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001017 case 'b':
1018 g_traceBufferSizeKB = atoi(optarg);
1019 break;
1020
1021 case 'c':
1022 g_traceOverwrite = true;
1023 break;
1024
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001025 case 'f':
1026 g_categoriesFile = optarg;
1027 break;
1028
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001029 case 'k':
1030 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001031 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001032
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001033 case 'n':
1034 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001035 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001036
1037 case 's':
1038 g_initialSleepSecs = atoi(optarg);
1039 break;
1040
1041 case 't':
1042 g_traceDurationSeconds = atoi(optarg);
1043 break;
1044
1045 case 'z':
1046 g_compress = true;
1047 break;
1048
John Reck40b26b42016-03-30 09:44:36 -07001049 case 'o':
1050 g_outputFile = optarg;
1051 break;
1052
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001053 case 0:
1054 if (!strcmp(long_options[option_index].name, "async_start")) {
1055 async = true;
1056 traceStop = false;
1057 traceDump = false;
1058 g_traceOverwrite = true;
1059 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1060 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001061 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001062 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1063 async = true;
1064 traceStart = false;
1065 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001066 } else if (!strcmp(long_options[option_index].name, "stream")) {
1067 traceStream = true;
1068 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001069 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1070 listSupportedCategories();
1071 exit(0);
1072 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001073 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001074
1075 default:
1076 fprintf(stderr, "\n");
1077 showHelp(argv[0]);
1078 exit(-1);
1079 break;
1080 }
1081 }
1082
1083 registerSigHandler();
1084
1085 if (g_initialSleepSecs > 0) {
1086 sleep(g_initialSleepSecs);
1087 }
1088
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001089 bool ok = true;
1090 ok &= setUpTrace();
1091 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001092
1093 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001094 if (!traceStream) {
1095 printf("capturing trace...");
1096 fflush(stdout);
1097 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001098
1099 // We clear the trace after starting it because tracing gets enabled for
1100 // each CPU individually in the kernel. Having the beginning of the trace
1101 // contain entries from only one CPU can cause "begin" entries without a
1102 // matching "end" entry to show up if a task gets migrated from one CPU to
1103 // another.
1104 ok = clearTrace();
1105
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001106 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001107 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001108 // Sleep to allow the trace to be captured.
1109 struct timespec timeLeft;
1110 timeLeft.tv_sec = g_traceDurationSeconds;
1111 timeLeft.tv_nsec = 0;
1112 do {
1113 if (g_traceAborted) {
1114 break;
1115 }
1116 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1117 }
Martijn Coenend9535872015-11-26 10:00:55 +01001118
1119 if (traceStream) {
1120 streamTrace();
1121 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001122 }
1123
1124 // Stop the trace and restore the default settings.
1125 if (traceStop)
1126 stopTrace();
1127
1128 if (ok && traceDump) {
1129 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001130 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001131 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001132 int outFd = STDOUT_FILENO;
1133 if (g_outputFile) {
1134 outFd = open(g_outputFile, O_WRONLY | O_CREAT);
1135 }
1136 if (outFd == -1) {
1137 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1138 } else {
1139 dprintf(outFd, "TRACE:\n");
1140 dumpTrace(outFd);
1141 if (g_outputFile) {
1142 close(outFd);
1143 }
1144 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001145 } else {
1146 printf("\ntrace aborted.\n");
1147 fflush(stdout);
1148 }
1149 clearTrace();
1150 } else if (!ok) {
1151 fprintf(stderr, "unable to start tracing\n");
1152 }
1153
1154 // Reset the trace buffer size to 1.
1155 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001156 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001157
1158 return g_traceAborted ? 1 : 0;
1159}