blob: 8faf2767584ec38c37c01c846d7d83b7df288f70 [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, { } },
Felipe Leme0f97c1d2016-09-07 11:33:26 -0700108 { "network", "Network", ATRACE_TAG_NETWORK, { } },
sergeyvdb404152016-05-02 19:26:07 -0700109 { k_coreServiceCategory, "Core services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700110 { "sched", "CPU Scheduling", 0, {
111 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_switch/enable" },
112 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_wakeup/enable" },
Riley Andrews5672bb72015-11-19 13:31:17 -0800113 { OPT, "/sys/kernel/debug/tracing/events/sched/sched_blocked_reason/enable" },
Ruchi Kandoicfe500d2015-11-23 13:47:20 -0800114 { OPT, "/sys/kernel/debug/tracing/events/sched/sched_cpu_hotplug/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800115 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700116 { "irq", "IRQ Events", 0, {
117 { REQ, "/sys/kernel/debug/tracing/events/irq/enable" },
Riley Andrews412e4f62015-11-02 21:01:34 -0800118 { OPT, "/sys/kernel/debug/tracing/events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700119 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100120 { "i2c", "I2C Events", 0, {
121 { REQ, "/sys/kernel/debug/tracing/events/i2c/enable" },
122 { REQ, "/sys/kernel/debug/tracing/events/i2c/i2c_read/enable" },
123 { REQ, "/sys/kernel/debug/tracing/events/i2c/i2c_write/enable" },
124 { REQ, "/sys/kernel/debug/tracing/events/i2c/i2c_result/enable" },
125 { REQ, "/sys/kernel/debug/tracing/events/i2c/i2c_reply/enable" },
126 { OPT, "/sys/kernel/debug/tracing/events/i2c/smbus_read/enable" },
127 { OPT, "/sys/kernel/debug/tracing/events/i2c/smbus_write/enable" },
128 { OPT, "/sys/kernel/debug/tracing/events/i2c/smbus_result/enable" },
129 { OPT, "/sys/kernel/debug/tracing/events/i2c/smbus_reply/enable" },
130 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700131 { "freq", "CPU Frequency", 0, {
132 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_frequency/enable" },
133 { OPT, "/sys/kernel/debug/tracing/events/power/clock_set_rate/enable" },
Ruchi Kandoiffcc7112015-11-19 18:32:00 -0800134 { OPT, "/sys/kernel/debug/tracing/events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800135 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700136 { "membus", "Memory Bus Utilization", 0, {
137 { REQ, "/sys/kernel/debug/tracing/events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800138 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700139 { "idle", "CPU Idle", 0, {
140 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800141 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700142 { "disk", "Disk I/O", 0, {
Greg Hackmanne80d32c2014-11-20 12:59:44 -0800143 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_enter/enable" },
144 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_exit/enable" },
145 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_begin/enable" },
146 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_end/enable" },
147 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_begin/enable" },
148 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_end/enable" },
149 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable" },
150 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable" },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700151 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" },
152 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800153 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700154 { "mmc", "eMMC commands", 0, {
155 { REQ, "/sys/kernel/debug/tracing/events/mmc/enable" },
156 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700157 { "load", "CPU Load", 0, {
158 { REQ, "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800159 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700160 { "sync", "Synchronization", 0, {
161 { REQ, "/sys/kernel/debug/tracing/events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800162 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700163 { "workq", "Kernel Workqueues", 0, {
164 { REQ, "/sys/kernel/debug/tracing/events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800165 } },
Colin Cross580407f2014-08-18 15:22:13 -0700166 { "memreclaim", "Kernel Memory Reclaim", 0, {
167 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
168 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
169 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_wake/enable" },
170 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_sleep/enable" },
171 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800172 { "regulators", "Voltage and Current Regulators", 0, {
173 { REQ, "/sys/kernel/debug/tracing/events/regulator/enable" },
174 } },
Scott Bauerae473362015-06-08 16:32:36 -0700175 { "binder_driver", "Binder Kernel driver", 0, {
176 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction/enable" },
177 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction_received/enable" },
178 } },
179 { "binder_lock", "Binder global lock trace", 0, {
180 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_lock/enable" },
181 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_locked/enable" },
182 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_unlock/enable" },
183 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200184 { "pagecache", "Page cache", 0, {
185 { REQ, "/sys/kernel/debug/tracing/events/filemap/enable" },
186 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800187};
188
189/* Command line options */
190static int g_traceDurationSeconds = 5;
191static bool g_traceOverwrite = false;
192static int g_traceBufferSizeKB = 2048;
193static bool g_compress = false;
194static bool g_nohup = false;
195static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900196static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700197static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700198static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700199static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800200
201/* Global state */
202static bool g_traceAborted = false;
203static bool g_categoryEnables[NELEM(k_categories)] = {};
204
205/* Sys file paths */
206static const char* k_traceClockPath =
207 "/sys/kernel/debug/tracing/trace_clock";
208
209static const char* k_traceBufferSizePath =
210 "/sys/kernel/debug/tracing/buffer_size_kb";
211
212static const char* k_tracingOverwriteEnablePath =
213 "/sys/kernel/debug/tracing/options/overwrite";
214
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700215static const char* k_currentTracerPath =
216 "/sys/kernel/debug/tracing/current_tracer";
217
218static const char* k_printTgidPath =
219 "/sys/kernel/debug/tracing/options/print-tgid";
220
221static const char* k_funcgraphAbsTimePath =
222 "/sys/kernel/debug/tracing/options/funcgraph-abstime";
223
224static const char* k_funcgraphCpuPath =
225 "/sys/kernel/debug/tracing/options/funcgraph-cpu";
226
227static const char* k_funcgraphProcPath =
228 "/sys/kernel/debug/tracing/options/funcgraph-proc";
229
230static const char* k_funcgraphFlatPath =
231 "/sys/kernel/debug/tracing/options/funcgraph-flat";
232
233static const char* k_funcgraphDurationPath =
234 "/sys/kernel/debug/tracing/options/funcgraph-duration";
235
236static const char* k_ftraceFilterPath =
237 "/sys/kernel/debug/tracing/set_ftrace_filter";
238
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800239static const char* k_tracingOnPath =
240 "/sys/kernel/debug/tracing/tracing_on";
241
242static const char* k_tracePath =
243 "/sys/kernel/debug/tracing/trace";
244
Martijn Coenend9535872015-11-26 10:00:55 +0100245static const char* k_traceStreamPath =
246 "/sys/kernel/debug/tracing/trace_pipe";
247
John Reck469a1942015-03-26 15:31:35 -0700248static const char* k_traceMarkerPath =
249 "/sys/kernel/debug/tracing/trace_marker";
250
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800251// Check whether a file exists.
252static bool fileExists(const char* filename) {
253 return access(filename, F_OK) != -1;
254}
255
256// Check whether a file is writable.
257static bool fileIsWritable(const char* filename) {
258 return access(filename, W_OK) != -1;
259}
260
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700261// Truncate a file.
262static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800263{
Jamie Gennis43122e72013-03-21 14:06:31 -0700264 // This uses creat rather than truncate because some of the debug kernel
265 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
266 // calls to truncate, but they are cleared by calls to creat.
267 int traceFD = creat(path, 0);
268 if (traceFD == -1) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700269 fprintf(stderr, "error truncating %s: %s (%d)\n", path,
Jamie Gennis43122e72013-03-21 14:06:31 -0700270 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700271 return false;
272 }
273
Jamie Gennis43122e72013-03-21 14:06:31 -0700274 close(traceFD);
275
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700276 return true;
277}
278
279static bool _writeStr(const char* filename, const char* str, int flags)
280{
281 int fd = open(filename, flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800282 if (fd == -1) {
283 fprintf(stderr, "error opening %s: %s (%d)\n", filename,
284 strerror(errno), errno);
285 return false;
286 }
287
288 bool ok = true;
289 ssize_t len = strlen(str);
290 if (write(fd, str, len) != len) {
291 fprintf(stderr, "error writing to %s: %s (%d)\n", filename,
292 strerror(errno), errno);
293 ok = false;
294 }
295
296 close(fd);
297
298 return ok;
299}
300
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700301// Write a string to a file, returning true if the write was successful.
302static bool writeStr(const char* filename, const char* str)
303{
304 return _writeStr(filename, str, O_WRONLY);
305}
306
307// Append a string to a file, returning true if the write was successful.
308static bool appendStr(const char* filename, const char* str)
309{
310 return _writeStr(filename, str, O_APPEND|O_WRONLY);
311}
312
John Reck469a1942015-03-26 15:31:35 -0700313static void writeClockSyncMarker()
314{
315 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200316 int len = 0;
317 int fd = open(k_traceMarkerPath, O_WRONLY);
318 if (fd == -1) {
319 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
320 strerror(errno), errno);
321 return;
322 }
John Reck469a1942015-03-26 15:31:35 -0700323 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200324
325 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
326 if (write(fd, buffer, len) != len) {
327 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
328 }
329
330 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
331 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
332 if (write(fd, buffer, len) != len) {
333 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
334 }
335
336 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700337}
338
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800339// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
340// file.
341static bool setKernelOptionEnable(const char* filename, bool enable)
342{
343 return writeStr(filename, enable ? "1" : "0");
344}
345
346// Check whether the category is supported on the device with the current
347// rootness. A category is supported only if all its required /sys/ files are
348// writable and if enabling the category will enable one or more tracing tags
349// or /sys/ files.
350static bool isCategorySupported(const TracingCategory& category)
351{
sergeyvdb404152016-05-02 19:26:07 -0700352 if (strcmp(category.name, k_coreServiceCategory) == 0) {
353 char value[PROPERTY_VALUE_MAX];
354 property_get(k_coreServicesProp, value, "");
355 return strlen(value) != 0;
356 }
357
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800358 bool ok = category.tags != 0;
359 for (int i = 0; i < MAX_SYS_FILES; i++) {
360 const char* path = category.sysfiles[i].path;
361 bool req = category.sysfiles[i].required == REQ;
362 if (path != NULL) {
363 if (req) {
364 if (!fileIsWritable(path)) {
365 return false;
366 } else {
367 ok = true;
368 }
369 } else {
370 ok |= fileIsWritable(path);
371 }
372 }
373 }
374 return ok;
375}
376
377// Check whether the category would be supported on the device if the user
378// were root. This function assumes that root is able to write to any file
379// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700380// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800381static bool isCategorySupportedForRoot(const TracingCategory& category)
382{
383 bool ok = category.tags != 0;
384 for (int i = 0; i < MAX_SYS_FILES; i++) {
385 const char* path = category.sysfiles[i].path;
386 bool req = category.sysfiles[i].required == REQ;
387 if (path != NULL) {
388 if (req) {
389 if (!fileExists(path)) {
390 return false;
391 } else {
392 ok = true;
393 }
394 } else {
395 ok |= fileExists(path);
396 }
397 }
398 }
399 return ok;
400}
401
402// Enable or disable overwriting of the kernel trace buffers. Disabling this
403// will cause tracing to stop once the trace buffers have filled up.
404static bool setTraceOverwriteEnable(bool enable)
405{
406 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
407}
408
409// Enable or disable kernel tracing.
410static bool setTracingEnabled(bool enable)
411{
412 return setKernelOptionEnable(k_tracingOnPath, enable);
413}
414
415// Clear the contents of the kernel trace.
416static bool clearTrace()
417{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700418 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800419}
420
421// Set the size of the kernel's trace buffer in kilobytes.
422static bool setTraceBufferSizeKB(int size)
423{
424 char str[32] = "1";
425 int len;
426 if (size < 1) {
427 size = 1;
428 }
429 snprintf(str, 32, "%d", size);
430 return writeStr(k_traceBufferSizePath, str);
431}
432
Colin Crossb1ce49b2014-08-20 14:28:47 -0700433// Read the trace_clock sysfs file and return true if it matches the requested
434// value. The trace_clock file format is:
435// local [global] counter uptime perf
436static bool isTraceClock(const char *mode)
437{
438 int fd = open(k_traceClockPath, O_RDONLY);
439 if (fd == -1) {
440 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceClockPath,
441 strerror(errno), errno);
442 return false;
443 }
444
445 char buf[4097];
446 ssize_t n = read(fd, buf, 4096);
447 close(fd);
448 if (n == -1) {
449 fprintf(stderr, "error reading %s: %s (%d)\n", k_traceClockPath,
450 strerror(errno), errno);
451 return false;
452 }
453 buf[n] = '\0';
454
455 char *start = strchr(buf, '[');
456 if (start == NULL) {
457 return false;
458 }
459 start++;
460
461 char *end = strchr(start, ']');
462 if (end == NULL) {
463 return false;
464 }
465 *end = '\0';
466
467 return strcmp(mode, start) == 0;
468}
469
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800470// Enable or disable the kernel's use of the global clock. Disabling the global
471// clock will result in the kernel using a per-CPU local clock.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700472// Any write to the trace_clock sysfs file will reset the buffer, so only
473// update it if the requested value is not the current value.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800474static bool setGlobalClockEnable(bool enable)
475{
Colin Crossb1ce49b2014-08-20 14:28:47 -0700476 const char *clock = enable ? "global" : "local";
477
478 if (isTraceClock(clock)) {
479 return true;
480 }
481
482 return writeStr(k_traceClockPath, clock);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800483}
484
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700485static bool setPrintTgidEnableIfPresent(bool enable)
486{
487 if (fileExists(k_printTgidPath)) {
488 return setKernelOptionEnable(k_printTgidPath, enable);
489 }
490 return true;
491}
492
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800493// Poke all the binder-enabled processes in the system to get them to re-read
494// their system properties.
495static bool pokeBinderServices()
496{
497 sp<IServiceManager> sm = defaultServiceManager();
498 Vector<String16> services = sm->listServices();
499 for (size_t i = 0; i < services.size(); i++) {
500 sp<IBinder> obj = sm->checkService(services[i]);
501 if (obj != NULL) {
502 Parcel data;
503 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
504 NULL, 0) != OK) {
505 if (false) {
506 // XXX: For some reason this fails on tablets trying to
507 // poke the "phone" service. It's not clear whether some
508 // are expected to fail.
509 String8 svc(services[i]);
510 fprintf(stderr, "error poking binder service %s\n",
511 svc.string());
512 return false;
513 }
514 }
515 }
516 }
517 return true;
518}
519
520// Set the trace tags that userland tracing uses, and poke the running
521// processes to pick up the new value.
522static bool setTagsProperty(uint64_t tags)
523{
sergeyv4144eff2016-04-28 11:40:04 -0700524 char buf[PROPERTY_VALUE_MAX];
525 snprintf(buf, sizeof(buf), "%#" PRIx64, tags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800526 if (property_set(k_traceTagsProperty, buf) < 0) {
527 fprintf(stderr, "error setting trace tags system property\n");
528 return false;
529 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700530 return true;
531}
532
sergeyv4144eff2016-04-28 11:40:04 -0700533static void clearAppProperties()
534{
535 char buf[PROPERTY_KEY_MAX];
536 for (int i = 0; i < MAX_PACKAGES; i++) {
537 snprintf(buf, sizeof(buf), k_traceAppsPropertyTemplate, i);
538 if (property_set(buf, "") < 0) {
539 fprintf(stderr, "failed to clear system property: %s\n", buf);
540 }
541 }
542 if (property_set(k_traceAppsNumberProperty, "") < 0) {
543 fprintf(stderr, "failed to clear system property: %s",
544 k_traceAppsNumberProperty);
545 }
546}
547
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700548// Set the system property that indicates which apps should perform
549// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700550static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700551{
sergeyv4144eff2016-04-28 11:40:04 -0700552 char buf[PROPERTY_KEY_MAX];
553 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700554 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700555 while (start != NULL) {
556 if (i == MAX_PACKAGES) {
557 fprintf(stderr, "error: only 16 packages could be traced at once\n");
558 clearAppProperties();
559 return false;
560 }
561 char* end = strchr(start, ',');
562 if (end != NULL) {
563 *end = '\0';
564 end++;
565 }
566 snprintf(buf, sizeof(buf), k_traceAppsPropertyTemplate, i);
567 if (property_set(buf, start) < 0) {
568 fprintf(stderr, "error setting trace app %d property to %s\n", i, buf);
569 clearAppProperties();
570 return false;
571 }
572 start = end;
573 i++;
574 }
575
576 snprintf(buf, sizeof(buf), "%d", i);
577 if (property_set(k_traceAppsNumberProperty, buf) < 0) {
578 fprintf(stderr, "error setting trace app number property to %s\n", buf);
579 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700580 return false;
581 }
582 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800583}
584
585// Disable all /sys/ enable files.
586static bool disableKernelTraceEvents() {
587 bool ok = true;
588 for (int i = 0; i < NELEM(k_categories); i++) {
589 const TracingCategory &c = k_categories[i];
590 for (int j = 0; j < MAX_SYS_FILES; j++) {
591 const char* path = c.sysfiles[j].path;
592 if (path != NULL && fileIsWritable(path)) {
593 ok &= setKernelOptionEnable(path, false);
594 }
595 }
596 }
597 return ok;
598}
599
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700600// Verify that the comma separated list of functions are being traced by the
601// kernel.
602static bool verifyKernelTraceFuncs(const char* funcs)
603{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100604 std::string buf;
605 if (!android::base::ReadFileToString(k_ftraceFilterPath, &buf)) {
606 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700607 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100608 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700609 }
610
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100611 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700612
613 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100614 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700615 bool ok = true;
616 char* myFuncs = strdup(funcs);
617 char* func = strtok(myFuncs, ",");
618 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100619 if (!strchr(func, '*')) {
620 String8 fancyFunc = String8::format("\n%s\n", func);
621 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
622 if (!found || func[0] == '\0') {
623 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
624 "to trace.\n", func);
625 ok = false;
626 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700627 }
628 func = strtok(NULL, ",");
629 }
630 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700631 return ok;
632}
633
634// Set the comma separated list of functions that the kernel is to trace.
635static bool setKernelTraceFuncs(const char* funcs)
636{
637 bool ok = true;
638
639 if (funcs == NULL || funcs[0] == '\0') {
640 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700641 if (fileIsWritable(k_currentTracerPath)) {
642 ok &= writeStr(k_currentTracerPath, "nop");
643 }
644 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700645 ok &= truncateFile(k_ftraceFilterPath);
646 }
647 } else {
648 // Enable kernel function tracing.
649 ok &= writeStr(k_currentTracerPath, "function_graph");
650 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
651 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
652 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
653 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
654
655 // Set the requested filter functions.
656 ok &= truncateFile(k_ftraceFilterPath);
657 char* myFuncs = strdup(funcs);
658 char* func = strtok(myFuncs, ",");
659 while (func) {
660 ok &= appendStr(k_ftraceFilterPath, func);
661 func = strtok(NULL, ",");
662 }
663 free(myFuncs);
664
665 // Verify that the set functions are being traced.
666 if (ok) {
667 ok &= verifyKernelTraceFuncs(funcs);
668 }
669 }
670
671 return ok;
672}
673
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900674static bool setCategoryEnable(const char* name, bool enable)
675{
676 for (int i = 0; i < NELEM(k_categories); i++) {
677 const TracingCategory& c = k_categories[i];
678 if (strcmp(name, c.name) == 0) {
679 if (isCategorySupported(c)) {
680 g_categoryEnables[i] = enable;
681 return true;
682 } else {
683 if (isCategorySupportedForRoot(c)) {
684 fprintf(stderr, "error: category \"%s\" requires root "
685 "privileges.\n", name);
686 } else {
687 fprintf(stderr, "error: category \"%s\" is not supported "
688 "on this device.\n", name);
689 }
690 return false;
691 }
692 }
693 }
694 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
695 return false;
696}
697
698static bool setCategoriesEnableFromFile(const char* categories_file)
699{
700 if (!categories_file) {
701 return true;
702 }
703 Tokenizer* tokenizer = NULL;
704 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
705 return false;
706 }
707 bool ok = true;
708 while (!tokenizer->isEol()) {
709 String8 token = tokenizer->nextToken(" ");
710 if (token.isEmpty()) {
711 tokenizer->skipDelimiters(" ");
712 continue;
713 }
714 ok &= setCategoryEnable(token.string(), true);
715 }
716 delete tokenizer;
717 return ok;
718}
719
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700720// Set all the kernel tracing settings to the desired state for this trace
721// capture.
722static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800723{
724 bool ok = true;
725
726 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900727 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800728 ok &= setTraceOverwriteEnable(g_traceOverwrite);
729 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
730 ok &= setGlobalClockEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700731 ok &= setPrintTgidEnableIfPresent(true);
732 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800733
734 // Set up the tags property.
735 uint64_t tags = 0;
736 for (int i = 0; i < NELEM(k_categories); i++) {
737 if (g_categoryEnables[i]) {
738 const TracingCategory &c = k_categories[i];
739 tags |= c.tags;
740 }
741 }
742 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700743
744 bool coreServicesTagEnabled = false;
745 for (int i = 0; i < NELEM(k_categories); i++) {
746 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
747 coreServicesTagEnabled = g_categoryEnables[i];
748 }
749 }
750
751 std::string packageList(g_debugAppCmdLine);
752 if (coreServicesTagEnabled) {
753 char value[PROPERTY_VALUE_MAX];
754 property_get(k_coreServicesProp, value, "");
755 if (!packageList.empty()) {
756 packageList += ",";
757 }
758 packageList += value;
759 }
Dan Austin09a79872016-05-31 13:27:03 -0700760 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700761 ok &= pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800762
763 // Disable all the sysfs enables. This is done as a separate loop from
764 // the enables to allow the same enable to exist in multiple categories.
765 ok &= disableKernelTraceEvents();
766
767 // Enable all the sysfs enables that are in an enabled category.
768 for (int i = 0; i < NELEM(k_categories); i++) {
769 if (g_categoryEnables[i]) {
770 const TracingCategory &c = k_categories[i];
771 for (int j = 0; j < MAX_SYS_FILES; j++) {
772 const char* path = c.sysfiles[j].path;
773 bool required = c.sysfiles[j].required == REQ;
774 if (path != NULL) {
775 if (fileIsWritable(path)) {
776 ok &= setKernelOptionEnable(path, true);
777 } else if (required) {
778 fprintf(stderr, "error writing file %s\n", path);
779 ok = false;
780 }
781 }
782 }
783 }
784 }
785
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800786 return ok;
787}
788
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700789// Reset all the kernel tracing settings to their default state.
790static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800791{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800792 // Disable all tracing that we're able to.
793 disableKernelTraceEvents();
794
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700795 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800796 setTagsProperty(0);
sergeyv4144eff2016-04-28 11:40:04 -0700797 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700798 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800799
800 // Set the options back to their defaults.
801 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700802 setTraceBufferSizeKB(1);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800803 setGlobalClockEnable(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700804 setPrintTgidEnableIfPresent(false);
805 setKernelTraceFuncs(NULL);
806}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800807
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700808
809// Enable tracing in the kernel.
810static bool startTrace()
811{
812 return setTracingEnabled(true);
813}
814
815// Disable tracing in the kernel.
816static void stopTrace()
817{
818 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800819}
820
Martijn Coenend9535872015-11-26 10:00:55 +0100821// Read data from the tracing pipe and forward to stdout
822static void streamTrace()
823{
824 char trace_data[4096];
825 int traceFD = open(k_traceStreamPath, O_RDWR);
826 if (traceFD == -1) {
827 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
828 strerror(errno), errno);
829 return;
830 }
831 while (!g_traceAborted) {
832 ssize_t bytes_read = read(traceFD, trace_data, 4096);
833 if (bytes_read > 0) {
834 write(STDOUT_FILENO, trace_data, bytes_read);
835 fflush(stdout);
836 } else {
837 if (!g_traceAborted) {
838 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
839 bytes_read, errno, strerror(errno));
840 }
841 break;
842 }
843 }
844}
845
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800846// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700847static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800848{
John Reck6c8ac922016-03-28 11:25:30 -0700849 ALOGI("Dumping trace");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800850 int traceFD = open(k_tracePath, O_RDWR);
851 if (traceFD == -1) {
852 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
853 strerror(errno), errno);
854 return;
855 }
856
857 if (g_compress) {
858 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800859 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700860
861 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800862 if (result != Z_OK) {
863 fprintf(stderr, "error initializing zlib: %d\n", result);
864 close(traceFD);
865 return;
866 }
867
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700868 constexpr size_t bufSize = 64*1024;
869 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
870 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
871 if (!in || !out) {
872 fprintf(stderr, "couldn't allocate buffers\n");
873 close(traceFD);
874 return;
875 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800876
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700877 int flush = Z_NO_FLUSH;
878
879 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800880 zs.avail_out = bufSize;
881
882 do {
883
884 if (zs.avail_in == 0) {
885 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700886 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800887 if (result < 0) {
888 fprintf(stderr, "error reading trace: %s (%d)\n",
889 strerror(errno), errno);
890 result = Z_STREAM_END;
891 break;
892 } else if (result == 0) {
893 flush = Z_FINISH;
894 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700895 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800896 zs.avail_in = result;
897 }
898 }
899
900 if (zs.avail_out == 0) {
901 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700902 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800903 if ((size_t)result < bufSize) {
904 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
905 strerror(errno), errno);
906 result = Z_STREAM_END; // skip deflate error message
907 zs.avail_out = bufSize; // skip the final write
908 break;
909 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700910 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800911 zs.avail_out = bufSize;
912 }
913
914 } while ((result = deflate(&zs, flush)) == Z_OK);
915
916 if (result != Z_STREAM_END) {
917 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
918 }
919
920 if (zs.avail_out < bufSize) {
921 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -0700922 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800923 if ((size_t)result < bytes) {
924 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
925 strerror(errno), errno);
926 }
927 }
928
929 result = deflateEnd(&zs);
930 if (result != Z_OK) {
931 fprintf(stderr, "error cleaning up zlib: %d\n", result);
932 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800933 } else {
934 ssize_t sent = 0;
John Reck40b26b42016-03-30 09:44:36 -0700935 while ((sent = sendfile(outFd, traceFD, NULL, 64*1024*1024)) > 0);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800936 if (sent == -1) {
937 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
938 errno);
939 }
940 }
941
942 close(traceFD);
943}
944
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700945static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800946{
947 if (!g_nohup) {
948 g_traceAborted = true;
949 }
950}
951
952static void registerSigHandler()
953{
954 struct sigaction sa;
955 sigemptyset(&sa.sa_mask);
956 sa.sa_flags = 0;
957 sa.sa_handler = handleSignal;
958 sigaction(SIGHUP, &sa, NULL);
959 sigaction(SIGINT, &sa, NULL);
960 sigaction(SIGQUIT, &sa, NULL);
961 sigaction(SIGTERM, &sa, NULL);
962}
963
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800964static void listSupportedCategories()
965{
966 for (int i = 0; i < NELEM(k_categories); i++) {
967 const TracingCategory& c = k_categories[i];
968 if (isCategorySupported(c)) {
969 printf(" %10s - %s\n", c.name, c.longname);
970 }
971 }
972}
973
974// Print the command usage help to stderr.
975static void showHelp(const char *cmd)
976{
977 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
978 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700979 " -a appname enable app-level tracing for a comma "
980 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800981 " -b N use a trace buffer size of N KB\n"
982 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900983 " -f filename use the categories written in a file as space-separated\n"
984 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700985 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800986 " -n ignore signals\n"
987 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700988 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800989 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700990 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800991 " --async_dump dump the current contents of circular trace buffer\n"
992 " --async_stop stop tracing and dump the current contents of circular\n"
993 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +0100994 " --stream stream trace to stdout as it enters the trace buffer\n"
995 " Note: this can take significant CPU time, and is best\n"
996 " used for measuring things that are not affected by\n"
997 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -0800998 " --list_categories\n"
999 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001000 " -o filename write the trace to the specified file instead\n"
1001 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001002 );
1003}
1004
1005int main(int argc, char **argv)
1006{
1007 bool async = false;
1008 bool traceStart = true;
1009 bool traceStop = true;
1010 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001011 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001012
1013 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1014 showHelp(argv[0]);
1015 exit(0);
1016 }
1017
1018 for (;;) {
1019 int ret;
1020 int option_index = 0;
1021 static struct option long_options[] = {
1022 {"async_start", no_argument, 0, 0 },
1023 {"async_stop", no_argument, 0, 0 },
1024 {"async_dump", no_argument, 0, 0 },
1025 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +01001026 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001027 { 0, 0, 0, 0 }
1028 };
1029
John Reck40b26b42016-03-30 09:44:36 -07001030 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001031 long_options, &option_index);
1032
1033 if (ret < 0) {
1034 for (int i = optind; i < argc; i++) {
1035 if (!setCategoryEnable(argv[i], true)) {
1036 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1037 exit(1);
1038 }
1039 }
1040 break;
1041 }
1042
1043 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001044 case 'a':
1045 g_debugAppCmdLine = optarg;
1046 break;
1047
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001048 case 'b':
1049 g_traceBufferSizeKB = atoi(optarg);
1050 break;
1051
1052 case 'c':
1053 g_traceOverwrite = true;
1054 break;
1055
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001056 case 'f':
1057 g_categoriesFile = optarg;
1058 break;
1059
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001060 case 'k':
1061 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001062 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001063
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001064 case 'n':
1065 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001066 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001067
1068 case 's':
1069 g_initialSleepSecs = atoi(optarg);
1070 break;
1071
1072 case 't':
1073 g_traceDurationSeconds = atoi(optarg);
1074 break;
1075
1076 case 'z':
1077 g_compress = true;
1078 break;
1079
John Reck40b26b42016-03-30 09:44:36 -07001080 case 'o':
1081 g_outputFile = optarg;
1082 break;
1083
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001084 case 0:
1085 if (!strcmp(long_options[option_index].name, "async_start")) {
1086 async = true;
1087 traceStop = false;
1088 traceDump = false;
1089 g_traceOverwrite = true;
1090 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1091 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001092 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001093 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1094 async = true;
1095 traceStart = false;
1096 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001097 } else if (!strcmp(long_options[option_index].name, "stream")) {
1098 traceStream = true;
1099 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001100 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1101 listSupportedCategories();
1102 exit(0);
1103 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001104 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001105
1106 default:
1107 fprintf(stderr, "\n");
1108 showHelp(argv[0]);
1109 exit(-1);
1110 break;
1111 }
1112 }
1113
1114 registerSigHandler();
1115
1116 if (g_initialSleepSecs > 0) {
1117 sleep(g_initialSleepSecs);
1118 }
1119
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001120 bool ok = true;
1121 ok &= setUpTrace();
1122 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001123
1124 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001125 if (!traceStream) {
1126 printf("capturing trace...");
1127 fflush(stdout);
1128 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001129
1130 // We clear the trace after starting it because tracing gets enabled for
1131 // each CPU individually in the kernel. Having the beginning of the trace
1132 // contain entries from only one CPU can cause "begin" entries without a
1133 // matching "end" entry to show up if a task gets migrated from one CPU to
1134 // another.
1135 ok = clearTrace();
1136
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001137 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001138 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001139 // Sleep to allow the trace to be captured.
1140 struct timespec timeLeft;
1141 timeLeft.tv_sec = g_traceDurationSeconds;
1142 timeLeft.tv_nsec = 0;
1143 do {
1144 if (g_traceAborted) {
1145 break;
1146 }
1147 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1148 }
Martijn Coenend9535872015-11-26 10:00:55 +01001149
1150 if (traceStream) {
1151 streamTrace();
1152 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001153 }
1154
1155 // Stop the trace and restore the default settings.
1156 if (traceStop)
1157 stopTrace();
1158
1159 if (ok && traceDump) {
1160 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001161 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001162 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001163 int outFd = STDOUT_FILENO;
1164 if (g_outputFile) {
George Burgess IV48443342016-05-04 19:42:00 -07001165 outFd = open(g_outputFile, O_WRONLY | O_CREAT, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001166 }
1167 if (outFd == -1) {
1168 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1169 } else {
1170 dprintf(outFd, "TRACE:\n");
1171 dumpTrace(outFd);
1172 if (g_outputFile) {
1173 close(outFd);
1174 }
1175 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001176 } else {
1177 printf("\ntrace aborted.\n");
1178 fflush(stdout);
1179 }
1180 clearTrace();
1181 } else if (!ok) {
1182 fprintf(stderr, "unable to start tracing\n");
1183 }
1184
1185 // Reset the trace buffer size to 1.
1186 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001187 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001188
1189 return g_traceAborted ? 1 : 0;
1190}