blob: a6d93dcc66870c902f858e1f8c521f47cd66fe13 [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>
Martijn Coenend9535872015-11-26 10:00:55 +010029#include <unistd.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080030#include <zlib.h>
31
Elliott Hughesa252f4d2016-07-21 17:12:15 -070032#include <memory>
33
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080034#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>
Stephane Gasparinid8419c22016-03-02 13:45:15 +010044#include <android-base/file.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080045
46using namespace android;
47
48#define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0])))
49
Mohamad Ayyash26dbcbe2014-04-08 15:24:11 -070050enum { MAX_SYS_FILES = 10 };
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080051
52const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
Jamie Gennisf7f29c82013-03-27 15:50:58 -070053const char* k_traceAppCmdlineProperty = "debug.atrace.app_cmdlines";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080054
55typedef enum { OPT, REQ } requiredness ;
56
57struct TracingCategory {
58 // The name identifying the category.
59 const char* name;
60
61 // A longer description of the category.
62 const char* longname;
63
64 // The userland tracing tags that the category enables.
65 uint64_t tags;
66
67 // The fname==NULL terminated list of /sys/ files that the category
68 // enables.
69 struct {
70 // Whether the file must be writable in order to enable the tracing
71 // category.
72 requiredness required;
73
74 // The path to the enable file.
75 const char* path;
76 } sysfiles[MAX_SYS_FILES];
77};
78
79/* Tracing categories */
80static const TracingCategory k_categories[] = {
Jamie Gennisb2a89e32013-03-11 19:37:53 -070081 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, { } },
82 { "input", "Input", ATRACE_TAG_INPUT, { } },
83 { "view", "View System", ATRACE_TAG_VIEW, { } },
84 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
85 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
86 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -050087 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070088 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
89 { "video", "Video", ATRACE_TAG_VIDEO, { } },
90 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
91 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -070092 { "app", "Application", ATRACE_TAG_APP, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -070093 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -070094 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -070095 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -070096 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -070097 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 14:36:20 -070098 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-07-01 01:46:25 +090099 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Greg Hackmannbbd7d992014-12-01 14:43:34 -0800100 { "database", "Database", ATRACE_TAG_DATABASE, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700101 { "sched", "CPU Scheduling", 0, {
102 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_switch/enable" },
103 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_wakeup/enable" },
Riley Andrews5672bb72015-11-19 13:31:17 -0800104 { OPT, "/sys/kernel/debug/tracing/events/sched/sched_blocked_reason/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" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800113 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700114 { "membus", "Memory Bus Utilization", 0, {
115 { REQ, "/sys/kernel/debug/tracing/events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800116 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700117 { "idle", "CPU Idle", 0, {
118 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800119 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700120 { "disk", "Disk I/O", 0, {
Greg Hackmanne80d32c2014-11-20 12:59:44 -0800121 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_enter/enable" },
122 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_exit/enable" },
123 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_begin/enable" },
124 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_end/enable" },
125 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_begin/enable" },
126 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_end/enable" },
127 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable" },
128 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable" },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700129 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" },
130 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800131 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700132 { "mmc", "eMMC commands", 0, {
133 { REQ, "/sys/kernel/debug/tracing/events/mmc/enable" },
134 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700135 { "load", "CPU Load", 0, {
136 { REQ, "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800137 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700138 { "sync", "Synchronization", 0, {
139 { REQ, "/sys/kernel/debug/tracing/events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800140 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700141 { "workq", "Kernel Workqueues", 0, {
142 { REQ, "/sys/kernel/debug/tracing/events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800143 } },
Colin Cross580407f2014-08-18 15:22:13 -0700144 { "memreclaim", "Kernel Memory Reclaim", 0, {
145 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
146 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
147 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_wake/enable" },
148 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_sleep/enable" },
149 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800150 { "regulators", "Voltage and Current Regulators", 0, {
151 { REQ, "/sys/kernel/debug/tracing/events/regulator/enable" },
152 } },
Scott Bauerae473362015-06-08 16:32:36 -0700153 { "binder_driver", "Binder Kernel driver", 0, {
154 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction/enable" },
155 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction_received/enable" },
156 } },
157 { "binder_lock", "Binder global lock trace", 0, {
158 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_lock/enable" },
159 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_locked/enable" },
160 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_unlock/enable" },
161 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800162};
163
164/* Command line options */
165static int g_traceDurationSeconds = 5;
166static bool g_traceOverwrite = false;
167static int g_traceBufferSizeKB = 2048;
168static bool g_compress = false;
169static bool g_nohup = false;
170static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900171static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700172static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700173static const char* g_debugAppCmdLine = "";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800174
175/* Global state */
176static bool g_traceAborted = false;
177static bool g_categoryEnables[NELEM(k_categories)] = {};
178
179/* Sys file paths */
180static const char* k_traceClockPath =
181 "/sys/kernel/debug/tracing/trace_clock";
182
183static const char* k_traceBufferSizePath =
184 "/sys/kernel/debug/tracing/buffer_size_kb";
185
186static const char* k_tracingOverwriteEnablePath =
187 "/sys/kernel/debug/tracing/options/overwrite";
188
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700189static const char* k_currentTracerPath =
190 "/sys/kernel/debug/tracing/current_tracer";
191
192static const char* k_printTgidPath =
193 "/sys/kernel/debug/tracing/options/print-tgid";
194
195static const char* k_funcgraphAbsTimePath =
196 "/sys/kernel/debug/tracing/options/funcgraph-abstime";
197
198static const char* k_funcgraphCpuPath =
199 "/sys/kernel/debug/tracing/options/funcgraph-cpu";
200
201static const char* k_funcgraphProcPath =
202 "/sys/kernel/debug/tracing/options/funcgraph-proc";
203
204static const char* k_funcgraphFlatPath =
205 "/sys/kernel/debug/tracing/options/funcgraph-flat";
206
207static const char* k_funcgraphDurationPath =
208 "/sys/kernel/debug/tracing/options/funcgraph-duration";
209
210static const char* k_ftraceFilterPath =
211 "/sys/kernel/debug/tracing/set_ftrace_filter";
212
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800213static const char* k_tracingOnPath =
214 "/sys/kernel/debug/tracing/tracing_on";
215
216static const char* k_tracePath =
217 "/sys/kernel/debug/tracing/trace";
218
Martijn Coenend9535872015-11-26 10:00:55 +0100219static const char* k_traceStreamPath =
220 "/sys/kernel/debug/tracing/trace_pipe";
221
John Reck469a1942015-03-26 15:31:35 -0700222static const char* k_traceMarkerPath =
223 "/sys/kernel/debug/tracing/trace_marker";
224
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800225// Check whether a file exists.
226static bool fileExists(const char* filename) {
227 return access(filename, F_OK) != -1;
228}
229
230// Check whether a file is writable.
231static bool fileIsWritable(const char* filename) {
232 return access(filename, W_OK) != -1;
233}
234
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700235// Truncate a file.
236static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800237{
Jamie Gennis43122e72013-03-21 14:06:31 -0700238 // This uses creat rather than truncate because some of the debug kernel
239 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
240 // calls to truncate, but they are cleared by calls to creat.
241 int traceFD = creat(path, 0);
242 if (traceFD == -1) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700243 fprintf(stderr, "error truncating %s: %s (%d)\n", path,
Jamie Gennis43122e72013-03-21 14:06:31 -0700244 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700245 return false;
246 }
247
Jamie Gennis43122e72013-03-21 14:06:31 -0700248 close(traceFD);
249
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700250 return true;
251}
252
253static bool _writeStr(const char* filename, const char* str, int flags)
254{
255 int fd = open(filename, flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800256 if (fd == -1) {
257 fprintf(stderr, "error opening %s: %s (%d)\n", filename,
258 strerror(errno), errno);
259 return false;
260 }
261
262 bool ok = true;
263 ssize_t len = strlen(str);
264 if (write(fd, str, len) != len) {
265 fprintf(stderr, "error writing to %s: %s (%d)\n", filename,
266 strerror(errno), errno);
267 ok = false;
268 }
269
270 close(fd);
271
272 return ok;
273}
274
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700275// Write a string to a file, returning true if the write was successful.
276static bool writeStr(const char* filename, const char* str)
277{
278 return _writeStr(filename, str, O_WRONLY);
279}
280
281// Append a string to a file, returning true if the write was successful.
282static bool appendStr(const char* filename, const char* str)
283{
284 return _writeStr(filename, str, O_APPEND|O_WRONLY);
285}
286
John Reck469a1942015-03-26 15:31:35 -0700287static void writeClockSyncMarker()
288{
289 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200290 int len = 0;
291 int fd = open(k_traceMarkerPath, O_WRONLY);
292 if (fd == -1) {
293 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
294 strerror(errno), errno);
295 return;
296 }
John Reck469a1942015-03-26 15:31:35 -0700297 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200298
299 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
300 if (write(fd, buffer, len) != len) {
301 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
302 }
303
304 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
305 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
306 if (write(fd, buffer, len) != len) {
307 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
308 }
309
310 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700311}
312
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800313// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
314// file.
315static bool setKernelOptionEnable(const char* filename, bool enable)
316{
317 return writeStr(filename, enable ? "1" : "0");
318}
319
320// Check whether the category is supported on the device with the current
321// rootness. A category is supported only if all its required /sys/ files are
322// writable and if enabling the category will enable one or more tracing tags
323// or /sys/ files.
324static bool isCategorySupported(const TracingCategory& category)
325{
326 bool ok = category.tags != 0;
327 for (int i = 0; i < MAX_SYS_FILES; i++) {
328 const char* path = category.sysfiles[i].path;
329 bool req = category.sysfiles[i].required == REQ;
330 if (path != NULL) {
331 if (req) {
332 if (!fileIsWritable(path)) {
333 return false;
334 } else {
335 ok = true;
336 }
337 } else {
338 ok |= fileIsWritable(path);
339 }
340 }
341 }
342 return ok;
343}
344
345// Check whether the category would be supported on the device if the user
346// were root. This function assumes that root is able to write to any file
347// that exists. It performs the same logic as isCategorySupported, but it
348// uses file existance rather than writability in the /sys/ file checks.
349static bool isCategorySupportedForRoot(const TracingCategory& category)
350{
351 bool ok = category.tags != 0;
352 for (int i = 0; i < MAX_SYS_FILES; i++) {
353 const char* path = category.sysfiles[i].path;
354 bool req = category.sysfiles[i].required == REQ;
355 if (path != NULL) {
356 if (req) {
357 if (!fileExists(path)) {
358 return false;
359 } else {
360 ok = true;
361 }
362 } else {
363 ok |= fileExists(path);
364 }
365 }
366 }
367 return ok;
368}
369
370// Enable or disable overwriting of the kernel trace buffers. Disabling this
371// will cause tracing to stop once the trace buffers have filled up.
372static bool setTraceOverwriteEnable(bool enable)
373{
374 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
375}
376
377// Enable or disable kernel tracing.
378static bool setTracingEnabled(bool enable)
379{
380 return setKernelOptionEnable(k_tracingOnPath, enable);
381}
382
383// Clear the contents of the kernel trace.
384static bool clearTrace()
385{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700386 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800387}
388
389// Set the size of the kernel's trace buffer in kilobytes.
390static bool setTraceBufferSizeKB(int size)
391{
392 char str[32] = "1";
393 int len;
394 if (size < 1) {
395 size = 1;
396 }
397 snprintf(str, 32, "%d", size);
398 return writeStr(k_traceBufferSizePath, str);
399}
400
Colin Crossb1ce49b2014-08-20 14:28:47 -0700401// Read the trace_clock sysfs file and return true if it matches the requested
402// value. The trace_clock file format is:
403// local [global] counter uptime perf
404static bool isTraceClock(const char *mode)
405{
406 int fd = open(k_traceClockPath, O_RDONLY);
407 if (fd == -1) {
408 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceClockPath,
409 strerror(errno), errno);
410 return false;
411 }
412
413 char buf[4097];
414 ssize_t n = read(fd, buf, 4096);
415 close(fd);
416 if (n == -1) {
417 fprintf(stderr, "error reading %s: %s (%d)\n", k_traceClockPath,
418 strerror(errno), errno);
419 return false;
420 }
421 buf[n] = '\0';
422
423 char *start = strchr(buf, '[');
424 if (start == NULL) {
425 return false;
426 }
427 start++;
428
429 char *end = strchr(start, ']');
430 if (end == NULL) {
431 return false;
432 }
433 *end = '\0';
434
435 return strcmp(mode, start) == 0;
436}
437
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800438// Enable or disable the kernel's use of the global clock. Disabling the global
439// clock will result in the kernel using a per-CPU local clock.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700440// Any write to the trace_clock sysfs file will reset the buffer, so only
441// update it if the requested value is not the current value.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800442static bool setGlobalClockEnable(bool enable)
443{
Colin Crossb1ce49b2014-08-20 14:28:47 -0700444 const char *clock = enable ? "global" : "local";
445
446 if (isTraceClock(clock)) {
447 return true;
448 }
449
450 return writeStr(k_traceClockPath, clock);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800451}
452
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700453static bool setPrintTgidEnableIfPresent(bool enable)
454{
455 if (fileExists(k_printTgidPath)) {
456 return setKernelOptionEnable(k_printTgidPath, enable);
457 }
458 return true;
459}
460
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800461// Poke all the binder-enabled processes in the system to get them to re-read
462// their system properties.
463static bool pokeBinderServices()
464{
465 sp<IServiceManager> sm = defaultServiceManager();
466 Vector<String16> services = sm->listServices();
467 for (size_t i = 0; i < services.size(); i++) {
468 sp<IBinder> obj = sm->checkService(services[i]);
469 if (obj != NULL) {
470 Parcel data;
471 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
472 NULL, 0) != OK) {
473 if (false) {
474 // XXX: For some reason this fails on tablets trying to
475 // poke the "phone" service. It's not clear whether some
476 // are expected to fail.
477 String8 svc(services[i]);
478 fprintf(stderr, "error poking binder service %s\n",
479 svc.string());
480 return false;
481 }
482 }
483 }
484 }
485 return true;
486}
487
488// Set the trace tags that userland tracing uses, and poke the running
489// processes to pick up the new value.
490static bool setTagsProperty(uint64_t tags)
491{
492 char buf[64];
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700493 snprintf(buf, 64, "%#" PRIx64, tags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800494 if (property_set(k_traceTagsProperty, buf) < 0) {
495 fprintf(stderr, "error setting trace tags system property\n");
496 return false;
497 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700498 return true;
499}
500
501// Set the system property that indicates which apps should perform
502// application-level tracing.
503static bool setAppCmdlineProperty(const char* cmdline)
504{
505 if (property_set(k_traceAppCmdlineProperty, cmdline) < 0) {
506 fprintf(stderr, "error setting trace app system property\n");
507 return false;
508 }
509 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800510}
511
512// Disable all /sys/ enable files.
513static bool disableKernelTraceEvents() {
514 bool ok = true;
515 for (int i = 0; i < NELEM(k_categories); i++) {
516 const TracingCategory &c = k_categories[i];
517 for (int j = 0; j < MAX_SYS_FILES; j++) {
518 const char* path = c.sysfiles[j].path;
519 if (path != NULL && fileIsWritable(path)) {
520 ok &= setKernelOptionEnable(path, false);
521 }
522 }
523 }
524 return ok;
525}
526
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700527// Verify that the comma separated list of functions are being traced by the
528// kernel.
529static bool verifyKernelTraceFuncs(const char* funcs)
530{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100531 std::string buf;
532 if (!android::base::ReadFileToString(k_ftraceFilterPath, &buf)) {
533 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700534 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100535 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700536 }
537
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100538 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700539
540 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100541 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700542 bool ok = true;
543 char* myFuncs = strdup(funcs);
544 char* func = strtok(myFuncs, ",");
545 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100546 if (!strchr(func, '*')) {
547 String8 fancyFunc = String8::format("\n%s\n", func);
548 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
549 if (!found || func[0] == '\0') {
550 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
551 "to trace.\n", func);
552 ok = false;
553 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700554 }
555 func = strtok(NULL, ",");
556 }
557 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700558 return ok;
559}
560
561// Set the comma separated list of functions that the kernel is to trace.
562static bool setKernelTraceFuncs(const char* funcs)
563{
564 bool ok = true;
565
566 if (funcs == NULL || funcs[0] == '\0') {
567 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700568 if (fileIsWritable(k_currentTracerPath)) {
569 ok &= writeStr(k_currentTracerPath, "nop");
570 }
571 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700572 ok &= truncateFile(k_ftraceFilterPath);
573 }
574 } else {
575 // Enable kernel function tracing.
576 ok &= writeStr(k_currentTracerPath, "function_graph");
577 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
578 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
579 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
580 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
581
582 // Set the requested filter functions.
583 ok &= truncateFile(k_ftraceFilterPath);
584 char* myFuncs = strdup(funcs);
585 char* func = strtok(myFuncs, ",");
586 while (func) {
587 ok &= appendStr(k_ftraceFilterPath, func);
588 func = strtok(NULL, ",");
589 }
590 free(myFuncs);
591
592 // Verify that the set functions are being traced.
593 if (ok) {
594 ok &= verifyKernelTraceFuncs(funcs);
595 }
596 }
597
598 return ok;
599}
600
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900601static bool setCategoryEnable(const char* name, bool enable)
602{
603 for (int i = 0; i < NELEM(k_categories); i++) {
604 const TracingCategory& c = k_categories[i];
605 if (strcmp(name, c.name) == 0) {
606 if (isCategorySupported(c)) {
607 g_categoryEnables[i] = enable;
608 return true;
609 } else {
610 if (isCategorySupportedForRoot(c)) {
611 fprintf(stderr, "error: category \"%s\" requires root "
612 "privileges.\n", name);
613 } else {
614 fprintf(stderr, "error: category \"%s\" is not supported "
615 "on this device.\n", name);
616 }
617 return false;
618 }
619 }
620 }
621 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
622 return false;
623}
624
625static bool setCategoriesEnableFromFile(const char* categories_file)
626{
627 if (!categories_file) {
628 return true;
629 }
630 Tokenizer* tokenizer = NULL;
631 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
632 return false;
633 }
634 bool ok = true;
635 while (!tokenizer->isEol()) {
636 String8 token = tokenizer->nextToken(" ");
637 if (token.isEmpty()) {
638 tokenizer->skipDelimiters(" ");
639 continue;
640 }
641 ok &= setCategoryEnable(token.string(), true);
642 }
643 delete tokenizer;
644 return ok;
645}
646
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700647// Set all the kernel tracing settings to the desired state for this trace
648// capture.
649static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800650{
651 bool ok = true;
652
653 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900654 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800655 ok &= setTraceOverwriteEnable(g_traceOverwrite);
656 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
657 ok &= setGlobalClockEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700658 ok &= setPrintTgidEnableIfPresent(true);
659 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800660
661 // Set up the tags property.
662 uint64_t tags = 0;
663 for (int i = 0; i < NELEM(k_categories); i++) {
664 if (g_categoryEnables[i]) {
665 const TracingCategory &c = k_categories[i];
666 tags |= c.tags;
667 }
668 }
669 ok &= setTagsProperty(tags);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700670 ok &= setAppCmdlineProperty(g_debugAppCmdLine);
671 ok &= pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800672
673 // Disable all the sysfs enables. This is done as a separate loop from
674 // the enables to allow the same enable to exist in multiple categories.
675 ok &= disableKernelTraceEvents();
676
677 // Enable all the sysfs enables that are in an enabled category.
678 for (int i = 0; i < NELEM(k_categories); i++) {
679 if (g_categoryEnables[i]) {
680 const TracingCategory &c = k_categories[i];
681 for (int j = 0; j < MAX_SYS_FILES; j++) {
682 const char* path = c.sysfiles[j].path;
683 bool required = c.sysfiles[j].required == REQ;
684 if (path != NULL) {
685 if (fileIsWritable(path)) {
686 ok &= setKernelOptionEnable(path, true);
687 } else if (required) {
688 fprintf(stderr, "error writing file %s\n", path);
689 ok = false;
690 }
691 }
692 }
693 }
694 }
695
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800696 return ok;
697}
698
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700699// Reset all the kernel tracing settings to their default state.
700static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800701{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800702 // Disable all tracing that we're able to.
703 disableKernelTraceEvents();
704
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700705 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800706 setTagsProperty(0);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700707 setAppCmdlineProperty("");
708 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800709
710 // Set the options back to their defaults.
711 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700712 setTraceBufferSizeKB(1);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800713 setGlobalClockEnable(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700714 setPrintTgidEnableIfPresent(false);
715 setKernelTraceFuncs(NULL);
716}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800717
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700718
719// Enable tracing in the kernel.
720static bool startTrace()
721{
722 return setTracingEnabled(true);
723}
724
725// Disable tracing in the kernel.
726static void stopTrace()
727{
728 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800729}
730
Martijn Coenend9535872015-11-26 10:00:55 +0100731// Read data from the tracing pipe and forward to stdout
732static void streamTrace()
733{
734 char trace_data[4096];
735 int traceFD = open(k_traceStreamPath, O_RDWR);
736 if (traceFD == -1) {
737 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
738 strerror(errno), errno);
739 return;
740 }
741 while (!g_traceAborted) {
742 ssize_t bytes_read = read(traceFD, trace_data, 4096);
743 if (bytes_read > 0) {
744 write(STDOUT_FILENO, trace_data, bytes_read);
745 fflush(stdout);
746 } else {
747 if (!g_traceAborted) {
748 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
749 bytes_read, errno, strerror(errno));
750 }
751 break;
752 }
753 }
754}
755
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800756// Read the current kernel trace and write it to stdout.
757static void dumpTrace()
758{
759 int traceFD = open(k_tracePath, O_RDWR);
760 if (traceFD == -1) {
761 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
762 strerror(errno), errno);
763 return;
764 }
765
766 if (g_compress) {
767 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800768 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700769
770 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800771 if (result != Z_OK) {
772 fprintf(stderr, "error initializing zlib: %d\n", result);
773 close(traceFD);
774 return;
775 }
776
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700777 constexpr size_t bufSize = 64*1024;
778 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
779 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
780 if (!in || !out) {
781 fprintf(stderr, "couldn't allocate buffers\n");
782 close(traceFD);
783 return;
784 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800785
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700786 int flush = Z_NO_FLUSH;
787
788 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800789 zs.avail_out = bufSize;
790
791 do {
792
793 if (zs.avail_in == 0) {
794 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700795 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800796 if (result < 0) {
797 fprintf(stderr, "error reading trace: %s (%d)\n",
798 strerror(errno), errno);
799 result = Z_STREAM_END;
800 break;
801 } else if (result == 0) {
802 flush = Z_FINISH;
803 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700804 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800805 zs.avail_in = result;
806 }
807 }
808
809 if (zs.avail_out == 0) {
810 // Need to write the output.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700811 result = write(STDOUT_FILENO, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800812 if ((size_t)result < bufSize) {
813 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
814 strerror(errno), errno);
815 result = Z_STREAM_END; // skip deflate error message
816 zs.avail_out = bufSize; // skip the final write
817 break;
818 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700819 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800820 zs.avail_out = bufSize;
821 }
822
823 } while ((result = deflate(&zs, flush)) == Z_OK);
824
825 if (result != Z_STREAM_END) {
826 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
827 }
828
829 if (zs.avail_out < bufSize) {
830 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700831 result = write(STDOUT_FILENO, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800832 if ((size_t)result < bytes) {
833 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
834 strerror(errno), errno);
835 }
836 }
837
838 result = deflateEnd(&zs);
839 if (result != Z_OK) {
840 fprintf(stderr, "error cleaning up zlib: %d\n", result);
841 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800842 } else {
843 ssize_t sent = 0;
844 while ((sent = sendfile(STDOUT_FILENO, traceFD, NULL, 64*1024*1024)) > 0);
845 if (sent == -1) {
846 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
847 errno);
848 }
849 }
850
851 close(traceFD);
852}
853
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700854static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800855{
856 if (!g_nohup) {
857 g_traceAborted = true;
858 }
859}
860
861static void registerSigHandler()
862{
863 struct sigaction sa;
864 sigemptyset(&sa.sa_mask);
865 sa.sa_flags = 0;
866 sa.sa_handler = handleSignal;
867 sigaction(SIGHUP, &sa, NULL);
868 sigaction(SIGINT, &sa, NULL);
869 sigaction(SIGQUIT, &sa, NULL);
870 sigaction(SIGTERM, &sa, NULL);
871}
872
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800873static void listSupportedCategories()
874{
875 for (int i = 0; i < NELEM(k_categories); i++) {
876 const TracingCategory& c = k_categories[i];
877 if (isCategorySupported(c)) {
878 printf(" %10s - %s\n", c.name, c.longname);
879 }
880 }
881}
882
883// Print the command usage help to stderr.
884static void showHelp(const char *cmd)
885{
886 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
887 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700888 " -a appname enable app-level tracing for a comma "
889 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800890 " -b N use a trace buffer size of N KB\n"
891 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900892 " -f filename use the categories written in a file as space-separated\n"
893 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700894 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800895 " -n ignore signals\n"
896 " -s N sleep for N seconds before tracing [default 0]\n"
897 " -t N trace for N seconds [defualt 5]\n"
898 " -z compress the trace dump\n"
899 " --async_start start circular trace and return immediatly\n"
900 " --async_dump dump the current contents of circular trace buffer\n"
901 " --async_stop stop tracing and dump the current contents of circular\n"
902 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +0100903 " --stream stream trace to stdout as it enters the trace buffer\n"
904 " Note: this can take significant CPU time, and is best\n"
905 " used for measuring things that are not affected by\n"
906 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -0800907 " --list_categories\n"
908 " list the available tracing categories\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800909 );
910}
911
912int main(int argc, char **argv)
913{
914 bool async = false;
915 bool traceStart = true;
916 bool traceStop = true;
917 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +0100918 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800919
920 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
921 showHelp(argv[0]);
922 exit(0);
923 }
924
925 for (;;) {
926 int ret;
927 int option_index = 0;
928 static struct option long_options[] = {
929 {"async_start", no_argument, 0, 0 },
930 {"async_stop", no_argument, 0, 0 },
931 {"async_dump", no_argument, 0, 0 },
932 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +0100933 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800934 { 0, 0, 0, 0 }
935 };
936
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900937 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:z",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800938 long_options, &option_index);
939
940 if (ret < 0) {
941 for (int i = optind; i < argc; i++) {
942 if (!setCategoryEnable(argv[i], true)) {
943 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
944 exit(1);
945 }
946 }
947 break;
948 }
949
950 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700951 case 'a':
952 g_debugAppCmdLine = optarg;
953 break;
954
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800955 case 'b':
956 g_traceBufferSizeKB = atoi(optarg);
957 break;
958
959 case 'c':
960 g_traceOverwrite = true;
961 break;
962
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900963 case 'f':
964 g_categoriesFile = optarg;
965 break;
966
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700967 case 'k':
968 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700969 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700970
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800971 case 'n':
972 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700973 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800974
975 case 's':
976 g_initialSleepSecs = atoi(optarg);
977 break;
978
979 case 't':
980 g_traceDurationSeconds = atoi(optarg);
981 break;
982
983 case 'z':
984 g_compress = true;
985 break;
986
987 case 0:
988 if (!strcmp(long_options[option_index].name, "async_start")) {
989 async = true;
990 traceStop = false;
991 traceDump = false;
992 g_traceOverwrite = true;
993 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
994 async = true;
John Reck4ba2b632015-05-15 10:00:34 -0700995 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800996 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
997 async = true;
998 traceStart = false;
999 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001000 } else if (!strcmp(long_options[option_index].name, "stream")) {
1001 traceStream = true;
1002 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001003 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1004 listSupportedCategories();
1005 exit(0);
1006 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001007 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001008
1009 default:
1010 fprintf(stderr, "\n");
1011 showHelp(argv[0]);
1012 exit(-1);
1013 break;
1014 }
1015 }
1016
1017 registerSigHandler();
1018
1019 if (g_initialSleepSecs > 0) {
1020 sleep(g_initialSleepSecs);
1021 }
1022
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001023 bool ok = true;
1024 ok &= setUpTrace();
1025 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001026
1027 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001028 if (!traceStream) {
1029 printf("capturing trace...");
1030 fflush(stdout);
1031 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001032
1033 // We clear the trace after starting it because tracing gets enabled for
1034 // each CPU individually in the kernel. Having the beginning of the trace
1035 // contain entries from only one CPU can cause "begin" entries without a
1036 // matching "end" entry to show up if a task gets migrated from one CPU to
1037 // another.
1038 ok = clearTrace();
1039
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001040 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001041 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001042 // Sleep to allow the trace to be captured.
1043 struct timespec timeLeft;
1044 timeLeft.tv_sec = g_traceDurationSeconds;
1045 timeLeft.tv_nsec = 0;
1046 do {
1047 if (g_traceAborted) {
1048 break;
1049 }
1050 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1051 }
Martijn Coenend9535872015-11-26 10:00:55 +01001052
1053 if (traceStream) {
1054 streamTrace();
1055 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001056 }
1057
1058 // Stop the trace and restore the default settings.
1059 if (traceStop)
1060 stopTrace();
1061
1062 if (ok && traceDump) {
1063 if (!g_traceAborted) {
1064 printf(" done\nTRACE:\n");
1065 fflush(stdout);
1066 dumpTrace();
1067 } else {
1068 printf("\ntrace aborted.\n");
1069 fflush(stdout);
1070 }
1071 clearTrace();
1072 } else if (!ok) {
1073 fprintf(stderr, "unable to start tracing\n");
1074 }
1075
1076 // Reset the trace buffer size to 1.
1077 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001078 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001079
1080 return g_traceAborted ? 1 : 0;
1081}