blob: 29cf2a4257b9e25df4efdf7301aeda3d79dafba7 [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
Elliott Hughesa252f4d2016-07-21 17:12:15 -070034#include <memory>
35
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080036#include <binder/IBinder.h>
37#include <binder/IServiceManager.h>
38#include <binder/Parcel.h>
39
40#include <cutils/properties.h>
41
42#include <utils/String8.h>
John Reck469a1942015-03-26 15:31:35 -070043#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +090044#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080045#include <utils/Trace.h>
Stephane Gasparinid8419c22016-03-02 13:45:15 +010046#include <android-base/file.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080047
48using namespace android;
49
50#define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0])))
51
sergeyv4144eff2016-04-28 11:40:04 -070052#define MAX_SYS_FILES 10
53#define MAX_PACKAGES 16
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080054
55const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
sergeyv4144eff2016-04-28 11:40:04 -070056
57const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
58const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070059const char* k_coreServiceCategory = "core_services";
60const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080061
62typedef enum { OPT, REQ } requiredness ;
63
64struct TracingCategory {
65 // The name identifying the category.
66 const char* name;
67
68 // A longer description of the category.
69 const char* longname;
70
71 // The userland tracing tags that the category enables.
72 uint64_t tags;
73
74 // The fname==NULL terminated list of /sys/ files that the category
75 // enables.
76 struct {
77 // Whether the file must be writable in order to enable the tracing
78 // category.
79 requiredness required;
80
81 // The path to the enable file.
82 const char* path;
83 } sysfiles[MAX_SYS_FILES];
84};
85
86/* Tracing categories */
87static const TracingCategory k_categories[] = {
Jamie Gennisb2a89e32013-03-11 19:37:53 -070088 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, { } },
89 { "input", "Input", ATRACE_TAG_INPUT, { } },
90 { "view", "View System", ATRACE_TAG_VIEW, { } },
91 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
92 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
93 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -050094 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070095 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
96 { "video", "Video", ATRACE_TAG_VIDEO, { } },
97 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
98 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -070099 { "app", "Application", ATRACE_TAG_APP, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -0700100 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -0700101 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -0700102 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -0700103 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700104 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 14:36:20 -0700105 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-07-01 01:46:25 +0900106 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Greg Hackmannbbd7d992014-12-01 14:43:34 -0800107 { "database", "Database", ATRACE_TAG_DATABASE, { } },
sergeyvdb404152016-05-02 19:26:07 -0700108 { k_coreServiceCategory, "Core services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700109 { "sched", "CPU Scheduling", 0, {
110 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_switch/enable" },
111 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_wakeup/enable" },
Riley Andrews5672bb72015-11-19 13:31:17 -0800112 { OPT, "/sys/kernel/debug/tracing/events/sched/sched_blocked_reason/enable" },
Ruchi Kandoicfe500d2015-11-23 13:47:20 -0800113 { OPT, "/sys/kernel/debug/tracing/events/sched/sched_cpu_hotplug/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800114 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700115 { "irq", "IRQ Events", 0, {
116 { REQ, "/sys/kernel/debug/tracing/events/irq/enable" },
Riley Andrews412e4f62015-11-02 21:01:34 -0800117 { OPT, "/sys/kernel/debug/tracing/events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700118 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100119 { "i2c", "I2C Events", 0, {
120 { REQ, "/sys/kernel/debug/tracing/events/i2c/enable" },
121 { REQ, "/sys/kernel/debug/tracing/events/i2c/i2c_read/enable" },
122 { REQ, "/sys/kernel/debug/tracing/events/i2c/i2c_write/enable" },
123 { REQ, "/sys/kernel/debug/tracing/events/i2c/i2c_result/enable" },
124 { REQ, "/sys/kernel/debug/tracing/events/i2c/i2c_reply/enable" },
125 { OPT, "/sys/kernel/debug/tracing/events/i2c/smbus_read/enable" },
126 { OPT, "/sys/kernel/debug/tracing/events/i2c/smbus_write/enable" },
127 { OPT, "/sys/kernel/debug/tracing/events/i2c/smbus_result/enable" },
128 { OPT, "/sys/kernel/debug/tracing/events/i2c/smbus_reply/enable" },
129 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700130 { "freq", "CPU Frequency", 0, {
131 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_frequency/enable" },
132 { OPT, "/sys/kernel/debug/tracing/events/power/clock_set_rate/enable" },
Ruchi Kandoiffcc7112015-11-19 18:32:00 -0800133 { OPT, "/sys/kernel/debug/tracing/events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800134 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700135 { "membus", "Memory Bus Utilization", 0, {
136 { REQ, "/sys/kernel/debug/tracing/events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800137 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700138 { "idle", "CPU Idle", 0, {
139 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800140 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700141 { "disk", "Disk I/O", 0, {
Greg Hackmanne80d32c2014-11-20 12:59:44 -0800142 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_enter/enable" },
143 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_exit/enable" },
144 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_begin/enable" },
145 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_end/enable" },
146 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_begin/enable" },
147 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_end/enable" },
148 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable" },
149 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable" },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700150 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" },
151 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800152 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700153 { "mmc", "eMMC commands", 0, {
154 { REQ, "/sys/kernel/debug/tracing/events/mmc/enable" },
155 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700156 { "load", "CPU Load", 0, {
157 { REQ, "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800158 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700159 { "sync", "Synchronization", 0, {
160 { REQ, "/sys/kernel/debug/tracing/events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800161 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700162 { "workq", "Kernel Workqueues", 0, {
163 { REQ, "/sys/kernel/debug/tracing/events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800164 } },
Colin Cross580407f2014-08-18 15:22:13 -0700165 { "memreclaim", "Kernel Memory Reclaim", 0, {
166 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
167 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
168 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_wake/enable" },
169 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_sleep/enable" },
170 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800171 { "regulators", "Voltage and Current Regulators", 0, {
172 { REQ, "/sys/kernel/debug/tracing/events/regulator/enable" },
173 } },
Scott Bauerae473362015-06-08 16:32:36 -0700174 { "binder_driver", "Binder Kernel driver", 0, {
175 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction/enable" },
176 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction_received/enable" },
177 } },
178 { "binder_lock", "Binder global lock trace", 0, {
179 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_lock/enable" },
180 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_locked/enable" },
181 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_unlock/enable" },
182 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200183 { "pagecache", "Page cache", 0, {
184 { REQ, "/sys/kernel/debug/tracing/events/filemap/enable" },
185 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800186};
187
188/* Command line options */
189static int g_traceDurationSeconds = 5;
190static bool g_traceOverwrite = false;
191static int g_traceBufferSizeKB = 2048;
192static bool g_compress = false;
193static bool g_nohup = false;
194static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900195static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700196static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700197static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700198static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800199
200/* Global state */
201static bool g_traceAborted = false;
202static bool g_categoryEnables[NELEM(k_categories)] = {};
203
204/* Sys file paths */
205static const char* k_traceClockPath =
206 "/sys/kernel/debug/tracing/trace_clock";
207
208static const char* k_traceBufferSizePath =
209 "/sys/kernel/debug/tracing/buffer_size_kb";
210
211static const char* k_tracingOverwriteEnablePath =
212 "/sys/kernel/debug/tracing/options/overwrite";
213
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700214static const char* k_currentTracerPath =
215 "/sys/kernel/debug/tracing/current_tracer";
216
217static const char* k_printTgidPath =
218 "/sys/kernel/debug/tracing/options/print-tgid";
219
220static const char* k_funcgraphAbsTimePath =
221 "/sys/kernel/debug/tracing/options/funcgraph-abstime";
222
223static const char* k_funcgraphCpuPath =
224 "/sys/kernel/debug/tracing/options/funcgraph-cpu";
225
226static const char* k_funcgraphProcPath =
227 "/sys/kernel/debug/tracing/options/funcgraph-proc";
228
229static const char* k_funcgraphFlatPath =
230 "/sys/kernel/debug/tracing/options/funcgraph-flat";
231
232static const char* k_funcgraphDurationPath =
233 "/sys/kernel/debug/tracing/options/funcgraph-duration";
234
235static const char* k_ftraceFilterPath =
236 "/sys/kernel/debug/tracing/set_ftrace_filter";
237
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800238static const char* k_tracingOnPath =
239 "/sys/kernel/debug/tracing/tracing_on";
240
241static const char* k_tracePath =
242 "/sys/kernel/debug/tracing/trace";
243
Martijn Coenend9535872015-11-26 10:00:55 +0100244static const char* k_traceStreamPath =
245 "/sys/kernel/debug/tracing/trace_pipe";
246
John Reck469a1942015-03-26 15:31:35 -0700247static const char* k_traceMarkerPath =
248 "/sys/kernel/debug/tracing/trace_marker";
249
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800250// Check whether a file exists.
251static bool fileExists(const char* filename) {
252 return access(filename, F_OK) != -1;
253}
254
255// Check whether a file is writable.
256static bool fileIsWritable(const char* filename) {
257 return access(filename, W_OK) != -1;
258}
259
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700260// Truncate a file.
261static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800262{
Jamie Gennis43122e72013-03-21 14:06:31 -0700263 // This uses creat rather than truncate because some of the debug kernel
264 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
265 // calls to truncate, but they are cleared by calls to creat.
266 int traceFD = creat(path, 0);
267 if (traceFD == -1) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700268 fprintf(stderr, "error truncating %s: %s (%d)\n", path,
Jamie Gennis43122e72013-03-21 14:06:31 -0700269 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700270 return false;
271 }
272
Jamie Gennis43122e72013-03-21 14:06:31 -0700273 close(traceFD);
274
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700275 return true;
276}
277
278static bool _writeStr(const char* filename, const char* str, int flags)
279{
280 int fd = open(filename, flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800281 if (fd == -1) {
282 fprintf(stderr, "error opening %s: %s (%d)\n", filename,
283 strerror(errno), errno);
284 return false;
285 }
286
287 bool ok = true;
288 ssize_t len = strlen(str);
289 if (write(fd, str, len) != len) {
290 fprintf(stderr, "error writing to %s: %s (%d)\n", filename,
291 strerror(errno), errno);
292 ok = false;
293 }
294
295 close(fd);
296
297 return ok;
298}
299
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700300// Write a string to a file, returning true if the write was successful.
301static bool writeStr(const char* filename, const char* str)
302{
303 return _writeStr(filename, str, O_WRONLY);
304}
305
306// Append a string to a file, returning true if the write was successful.
307static bool appendStr(const char* filename, const char* str)
308{
309 return _writeStr(filename, str, O_APPEND|O_WRONLY);
310}
311
John Reck469a1942015-03-26 15:31:35 -0700312static void writeClockSyncMarker()
313{
314 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200315 int len = 0;
316 int fd = open(k_traceMarkerPath, O_WRONLY);
317 if (fd == -1) {
318 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
319 strerror(errno), errno);
320 return;
321 }
John Reck469a1942015-03-26 15:31:35 -0700322 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200323
324 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
325 if (write(fd, buffer, len) != len) {
326 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
327 }
328
329 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
330 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
331 if (write(fd, buffer, len) != len) {
332 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
333 }
334
335 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700336}
337
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800338// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
339// file.
340static bool setKernelOptionEnable(const char* filename, bool enable)
341{
342 return writeStr(filename, enable ? "1" : "0");
343}
344
345// Check whether the category is supported on the device with the current
346// rootness. A category is supported only if all its required /sys/ files are
347// writable and if enabling the category will enable one or more tracing tags
348// or /sys/ files.
349static bool isCategorySupported(const TracingCategory& category)
350{
sergeyvdb404152016-05-02 19:26:07 -0700351 if (strcmp(category.name, k_coreServiceCategory) == 0) {
352 char value[PROPERTY_VALUE_MAX];
353 property_get(k_coreServicesProp, value, "");
354 return strlen(value) != 0;
355 }
356
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800357 bool ok = category.tags != 0;
358 for (int i = 0; i < MAX_SYS_FILES; i++) {
359 const char* path = category.sysfiles[i].path;
360 bool req = category.sysfiles[i].required == REQ;
361 if (path != NULL) {
362 if (req) {
363 if (!fileIsWritable(path)) {
364 return false;
365 } else {
366 ok = true;
367 }
368 } else {
369 ok |= fileIsWritable(path);
370 }
371 }
372 }
373 return ok;
374}
375
376// Check whether the category would be supported on the device if the user
377// were root. This function assumes that root is able to write to any file
378// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700379// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800380static bool isCategorySupportedForRoot(const TracingCategory& category)
381{
382 bool ok = category.tags != 0;
383 for (int i = 0; i < MAX_SYS_FILES; i++) {
384 const char* path = category.sysfiles[i].path;
385 bool req = category.sysfiles[i].required == REQ;
386 if (path != NULL) {
387 if (req) {
388 if (!fileExists(path)) {
389 return false;
390 } else {
391 ok = true;
392 }
393 } else {
394 ok |= fileExists(path);
395 }
396 }
397 }
398 return ok;
399}
400
401// Enable or disable overwriting of the kernel trace buffers. Disabling this
402// will cause tracing to stop once the trace buffers have filled up.
403static bool setTraceOverwriteEnable(bool enable)
404{
405 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
406}
407
408// Enable or disable kernel tracing.
409static bool setTracingEnabled(bool enable)
410{
411 return setKernelOptionEnable(k_tracingOnPath, enable);
412}
413
414// Clear the contents of the kernel trace.
415static bool clearTrace()
416{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700417 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800418}
419
420// Set the size of the kernel's trace buffer in kilobytes.
421static bool setTraceBufferSizeKB(int size)
422{
423 char str[32] = "1";
424 int len;
425 if (size < 1) {
426 size = 1;
427 }
428 snprintf(str, 32, "%d", size);
429 return writeStr(k_traceBufferSizePath, str);
430}
431
Colin Crossb1ce49b2014-08-20 14:28:47 -0700432// Read the trace_clock sysfs file and return true if it matches the requested
433// value. The trace_clock file format is:
434// local [global] counter uptime perf
435static bool isTraceClock(const char *mode)
436{
437 int fd = open(k_traceClockPath, O_RDONLY);
438 if (fd == -1) {
439 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceClockPath,
440 strerror(errno), errno);
441 return false;
442 }
443
444 char buf[4097];
445 ssize_t n = read(fd, buf, 4096);
446 close(fd);
447 if (n == -1) {
448 fprintf(stderr, "error reading %s: %s (%d)\n", k_traceClockPath,
449 strerror(errno), errno);
450 return false;
451 }
452 buf[n] = '\0';
453
454 char *start = strchr(buf, '[');
455 if (start == NULL) {
456 return false;
457 }
458 start++;
459
460 char *end = strchr(start, ']');
461 if (end == NULL) {
462 return false;
463 }
464 *end = '\0';
465
466 return strcmp(mode, start) == 0;
467}
468
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800469// Enable or disable the kernel's use of the global clock. Disabling the global
470// clock will result in the kernel using a per-CPU local clock.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700471// Any write to the trace_clock sysfs file will reset the buffer, so only
472// update it if the requested value is not the current value.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800473static bool setGlobalClockEnable(bool enable)
474{
Colin Crossb1ce49b2014-08-20 14:28:47 -0700475 const char *clock = enable ? "global" : "local";
476
477 if (isTraceClock(clock)) {
478 return true;
479 }
480
481 return writeStr(k_traceClockPath, clock);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800482}
483
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700484static bool setPrintTgidEnableIfPresent(bool enable)
485{
486 if (fileExists(k_printTgidPath)) {
487 return setKernelOptionEnable(k_printTgidPath, enable);
488 }
489 return true;
490}
491
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800492// Poke all the binder-enabled processes in the system to get them to re-read
493// their system properties.
494static bool pokeBinderServices()
495{
496 sp<IServiceManager> sm = defaultServiceManager();
497 Vector<String16> services = sm->listServices();
498 for (size_t i = 0; i < services.size(); i++) {
499 sp<IBinder> obj = sm->checkService(services[i]);
500 if (obj != NULL) {
501 Parcel data;
502 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
503 NULL, 0) != OK) {
504 if (false) {
505 // XXX: For some reason this fails on tablets trying to
506 // poke the "phone" service. It's not clear whether some
507 // are expected to fail.
508 String8 svc(services[i]);
509 fprintf(stderr, "error poking binder service %s\n",
510 svc.string());
511 return false;
512 }
513 }
514 }
515 }
516 return true;
517}
518
519// Set the trace tags that userland tracing uses, and poke the running
520// processes to pick up the new value.
521static bool setTagsProperty(uint64_t tags)
522{
sergeyv4144eff2016-04-28 11:40:04 -0700523 char buf[PROPERTY_VALUE_MAX];
524 snprintf(buf, sizeof(buf), "%#" PRIx64, tags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800525 if (property_set(k_traceTagsProperty, buf) < 0) {
526 fprintf(stderr, "error setting trace tags system property\n");
527 return false;
528 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700529 return true;
530}
531
sergeyv4144eff2016-04-28 11:40:04 -0700532static void clearAppProperties()
533{
534 char buf[PROPERTY_KEY_MAX];
535 for (int i = 0; i < MAX_PACKAGES; i++) {
536 snprintf(buf, sizeof(buf), k_traceAppsPropertyTemplate, i);
537 if (property_set(buf, "") < 0) {
538 fprintf(stderr, "failed to clear system property: %s\n", buf);
539 }
540 }
541 if (property_set(k_traceAppsNumberProperty, "") < 0) {
542 fprintf(stderr, "failed to clear system property: %s",
543 k_traceAppsNumberProperty);
544 }
545}
546
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700547// Set the system property that indicates which apps should perform
548// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700549static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700550{
sergeyv4144eff2016-04-28 11:40:04 -0700551 char buf[PROPERTY_KEY_MAX];
552 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700553 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700554 while (start != NULL) {
555 if (i == MAX_PACKAGES) {
556 fprintf(stderr, "error: only 16 packages could be traced at once\n");
557 clearAppProperties();
558 return false;
559 }
560 char* end = strchr(start, ',');
561 if (end != NULL) {
562 *end = '\0';
563 end++;
564 }
565 snprintf(buf, sizeof(buf), k_traceAppsPropertyTemplate, i);
566 if (property_set(buf, start) < 0) {
567 fprintf(stderr, "error setting trace app %d property to %s\n", i, buf);
568 clearAppProperties();
569 return false;
570 }
571 start = end;
572 i++;
573 }
574
575 snprintf(buf, sizeof(buf), "%d", i);
576 if (property_set(k_traceAppsNumberProperty, buf) < 0) {
577 fprintf(stderr, "error setting trace app number property to %s\n", buf);
578 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700579 return false;
580 }
581 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800582}
583
584// Disable all /sys/ enable files.
585static bool disableKernelTraceEvents() {
586 bool ok = true;
587 for (int i = 0; i < NELEM(k_categories); i++) {
588 const TracingCategory &c = k_categories[i];
589 for (int j = 0; j < MAX_SYS_FILES; j++) {
590 const char* path = c.sysfiles[j].path;
591 if (path != NULL && fileIsWritable(path)) {
592 ok &= setKernelOptionEnable(path, false);
593 }
594 }
595 }
596 return ok;
597}
598
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700599// Verify that the comma separated list of functions are being traced by the
600// kernel.
601static bool verifyKernelTraceFuncs(const char* funcs)
602{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100603 std::string buf;
604 if (!android::base::ReadFileToString(k_ftraceFilterPath, &buf)) {
605 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700606 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100607 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700608 }
609
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100610 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700611
612 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100613 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700614 bool ok = true;
615 char* myFuncs = strdup(funcs);
616 char* func = strtok(myFuncs, ",");
617 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100618 if (!strchr(func, '*')) {
619 String8 fancyFunc = String8::format("\n%s\n", func);
620 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
621 if (!found || func[0] == '\0') {
622 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
623 "to trace.\n", func);
624 ok = false;
625 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700626 }
627 func = strtok(NULL, ",");
628 }
629 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700630 return ok;
631}
632
633// Set the comma separated list of functions that the kernel is to trace.
634static bool setKernelTraceFuncs(const char* funcs)
635{
636 bool ok = true;
637
638 if (funcs == NULL || funcs[0] == '\0') {
639 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700640 if (fileIsWritable(k_currentTracerPath)) {
641 ok &= writeStr(k_currentTracerPath, "nop");
642 }
643 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700644 ok &= truncateFile(k_ftraceFilterPath);
645 }
646 } else {
647 // Enable kernel function tracing.
648 ok &= writeStr(k_currentTracerPath, "function_graph");
649 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
650 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
651 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
652 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
653
654 // Set the requested filter functions.
655 ok &= truncateFile(k_ftraceFilterPath);
656 char* myFuncs = strdup(funcs);
657 char* func = strtok(myFuncs, ",");
658 while (func) {
659 ok &= appendStr(k_ftraceFilterPath, func);
660 func = strtok(NULL, ",");
661 }
662 free(myFuncs);
663
664 // Verify that the set functions are being traced.
665 if (ok) {
666 ok &= verifyKernelTraceFuncs(funcs);
667 }
668 }
669
670 return ok;
671}
672
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900673static bool setCategoryEnable(const char* name, bool enable)
674{
675 for (int i = 0; i < NELEM(k_categories); i++) {
676 const TracingCategory& c = k_categories[i];
677 if (strcmp(name, c.name) == 0) {
678 if (isCategorySupported(c)) {
679 g_categoryEnables[i] = enable;
680 return true;
681 } else {
682 if (isCategorySupportedForRoot(c)) {
683 fprintf(stderr, "error: category \"%s\" requires root "
684 "privileges.\n", name);
685 } else {
686 fprintf(stderr, "error: category \"%s\" is not supported "
687 "on this device.\n", name);
688 }
689 return false;
690 }
691 }
692 }
693 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
694 return false;
695}
696
697static bool setCategoriesEnableFromFile(const char* categories_file)
698{
699 if (!categories_file) {
700 return true;
701 }
702 Tokenizer* tokenizer = NULL;
703 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
704 return false;
705 }
706 bool ok = true;
707 while (!tokenizer->isEol()) {
708 String8 token = tokenizer->nextToken(" ");
709 if (token.isEmpty()) {
710 tokenizer->skipDelimiters(" ");
711 continue;
712 }
713 ok &= setCategoryEnable(token.string(), true);
714 }
715 delete tokenizer;
716 return ok;
717}
718
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700719// Set all the kernel tracing settings to the desired state for this trace
720// capture.
721static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800722{
723 bool ok = true;
724
725 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900726 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800727 ok &= setTraceOverwriteEnable(g_traceOverwrite);
728 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
729 ok &= setGlobalClockEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700730 ok &= setPrintTgidEnableIfPresent(true);
731 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800732
733 // Set up the tags property.
734 uint64_t tags = 0;
735 for (int i = 0; i < NELEM(k_categories); i++) {
736 if (g_categoryEnables[i]) {
737 const TracingCategory &c = k_categories[i];
738 tags |= c.tags;
739 }
740 }
741 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700742
743 bool coreServicesTagEnabled = false;
744 for (int i = 0; i < NELEM(k_categories); i++) {
745 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
746 coreServicesTagEnabled = g_categoryEnables[i];
747 }
748 }
749
750 std::string packageList(g_debugAppCmdLine);
751 if (coreServicesTagEnabled) {
752 char value[PROPERTY_VALUE_MAX];
753 property_get(k_coreServicesProp, value, "");
754 if (!packageList.empty()) {
755 packageList += ",";
756 }
757 packageList += value;
758 }
Dan Austin09a79872016-05-31 13:27:03 -0700759 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700760 ok &= pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800761
762 // Disable all the sysfs enables. This is done as a separate loop from
763 // the enables to allow the same enable to exist in multiple categories.
764 ok &= disableKernelTraceEvents();
765
766 // Enable all the sysfs enables that are in an enabled category.
767 for (int i = 0; i < NELEM(k_categories); i++) {
768 if (g_categoryEnables[i]) {
769 const TracingCategory &c = k_categories[i];
770 for (int j = 0; j < MAX_SYS_FILES; j++) {
771 const char* path = c.sysfiles[j].path;
772 bool required = c.sysfiles[j].required == REQ;
773 if (path != NULL) {
774 if (fileIsWritable(path)) {
775 ok &= setKernelOptionEnable(path, true);
776 } else if (required) {
777 fprintf(stderr, "error writing file %s\n", path);
778 ok = false;
779 }
780 }
781 }
782 }
783 }
784
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800785 return ok;
786}
787
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700788// Reset all the kernel tracing settings to their default state.
789static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800790{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800791 // Disable all tracing that we're able to.
792 disableKernelTraceEvents();
793
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700794 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800795 setTagsProperty(0);
sergeyv4144eff2016-04-28 11:40:04 -0700796 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700797 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800798
799 // Set the options back to their defaults.
800 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700801 setTraceBufferSizeKB(1);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800802 setGlobalClockEnable(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700803 setPrintTgidEnableIfPresent(false);
804 setKernelTraceFuncs(NULL);
805}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800806
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700807
808// Enable tracing in the kernel.
809static bool startTrace()
810{
811 return setTracingEnabled(true);
812}
813
814// Disable tracing in the kernel.
815static void stopTrace()
816{
817 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800818}
819
Martijn Coenend9535872015-11-26 10:00:55 +0100820// Read data from the tracing pipe and forward to stdout
821static void streamTrace()
822{
823 char trace_data[4096];
824 int traceFD = open(k_traceStreamPath, O_RDWR);
825 if (traceFD == -1) {
826 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
827 strerror(errno), errno);
828 return;
829 }
830 while (!g_traceAborted) {
831 ssize_t bytes_read = read(traceFD, trace_data, 4096);
832 if (bytes_read > 0) {
833 write(STDOUT_FILENO, trace_data, bytes_read);
834 fflush(stdout);
835 } else {
836 if (!g_traceAborted) {
837 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
838 bytes_read, errno, strerror(errno));
839 }
840 break;
841 }
842 }
843}
844
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800845// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700846static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800847{
John Reck6c8ac922016-03-28 11:25:30 -0700848 ALOGI("Dumping trace");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800849 int traceFD = open(k_tracePath, O_RDWR);
850 if (traceFD == -1) {
851 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
852 strerror(errno), errno);
853 return;
854 }
855
856 if (g_compress) {
857 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800858 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700859
860 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800861 if (result != Z_OK) {
862 fprintf(stderr, "error initializing zlib: %d\n", result);
863 close(traceFD);
864 return;
865 }
866
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700867 constexpr size_t bufSize = 64*1024;
868 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
869 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
870 if (!in || !out) {
871 fprintf(stderr, "couldn't allocate buffers\n");
872 close(traceFD);
873 return;
874 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800875
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700876 int flush = Z_NO_FLUSH;
877
878 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800879 zs.avail_out = bufSize;
880
881 do {
882
883 if (zs.avail_in == 0) {
884 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700885 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800886 if (result < 0) {
887 fprintf(stderr, "error reading trace: %s (%d)\n",
888 strerror(errno), errno);
889 result = Z_STREAM_END;
890 break;
891 } else if (result == 0) {
892 flush = Z_FINISH;
893 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700894 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800895 zs.avail_in = result;
896 }
897 }
898
899 if (zs.avail_out == 0) {
900 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700901 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800902 if ((size_t)result < bufSize) {
903 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
904 strerror(errno), errno);
905 result = Z_STREAM_END; // skip deflate error message
906 zs.avail_out = bufSize; // skip the final write
907 break;
908 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700909 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800910 zs.avail_out = bufSize;
911 }
912
913 } while ((result = deflate(&zs, flush)) == Z_OK);
914
915 if (result != Z_STREAM_END) {
916 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
917 }
918
919 if (zs.avail_out < bufSize) {
920 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -0700921 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800922 if ((size_t)result < bytes) {
923 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
924 strerror(errno), errno);
925 }
926 }
927
928 result = deflateEnd(&zs);
929 if (result != Z_OK) {
930 fprintf(stderr, "error cleaning up zlib: %d\n", result);
931 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800932 } else {
933 ssize_t sent = 0;
John Reck40b26b42016-03-30 09:44:36 -0700934 while ((sent = sendfile(outFd, traceFD, NULL, 64*1024*1024)) > 0);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800935 if (sent == -1) {
936 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
937 errno);
938 }
939 }
940
941 close(traceFD);
942}
943
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700944static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800945{
946 if (!g_nohup) {
947 g_traceAborted = true;
948 }
949}
950
951static void registerSigHandler()
952{
953 struct sigaction sa;
954 sigemptyset(&sa.sa_mask);
955 sa.sa_flags = 0;
956 sa.sa_handler = handleSignal;
957 sigaction(SIGHUP, &sa, NULL);
958 sigaction(SIGINT, &sa, NULL);
959 sigaction(SIGQUIT, &sa, NULL);
960 sigaction(SIGTERM, &sa, NULL);
961}
962
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800963static void listSupportedCategories()
964{
965 for (int i = 0; i < NELEM(k_categories); i++) {
966 const TracingCategory& c = k_categories[i];
967 if (isCategorySupported(c)) {
968 printf(" %10s - %s\n", c.name, c.longname);
969 }
970 }
971}
972
973// Print the command usage help to stderr.
974static void showHelp(const char *cmd)
975{
976 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
977 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700978 " -a appname enable app-level tracing for a comma "
979 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800980 " -b N use a trace buffer size of N KB\n"
981 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900982 " -f filename use the categories written in a file as space-separated\n"
983 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700984 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800985 " -n ignore signals\n"
986 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700987 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800988 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700989 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800990 " --async_dump dump the current contents of circular trace buffer\n"
991 " --async_stop stop tracing and dump the current contents of circular\n"
992 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +0100993 " --stream stream trace to stdout as it enters the trace buffer\n"
994 " Note: this can take significant CPU time, and is best\n"
995 " used for measuring things that are not affected by\n"
996 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -0800997 " --list_categories\n"
998 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -0700999 " -o filename write the trace to the specified file instead\n"
1000 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001001 );
1002}
1003
1004int main(int argc, char **argv)
1005{
1006 bool async = false;
1007 bool traceStart = true;
1008 bool traceStop = true;
1009 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001010 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001011
1012 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1013 showHelp(argv[0]);
1014 exit(0);
1015 }
1016
1017 for (;;) {
1018 int ret;
1019 int option_index = 0;
1020 static struct option long_options[] = {
1021 {"async_start", no_argument, 0, 0 },
1022 {"async_stop", no_argument, 0, 0 },
1023 {"async_dump", no_argument, 0, 0 },
1024 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +01001025 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001026 { 0, 0, 0, 0 }
1027 };
1028
John Reck40b26b42016-03-30 09:44:36 -07001029 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001030 long_options, &option_index);
1031
1032 if (ret < 0) {
1033 for (int i = optind; i < argc; i++) {
1034 if (!setCategoryEnable(argv[i], true)) {
1035 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1036 exit(1);
1037 }
1038 }
1039 break;
1040 }
1041
1042 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001043 case 'a':
1044 g_debugAppCmdLine = optarg;
1045 break;
1046
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001047 case 'b':
1048 g_traceBufferSizeKB = atoi(optarg);
1049 break;
1050
1051 case 'c':
1052 g_traceOverwrite = true;
1053 break;
1054
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001055 case 'f':
1056 g_categoriesFile = optarg;
1057 break;
1058
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001059 case 'k':
1060 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001061 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001062
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001063 case 'n':
1064 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001065 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001066
1067 case 's':
1068 g_initialSleepSecs = atoi(optarg);
1069 break;
1070
1071 case 't':
1072 g_traceDurationSeconds = atoi(optarg);
1073 break;
1074
1075 case 'z':
1076 g_compress = true;
1077 break;
1078
John Reck40b26b42016-03-30 09:44:36 -07001079 case 'o':
1080 g_outputFile = optarg;
1081 break;
1082
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001083 case 0:
1084 if (!strcmp(long_options[option_index].name, "async_start")) {
1085 async = true;
1086 traceStop = false;
1087 traceDump = false;
1088 g_traceOverwrite = true;
1089 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1090 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001091 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001092 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1093 async = true;
1094 traceStart = false;
1095 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001096 } else if (!strcmp(long_options[option_index].name, "stream")) {
1097 traceStream = true;
1098 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001099 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1100 listSupportedCategories();
1101 exit(0);
1102 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001103 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001104
1105 default:
1106 fprintf(stderr, "\n");
1107 showHelp(argv[0]);
1108 exit(-1);
1109 break;
1110 }
1111 }
1112
1113 registerSigHandler();
1114
1115 if (g_initialSleepSecs > 0) {
1116 sleep(g_initialSleepSecs);
1117 }
1118
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001119 bool ok = true;
1120 ok &= setUpTrace();
1121 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001122
1123 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001124 if (!traceStream) {
1125 printf("capturing trace...");
1126 fflush(stdout);
1127 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001128
1129 // We clear the trace after starting it because tracing gets enabled for
1130 // each CPU individually in the kernel. Having the beginning of the trace
1131 // contain entries from only one CPU can cause "begin" entries without a
1132 // matching "end" entry to show up if a task gets migrated from one CPU to
1133 // another.
1134 ok = clearTrace();
1135
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001136 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001137 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001138 // Sleep to allow the trace to be captured.
1139 struct timespec timeLeft;
1140 timeLeft.tv_sec = g_traceDurationSeconds;
1141 timeLeft.tv_nsec = 0;
1142 do {
1143 if (g_traceAborted) {
1144 break;
1145 }
1146 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1147 }
Martijn Coenend9535872015-11-26 10:00:55 +01001148
1149 if (traceStream) {
1150 streamTrace();
1151 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001152 }
1153
1154 // Stop the trace and restore the default settings.
1155 if (traceStop)
1156 stopTrace();
1157
1158 if (ok && traceDump) {
1159 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001160 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001161 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001162 int outFd = STDOUT_FILENO;
1163 if (g_outputFile) {
George Burgess IV48443342016-05-04 19:42:00 -07001164 outFd = open(g_outputFile, O_WRONLY | O_CREAT, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001165 }
1166 if (outFd == -1) {
1167 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1168 } else {
1169 dprintf(outFd, "TRACE:\n");
1170 dumpTrace(outFd);
1171 if (g_outputFile) {
1172 close(outFd);
1173 }
1174 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001175 } else {
1176 printf("\ntrace aborted.\n");
1177 fflush(stdout);
1178 }
1179 clearTrace();
1180 } else if (!ok) {
1181 fprintf(stderr, "unable to start tracing\n");
1182 }
1183
1184 // Reset the trace buffer size to 1.
1185 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001186 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001187
1188 return g_traceAborted ? 1 : 0;
1189}