blob: 61b8f6b6215de595b4537a458bf3a60015768c06 [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
Mohamad Ayyash26dbcbe2014-04-08 15:24:11 -070049enum { MAX_SYS_FILES = 10 };
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080050
51const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
Jamie Gennisf7f29c82013-03-27 15:50:58 -070052const char* k_traceAppCmdlineProperty = "debug.atrace.app_cmdlines";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080053
54typedef enum { OPT, REQ } requiredness ;
55
56struct TracingCategory {
57 // The name identifying the category.
58 const char* name;
59
60 // A longer description of the category.
61 const char* longname;
62
63 // The userland tracing tags that the category enables.
64 uint64_t tags;
65
66 // The fname==NULL terminated list of /sys/ files that the category
67 // enables.
68 struct {
69 // Whether the file must be writable in order to enable the tracing
70 // category.
71 requiredness required;
72
73 // The path to the enable file.
74 const char* path;
75 } sysfiles[MAX_SYS_FILES];
76};
77
78/* Tracing categories */
79static const TracingCategory k_categories[] = {
Jamie Gennisb2a89e32013-03-11 19:37:53 -070080 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, { } },
81 { "input", "Input", ATRACE_TAG_INPUT, { } },
82 { "view", "View System", ATRACE_TAG_VIEW, { } },
83 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
84 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
85 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -050086 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070087 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
88 { "video", "Video", ATRACE_TAG_VIDEO, { } },
89 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
90 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -070091 { "app", "Application", ATRACE_TAG_APP, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -070092 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -070093 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -070094 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -070095 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -070096 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 14:36:20 -070097 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-07-01 01:46:25 +090098 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Greg Hackmannbbd7d992014-12-01 14:43:34 -080099 { "database", "Database", ATRACE_TAG_DATABASE, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700100 { "sched", "CPU Scheduling", 0, {
101 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_switch/enable" },
102 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_wakeup/enable" },
Riley Andrews5672bb72015-11-19 13:31:17 -0800103 { OPT, "/sys/kernel/debug/tracing/events/sched/sched_blocked_reason/enable" },
Ruchi Kandoicfe500d2015-11-23 13:47:20 -0800104 { OPT, "/sys/kernel/debug/tracing/events/sched/sched_cpu_hotplug/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800105 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700106 { "irq", "IRQ Events", 0, {
107 { REQ, "/sys/kernel/debug/tracing/events/irq/enable" },
Riley Andrews412e4f62015-11-02 21:01:34 -0800108 { OPT, "/sys/kernel/debug/tracing/events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700109 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700110 { "freq", "CPU Frequency", 0, {
111 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_frequency/enable" },
112 { OPT, "/sys/kernel/debug/tracing/events/power/clock_set_rate/enable" },
Ruchi Kandoiffcc7112015-11-19 18:32:00 -0800113 { OPT, "/sys/kernel/debug/tracing/events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800114 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700115 { "membus", "Memory Bus Utilization", 0, {
116 { REQ, "/sys/kernel/debug/tracing/events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800117 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700118 { "idle", "CPU Idle", 0, {
119 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800120 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700121 { "disk", "Disk I/O", 0, {
Greg Hackmanne80d32c2014-11-20 12:59:44 -0800122 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_enter/enable" },
123 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_exit/enable" },
124 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_begin/enable" },
125 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_end/enable" },
126 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_begin/enable" },
127 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_end/enable" },
128 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable" },
129 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable" },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700130 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" },
131 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800132 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700133 { "mmc", "eMMC commands", 0, {
134 { REQ, "/sys/kernel/debug/tracing/events/mmc/enable" },
135 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700136 { "load", "CPU Load", 0, {
137 { REQ, "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800138 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700139 { "sync", "Synchronization", 0, {
140 { REQ, "/sys/kernel/debug/tracing/events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800141 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700142 { "workq", "Kernel Workqueues", 0, {
143 { REQ, "/sys/kernel/debug/tracing/events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800144 } },
Colin Cross580407f2014-08-18 15:22:13 -0700145 { "memreclaim", "Kernel Memory Reclaim", 0, {
146 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
147 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
148 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_wake/enable" },
149 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_sleep/enable" },
150 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800151 { "regulators", "Voltage and Current Regulators", 0, {
152 { REQ, "/sys/kernel/debug/tracing/events/regulator/enable" },
153 } },
Scott Bauerae473362015-06-08 16:32:36 -0700154 { "binder_driver", "Binder Kernel driver", 0, {
155 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction/enable" },
156 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction_received/enable" },
157 } },
158 { "binder_lock", "Binder global lock trace", 0, {
159 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_lock/enable" },
160 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_locked/enable" },
161 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_unlock/enable" },
162 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200163 { "pagecache", "Page cache", 0, {
164 { REQ, "/sys/kernel/debug/tracing/events/filemap/enable" },
165 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800166};
167
168/* Command line options */
169static int g_traceDurationSeconds = 5;
170static bool g_traceOverwrite = false;
171static int g_traceBufferSizeKB = 2048;
172static bool g_compress = false;
173static bool g_nohup = false;
174static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900175static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700176static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700177static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700178static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800179
180/* Global state */
181static bool g_traceAborted = false;
182static bool g_categoryEnables[NELEM(k_categories)] = {};
183
184/* Sys file paths */
185static const char* k_traceClockPath =
186 "/sys/kernel/debug/tracing/trace_clock";
187
188static const char* k_traceBufferSizePath =
189 "/sys/kernel/debug/tracing/buffer_size_kb";
190
191static const char* k_tracingOverwriteEnablePath =
192 "/sys/kernel/debug/tracing/options/overwrite";
193
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700194static const char* k_currentTracerPath =
195 "/sys/kernel/debug/tracing/current_tracer";
196
197static const char* k_printTgidPath =
198 "/sys/kernel/debug/tracing/options/print-tgid";
199
200static const char* k_funcgraphAbsTimePath =
201 "/sys/kernel/debug/tracing/options/funcgraph-abstime";
202
203static const char* k_funcgraphCpuPath =
204 "/sys/kernel/debug/tracing/options/funcgraph-cpu";
205
206static const char* k_funcgraphProcPath =
207 "/sys/kernel/debug/tracing/options/funcgraph-proc";
208
209static const char* k_funcgraphFlatPath =
210 "/sys/kernel/debug/tracing/options/funcgraph-flat";
211
212static const char* k_funcgraphDurationPath =
213 "/sys/kernel/debug/tracing/options/funcgraph-duration";
214
215static const char* k_ftraceFilterPath =
216 "/sys/kernel/debug/tracing/set_ftrace_filter";
217
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800218static const char* k_tracingOnPath =
219 "/sys/kernel/debug/tracing/tracing_on";
220
221static const char* k_tracePath =
222 "/sys/kernel/debug/tracing/trace";
223
Martijn Coenend9535872015-11-26 10:00:55 +0100224static const char* k_traceStreamPath =
225 "/sys/kernel/debug/tracing/trace_pipe";
226
John Reck469a1942015-03-26 15:31:35 -0700227static const char* k_traceMarkerPath =
228 "/sys/kernel/debug/tracing/trace_marker";
229
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800230// Check whether a file exists.
231static bool fileExists(const char* filename) {
232 return access(filename, F_OK) != -1;
233}
234
235// Check whether a file is writable.
236static bool fileIsWritable(const char* filename) {
237 return access(filename, W_OK) != -1;
238}
239
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700240// Truncate a file.
241static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800242{
Jamie Gennis43122e72013-03-21 14:06:31 -0700243 // This uses creat rather than truncate because some of the debug kernel
244 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
245 // calls to truncate, but they are cleared by calls to creat.
246 int traceFD = creat(path, 0);
247 if (traceFD == -1) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700248 fprintf(stderr, "error truncating %s: %s (%d)\n", path,
Jamie Gennis43122e72013-03-21 14:06:31 -0700249 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700250 return false;
251 }
252
Jamie Gennis43122e72013-03-21 14:06:31 -0700253 close(traceFD);
254
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700255 return true;
256}
257
258static bool _writeStr(const char* filename, const char* str, int flags)
259{
260 int fd = open(filename, flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800261 if (fd == -1) {
262 fprintf(stderr, "error opening %s: %s (%d)\n", filename,
263 strerror(errno), errno);
264 return false;
265 }
266
267 bool ok = true;
268 ssize_t len = strlen(str);
269 if (write(fd, str, len) != len) {
270 fprintf(stderr, "error writing to %s: %s (%d)\n", filename,
271 strerror(errno), errno);
272 ok = false;
273 }
274
275 close(fd);
276
277 return ok;
278}
279
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700280// Write a string to a file, returning true if the write was successful.
281static bool writeStr(const char* filename, const char* str)
282{
283 return _writeStr(filename, str, O_WRONLY);
284}
285
286// Append a string to a file, returning true if the write was successful.
287static bool appendStr(const char* filename, const char* str)
288{
289 return _writeStr(filename, str, O_APPEND|O_WRONLY);
290}
291
John Reck469a1942015-03-26 15:31:35 -0700292static void writeClockSyncMarker()
293{
294 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200295 int len = 0;
296 int fd = open(k_traceMarkerPath, O_WRONLY);
297 if (fd == -1) {
298 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
299 strerror(errno), errno);
300 return;
301 }
John Reck469a1942015-03-26 15:31:35 -0700302 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200303
304 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
305 if (write(fd, buffer, len) != len) {
306 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
307 }
308
309 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
310 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
311 if (write(fd, buffer, len) != len) {
312 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
313 }
314
315 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700316}
317
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800318// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
319// file.
320static bool setKernelOptionEnable(const char* filename, bool enable)
321{
322 return writeStr(filename, enable ? "1" : "0");
323}
324
325// Check whether the category is supported on the device with the current
326// rootness. A category is supported only if all its required /sys/ files are
327// writable and if enabling the category will enable one or more tracing tags
328// or /sys/ files.
329static bool isCategorySupported(const TracingCategory& category)
330{
331 bool ok = category.tags != 0;
332 for (int i = 0; i < MAX_SYS_FILES; i++) {
333 const char* path = category.sysfiles[i].path;
334 bool req = category.sysfiles[i].required == REQ;
335 if (path != NULL) {
336 if (req) {
337 if (!fileIsWritable(path)) {
338 return false;
339 } else {
340 ok = true;
341 }
342 } else {
343 ok |= fileIsWritable(path);
344 }
345 }
346 }
347 return ok;
348}
349
350// Check whether the category would be supported on the device if the user
351// were root. This function assumes that root is able to write to any file
352// that exists. It performs the same logic as isCategorySupported, but it
353// uses file existance rather than writability in the /sys/ file checks.
354static bool isCategorySupportedForRoot(const TracingCategory& category)
355{
356 bool ok = category.tags != 0;
357 for (int i = 0; i < MAX_SYS_FILES; i++) {
358 const char* path = category.sysfiles[i].path;
359 bool req = category.sysfiles[i].required == REQ;
360 if (path != NULL) {
361 if (req) {
362 if (!fileExists(path)) {
363 return false;
364 } else {
365 ok = true;
366 }
367 } else {
368 ok |= fileExists(path);
369 }
370 }
371 }
372 return ok;
373}
374
375// Enable or disable overwriting of the kernel trace buffers. Disabling this
376// will cause tracing to stop once the trace buffers have filled up.
377static bool setTraceOverwriteEnable(bool enable)
378{
379 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
380}
381
382// Enable or disable kernel tracing.
383static bool setTracingEnabled(bool enable)
384{
385 return setKernelOptionEnable(k_tracingOnPath, enable);
386}
387
388// Clear the contents of the kernel trace.
389static bool clearTrace()
390{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700391 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800392}
393
394// Set the size of the kernel's trace buffer in kilobytes.
395static bool setTraceBufferSizeKB(int size)
396{
397 char str[32] = "1";
398 int len;
399 if (size < 1) {
400 size = 1;
401 }
402 snprintf(str, 32, "%d", size);
403 return writeStr(k_traceBufferSizePath, str);
404}
405
Colin Crossb1ce49b2014-08-20 14:28:47 -0700406// Read the trace_clock sysfs file and return true if it matches the requested
407// value. The trace_clock file format is:
408// local [global] counter uptime perf
409static bool isTraceClock(const char *mode)
410{
411 int fd = open(k_traceClockPath, O_RDONLY);
412 if (fd == -1) {
413 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceClockPath,
414 strerror(errno), errno);
415 return false;
416 }
417
418 char buf[4097];
419 ssize_t n = read(fd, buf, 4096);
420 close(fd);
421 if (n == -1) {
422 fprintf(stderr, "error reading %s: %s (%d)\n", k_traceClockPath,
423 strerror(errno), errno);
424 return false;
425 }
426 buf[n] = '\0';
427
428 char *start = strchr(buf, '[');
429 if (start == NULL) {
430 return false;
431 }
432 start++;
433
434 char *end = strchr(start, ']');
435 if (end == NULL) {
436 return false;
437 }
438 *end = '\0';
439
440 return strcmp(mode, start) == 0;
441}
442
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800443// Enable or disable the kernel's use of the global clock. Disabling the global
444// clock will result in the kernel using a per-CPU local clock.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700445// Any write to the trace_clock sysfs file will reset the buffer, so only
446// update it if the requested value is not the current value.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800447static bool setGlobalClockEnable(bool enable)
448{
Colin Crossb1ce49b2014-08-20 14:28:47 -0700449 const char *clock = enable ? "global" : "local";
450
451 if (isTraceClock(clock)) {
452 return true;
453 }
454
455 return writeStr(k_traceClockPath, clock);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800456}
457
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700458static bool setPrintTgidEnableIfPresent(bool enable)
459{
460 if (fileExists(k_printTgidPath)) {
461 return setKernelOptionEnable(k_printTgidPath, enable);
462 }
463 return true;
464}
465
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800466// Poke all the binder-enabled processes in the system to get them to re-read
467// their system properties.
468static bool pokeBinderServices()
469{
470 sp<IServiceManager> sm = defaultServiceManager();
471 Vector<String16> services = sm->listServices();
472 for (size_t i = 0; i < services.size(); i++) {
473 sp<IBinder> obj = sm->checkService(services[i]);
474 if (obj != NULL) {
475 Parcel data;
476 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
477 NULL, 0) != OK) {
478 if (false) {
479 // XXX: For some reason this fails on tablets trying to
480 // poke the "phone" service. It's not clear whether some
481 // are expected to fail.
482 String8 svc(services[i]);
483 fprintf(stderr, "error poking binder service %s\n",
484 svc.string());
485 return false;
486 }
487 }
488 }
489 }
490 return true;
491}
492
493// Set the trace tags that userland tracing uses, and poke the running
494// processes to pick up the new value.
495static bool setTagsProperty(uint64_t tags)
496{
497 char buf[64];
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700498 snprintf(buf, 64, "%#" PRIx64, tags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800499 if (property_set(k_traceTagsProperty, buf) < 0) {
500 fprintf(stderr, "error setting trace tags system property\n");
501 return false;
502 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700503 return true;
504}
505
506// Set the system property that indicates which apps should perform
507// application-level tracing.
508static bool setAppCmdlineProperty(const char* cmdline)
509{
510 if (property_set(k_traceAppCmdlineProperty, cmdline) < 0) {
511 fprintf(stderr, "error setting trace app system property\n");
512 return false;
513 }
514 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800515}
516
517// Disable all /sys/ enable files.
518static bool disableKernelTraceEvents() {
519 bool ok = true;
520 for (int i = 0; i < NELEM(k_categories); i++) {
521 const TracingCategory &c = k_categories[i];
522 for (int j = 0; j < MAX_SYS_FILES; j++) {
523 const char* path = c.sysfiles[j].path;
524 if (path != NULL && fileIsWritable(path)) {
525 ok &= setKernelOptionEnable(path, false);
526 }
527 }
528 }
529 return ok;
530}
531
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700532// Verify that the comma separated list of functions are being traced by the
533// kernel.
534static bool verifyKernelTraceFuncs(const char* funcs)
535{
536 int fd = open(k_ftraceFilterPath, O_RDONLY);
537 if (fd == -1) {
538 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
539 strerror(errno), errno);
540 return false;
541 }
542
543 char buf[4097];
544 ssize_t n = read(fd, buf, 4096);
545 close(fd);
546 if (n == -1) {
547 fprintf(stderr, "error reading %s: %s (%d)\n", k_ftraceFilterPath,
548 strerror(errno), errno);
549 return false;
550 }
551
552 buf[n] = '\0';
553 String8 funcList = String8::format("\n%s", buf);
554
555 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100556 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700557 bool ok = true;
558 char* myFuncs = strdup(funcs);
559 char* func = strtok(myFuncs, ",");
560 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100561 if (!strchr(func, '*')) {
562 String8 fancyFunc = String8::format("\n%s\n", func);
563 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
564 if (!found || func[0] == '\0') {
565 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
566 "to trace.\n", func);
567 ok = false;
568 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700569 }
570 func = strtok(NULL, ",");
571 }
572 free(myFuncs);
573
574 return ok;
575}
576
577// Set the comma separated list of functions that the kernel is to trace.
578static bool setKernelTraceFuncs(const char* funcs)
579{
580 bool ok = true;
581
582 if (funcs == NULL || funcs[0] == '\0') {
583 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700584 if (fileIsWritable(k_currentTracerPath)) {
585 ok &= writeStr(k_currentTracerPath, "nop");
586 }
587 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700588 ok &= truncateFile(k_ftraceFilterPath);
589 }
590 } else {
591 // Enable kernel function tracing.
592 ok &= writeStr(k_currentTracerPath, "function_graph");
593 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
594 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
595 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
596 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
597
598 // Set the requested filter functions.
599 ok &= truncateFile(k_ftraceFilterPath);
600 char* myFuncs = strdup(funcs);
601 char* func = strtok(myFuncs, ",");
602 while (func) {
603 ok &= appendStr(k_ftraceFilterPath, func);
604 func = strtok(NULL, ",");
605 }
606 free(myFuncs);
607
608 // Verify that the set functions are being traced.
609 if (ok) {
610 ok &= verifyKernelTraceFuncs(funcs);
611 }
612 }
613
614 return ok;
615}
616
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900617static bool setCategoryEnable(const char* name, bool enable)
618{
619 for (int i = 0; i < NELEM(k_categories); i++) {
620 const TracingCategory& c = k_categories[i];
621 if (strcmp(name, c.name) == 0) {
622 if (isCategorySupported(c)) {
623 g_categoryEnables[i] = enable;
624 return true;
625 } else {
626 if (isCategorySupportedForRoot(c)) {
627 fprintf(stderr, "error: category \"%s\" requires root "
628 "privileges.\n", name);
629 } else {
630 fprintf(stderr, "error: category \"%s\" is not supported "
631 "on this device.\n", name);
632 }
633 return false;
634 }
635 }
636 }
637 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
638 return false;
639}
640
641static bool setCategoriesEnableFromFile(const char* categories_file)
642{
643 if (!categories_file) {
644 return true;
645 }
646 Tokenizer* tokenizer = NULL;
647 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
648 return false;
649 }
650 bool ok = true;
651 while (!tokenizer->isEol()) {
652 String8 token = tokenizer->nextToken(" ");
653 if (token.isEmpty()) {
654 tokenizer->skipDelimiters(" ");
655 continue;
656 }
657 ok &= setCategoryEnable(token.string(), true);
658 }
659 delete tokenizer;
660 return ok;
661}
662
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700663// Set all the kernel tracing settings to the desired state for this trace
664// capture.
665static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800666{
667 bool ok = true;
668
669 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900670 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800671 ok &= setTraceOverwriteEnable(g_traceOverwrite);
672 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
673 ok &= setGlobalClockEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700674 ok &= setPrintTgidEnableIfPresent(true);
675 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800676
677 // Set up the tags property.
678 uint64_t tags = 0;
679 for (int i = 0; i < NELEM(k_categories); i++) {
680 if (g_categoryEnables[i]) {
681 const TracingCategory &c = k_categories[i];
682 tags |= c.tags;
683 }
684 }
685 ok &= setTagsProperty(tags);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700686 ok &= setAppCmdlineProperty(g_debugAppCmdLine);
687 ok &= pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800688
689 // Disable all the sysfs enables. This is done as a separate loop from
690 // the enables to allow the same enable to exist in multiple categories.
691 ok &= disableKernelTraceEvents();
692
693 // Enable all the sysfs enables that are in an enabled category.
694 for (int i = 0; i < NELEM(k_categories); i++) {
695 if (g_categoryEnables[i]) {
696 const TracingCategory &c = k_categories[i];
697 for (int j = 0; j < MAX_SYS_FILES; j++) {
698 const char* path = c.sysfiles[j].path;
699 bool required = c.sysfiles[j].required == REQ;
700 if (path != NULL) {
701 if (fileIsWritable(path)) {
702 ok &= setKernelOptionEnable(path, true);
703 } else if (required) {
704 fprintf(stderr, "error writing file %s\n", path);
705 ok = false;
706 }
707 }
708 }
709 }
710 }
711
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800712 return ok;
713}
714
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700715// Reset all the kernel tracing settings to their default state.
716static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800717{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800718 // Disable all tracing that we're able to.
719 disableKernelTraceEvents();
720
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700721 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800722 setTagsProperty(0);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700723 setAppCmdlineProperty("");
724 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800725
726 // Set the options back to their defaults.
727 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700728 setTraceBufferSizeKB(1);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800729 setGlobalClockEnable(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700730 setPrintTgidEnableIfPresent(false);
731 setKernelTraceFuncs(NULL);
732}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800733
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700734
735// Enable tracing in the kernel.
736static bool startTrace()
737{
738 return setTracingEnabled(true);
739}
740
741// Disable tracing in the kernel.
742static void stopTrace()
743{
744 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800745}
746
Martijn Coenend9535872015-11-26 10:00:55 +0100747// Read data from the tracing pipe and forward to stdout
748static void streamTrace()
749{
750 char trace_data[4096];
751 int traceFD = open(k_traceStreamPath, O_RDWR);
752 if (traceFD == -1) {
753 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
754 strerror(errno), errno);
755 return;
756 }
757 while (!g_traceAborted) {
758 ssize_t bytes_read = read(traceFD, trace_data, 4096);
759 if (bytes_read > 0) {
760 write(STDOUT_FILENO, trace_data, bytes_read);
761 fflush(stdout);
762 } else {
763 if (!g_traceAborted) {
764 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
765 bytes_read, errno, strerror(errno));
766 }
767 break;
768 }
769 }
770}
771
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800772// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700773static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800774{
John Reck6c8ac922016-03-28 11:25:30 -0700775 ALOGI("Dumping trace");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800776 int traceFD = open(k_tracePath, O_RDWR);
777 if (traceFD == -1) {
778 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
779 strerror(errno), errno);
780 return;
781 }
782
783 if (g_compress) {
784 z_stream zs;
785 uint8_t *in, *out;
786 int result, flush;
787
Elliott Hughes3da5d232015-01-25 08:35:20 -0800788 memset(&zs, 0, sizeof(zs));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800789 result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
790 if (result != Z_OK) {
791 fprintf(stderr, "error initializing zlib: %d\n", result);
792 close(traceFD);
793 return;
794 }
795
796 const size_t bufSize = 64*1024;
797 in = (uint8_t*)malloc(bufSize);
798 out = (uint8_t*)malloc(bufSize);
799 flush = Z_NO_FLUSH;
800
801 zs.next_out = out;
802 zs.avail_out = bufSize;
803
804 do {
805
806 if (zs.avail_in == 0) {
807 // More input is needed.
808 result = read(traceFD, in, bufSize);
809 if (result < 0) {
810 fprintf(stderr, "error reading trace: %s (%d)\n",
811 strerror(errno), errno);
812 result = Z_STREAM_END;
813 break;
814 } else if (result == 0) {
815 flush = Z_FINISH;
816 } else {
817 zs.next_in = in;
818 zs.avail_in = result;
819 }
820 }
821
822 if (zs.avail_out == 0) {
823 // Need to write the output.
John Reck40b26b42016-03-30 09:44:36 -0700824 result = write(outFd, out, bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800825 if ((size_t)result < bufSize) {
826 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
827 strerror(errno), errno);
828 result = Z_STREAM_END; // skip deflate error message
829 zs.avail_out = bufSize; // skip the final write
830 break;
831 }
832 zs.next_out = out;
833 zs.avail_out = bufSize;
834 }
835
836 } while ((result = deflate(&zs, flush)) == Z_OK);
837
838 if (result != Z_STREAM_END) {
839 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
840 }
841
842 if (zs.avail_out < bufSize) {
843 size_t bytes = bufSize - zs.avail_out;
John Reck40b26b42016-03-30 09:44:36 -0700844 result = write(outFd, out, bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800845 if ((size_t)result < bytes) {
846 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
847 strerror(errno), errno);
848 }
849 }
850
851 result = deflateEnd(&zs);
852 if (result != Z_OK) {
853 fprintf(stderr, "error cleaning up zlib: %d\n", result);
854 }
855
856 free(in);
857 free(out);
858 } else {
859 ssize_t sent = 0;
John Reck40b26b42016-03-30 09:44:36 -0700860 while ((sent = sendfile(outFd, traceFD, NULL, 64*1024*1024)) > 0);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800861 if (sent == -1) {
862 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
863 errno);
864 }
865 }
866
867 close(traceFD);
868}
869
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700870static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800871{
872 if (!g_nohup) {
873 g_traceAborted = true;
874 }
875}
876
877static void registerSigHandler()
878{
879 struct sigaction sa;
880 sigemptyset(&sa.sa_mask);
881 sa.sa_flags = 0;
882 sa.sa_handler = handleSignal;
883 sigaction(SIGHUP, &sa, NULL);
884 sigaction(SIGINT, &sa, NULL);
885 sigaction(SIGQUIT, &sa, NULL);
886 sigaction(SIGTERM, &sa, NULL);
887}
888
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800889static void listSupportedCategories()
890{
891 for (int i = 0; i < NELEM(k_categories); i++) {
892 const TracingCategory& c = k_categories[i];
893 if (isCategorySupported(c)) {
894 printf(" %10s - %s\n", c.name, c.longname);
895 }
896 }
897}
898
899// Print the command usage help to stderr.
900static void showHelp(const char *cmd)
901{
902 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
903 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700904 " -a appname enable app-level tracing for a comma "
905 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800906 " -b N use a trace buffer size of N KB\n"
907 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900908 " -f filename use the categories written in a file as space-separated\n"
909 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700910 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800911 " -n ignore signals\n"
912 " -s N sleep for N seconds before tracing [default 0]\n"
913 " -t N trace for N seconds [defualt 5]\n"
914 " -z compress the trace dump\n"
915 " --async_start start circular trace and return immediatly\n"
916 " --async_dump dump the current contents of circular trace buffer\n"
917 " --async_stop stop tracing and dump the current contents of circular\n"
918 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +0100919 " --stream stream trace to stdout as it enters the trace buffer\n"
920 " Note: this can take significant CPU time, and is best\n"
921 " used for measuring things that are not affected by\n"
922 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -0800923 " --list_categories\n"
924 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -0700925 " -o filename write the trace to the specified file instead\n"
926 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800927 );
928}
929
930int main(int argc, char **argv)
931{
932 bool async = false;
933 bool traceStart = true;
934 bool traceStop = true;
935 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +0100936 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800937
938 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
939 showHelp(argv[0]);
940 exit(0);
941 }
942
943 for (;;) {
944 int ret;
945 int option_index = 0;
946 static struct option long_options[] = {
947 {"async_start", no_argument, 0, 0 },
948 {"async_stop", no_argument, 0, 0 },
949 {"async_dump", no_argument, 0, 0 },
950 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +0100951 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800952 { 0, 0, 0, 0 }
953 };
954
John Reck40b26b42016-03-30 09:44:36 -0700955 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800956 long_options, &option_index);
957
958 if (ret < 0) {
959 for (int i = optind; i < argc; i++) {
960 if (!setCategoryEnable(argv[i], true)) {
961 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
962 exit(1);
963 }
964 }
965 break;
966 }
967
968 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700969 case 'a':
970 g_debugAppCmdLine = optarg;
971 break;
972
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800973 case 'b':
974 g_traceBufferSizeKB = atoi(optarg);
975 break;
976
977 case 'c':
978 g_traceOverwrite = true;
979 break;
980
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900981 case 'f':
982 g_categoriesFile = optarg;
983 break;
984
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700985 case 'k':
986 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700987 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700988
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800989 case 'n':
990 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700991 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800992
993 case 's':
994 g_initialSleepSecs = atoi(optarg);
995 break;
996
997 case 't':
998 g_traceDurationSeconds = atoi(optarg);
999 break;
1000
1001 case 'z':
1002 g_compress = true;
1003 break;
1004
John Reck40b26b42016-03-30 09:44:36 -07001005 case 'o':
1006 g_outputFile = optarg;
1007 break;
1008
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001009 case 0:
1010 if (!strcmp(long_options[option_index].name, "async_start")) {
1011 async = true;
1012 traceStop = false;
1013 traceDump = false;
1014 g_traceOverwrite = true;
1015 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1016 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001017 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001018 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1019 async = true;
1020 traceStart = false;
1021 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001022 } else if (!strcmp(long_options[option_index].name, "stream")) {
1023 traceStream = true;
1024 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001025 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1026 listSupportedCategories();
1027 exit(0);
1028 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001029 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001030
1031 default:
1032 fprintf(stderr, "\n");
1033 showHelp(argv[0]);
1034 exit(-1);
1035 break;
1036 }
1037 }
1038
1039 registerSigHandler();
1040
1041 if (g_initialSleepSecs > 0) {
1042 sleep(g_initialSleepSecs);
1043 }
1044
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001045 bool ok = true;
1046 ok &= setUpTrace();
1047 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001048
1049 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001050 if (!traceStream) {
1051 printf("capturing trace...");
1052 fflush(stdout);
1053 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001054
1055 // We clear the trace after starting it because tracing gets enabled for
1056 // each CPU individually in the kernel. Having the beginning of the trace
1057 // contain entries from only one CPU can cause "begin" entries without a
1058 // matching "end" entry to show up if a task gets migrated from one CPU to
1059 // another.
1060 ok = clearTrace();
1061
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001062 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001063 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001064 // Sleep to allow the trace to be captured.
1065 struct timespec timeLeft;
1066 timeLeft.tv_sec = g_traceDurationSeconds;
1067 timeLeft.tv_nsec = 0;
1068 do {
1069 if (g_traceAborted) {
1070 break;
1071 }
1072 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1073 }
Martijn Coenend9535872015-11-26 10:00:55 +01001074
1075 if (traceStream) {
1076 streamTrace();
1077 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001078 }
1079
1080 // Stop the trace and restore the default settings.
1081 if (traceStop)
1082 stopTrace();
1083
1084 if (ok && traceDump) {
1085 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001086 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001087 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001088 int outFd = STDOUT_FILENO;
1089 if (g_outputFile) {
1090 outFd = open(g_outputFile, O_WRONLY | O_CREAT);
1091 }
1092 if (outFd == -1) {
1093 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1094 } else {
1095 dprintf(outFd, "TRACE:\n");
1096 dumpTrace(outFd);
1097 if (g_outputFile) {
1098 close(outFd);
1099 }
1100 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001101 } else {
1102 printf("\ntrace aborted.\n");
1103 fflush(stdout);
1104 }
1105 clearTrace();
1106 } else if (!ok) {
1107 fprintf(stderr, "unable to start tracing\n");
1108 }
1109
1110 // Reset the trace buffer size to 1.
1111 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001112 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001113
1114 return g_traceAborted ? 1 : 0;
1115}