blob: f6f337ca58de2c03c3c55bf15ffaad0b81dd0230 [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
Martijn Coenenee9b97e2016-11-16 16:00:26 +010040#include <android/hidl/manager/1.0/IServiceManager.h>
41#include <hidl/ServiceManagement.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080042#include <cutils/properties.h>
43
44#include <utils/String8.h>
John Reck469a1942015-03-26 15:31:35 -070045#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +090046#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080047#include <utils/Trace.h>
Stephane Gasparinid8419c22016-03-02 13:45:15 +010048#include <android-base/file.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080049
50using namespace android;
51
Martijn Coenenee9b97e2016-11-16 16:00:26 +010052using std::string;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080053#define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0])))
54
sergeyv4144eff2016-04-28 11:40:04 -070055#define MAX_SYS_FILES 10
56#define MAX_PACKAGES 16
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080057
58const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
sergeyv4144eff2016-04-28 11:40:04 -070059
60const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
61const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070062const char* k_coreServiceCategory = "core_services";
63const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080064
65typedef enum { OPT, REQ } requiredness ;
66
67struct TracingCategory {
68 // The name identifying the category.
69 const char* name;
70
71 // A longer description of the category.
72 const char* longname;
73
74 // The userland tracing tags that the category enables.
75 uint64_t tags;
76
77 // The fname==NULL terminated list of /sys/ files that the category
78 // enables.
79 struct {
80 // Whether the file must be writable in order to enable the tracing
81 // category.
82 requiredness required;
83
84 // The path to the enable file.
85 const char* path;
86 } sysfiles[MAX_SYS_FILES];
87};
88
89/* Tracing categories */
90static const TracingCategory k_categories[] = {
Jamie Gennisb2a89e32013-03-11 19:37:53 -070091 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, { } },
92 { "input", "Input", ATRACE_TAG_INPUT, { } },
93 { "view", "View System", ATRACE_TAG_VIEW, { } },
94 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
95 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
96 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -050097 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070098 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
99 { "video", "Video", ATRACE_TAG_VIDEO, { } },
100 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
101 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700102 { "app", "Application", ATRACE_TAG_APP, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -0700103 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -0700104 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -0700105 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -0700106 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700107 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 14:36:20 -0700108 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-07-01 01:46:25 +0900109 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Greg Hackmannbbd7d992014-12-01 14:43:34 -0800110 { "database", "Database", ATRACE_TAG_DATABASE, { } },
sergeyvdb404152016-05-02 19:26:07 -0700111 { k_coreServiceCategory, "Core services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700112 { "sched", "CPU Scheduling", 0, {
113 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_switch/enable" },
114 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_wakeup/enable" },
Riley Andrews5672bb72015-11-19 13:31:17 -0800115 { OPT, "/sys/kernel/debug/tracing/events/sched/sched_blocked_reason/enable" },
Ruchi Kandoicfe500d2015-11-23 13:47:20 -0800116 { OPT, "/sys/kernel/debug/tracing/events/sched/sched_cpu_hotplug/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800117 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700118 { "irq", "IRQ Events", 0, {
119 { REQ, "/sys/kernel/debug/tracing/events/irq/enable" },
Riley Andrews412e4f62015-11-02 21:01:34 -0800120 { OPT, "/sys/kernel/debug/tracing/events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700121 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700122 { "freq", "CPU Frequency", 0, {
123 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_frequency/enable" },
124 { OPT, "/sys/kernel/debug/tracing/events/power/clock_set_rate/enable" },
Ruchi Kandoiffcc7112015-11-19 18:32:00 -0800125 { OPT, "/sys/kernel/debug/tracing/events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800126 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700127 { "membus", "Memory Bus Utilization", 0, {
128 { REQ, "/sys/kernel/debug/tracing/events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800129 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700130 { "idle", "CPU Idle", 0, {
131 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800132 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700133 { "disk", "Disk I/O", 0, {
Greg Hackmanne80d32c2014-11-20 12:59:44 -0800134 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_enter/enable" },
135 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_exit/enable" },
136 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_begin/enable" },
137 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_end/enable" },
138 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_begin/enable" },
139 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_end/enable" },
140 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable" },
141 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable" },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700142 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" },
143 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800144 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700145 { "mmc", "eMMC commands", 0, {
146 { REQ, "/sys/kernel/debug/tracing/events/mmc/enable" },
147 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700148 { "load", "CPU Load", 0, {
149 { REQ, "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800150 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700151 { "sync", "Synchronization", 0, {
152 { REQ, "/sys/kernel/debug/tracing/events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800153 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700154 { "workq", "Kernel Workqueues", 0, {
155 { REQ, "/sys/kernel/debug/tracing/events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800156 } },
Colin Cross580407f2014-08-18 15:22:13 -0700157 { "memreclaim", "Kernel Memory Reclaim", 0, {
158 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
159 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
160 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_wake/enable" },
161 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_sleep/enable" },
162 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800163 { "regulators", "Voltage and Current Regulators", 0, {
164 { REQ, "/sys/kernel/debug/tracing/events/regulator/enable" },
165 } },
Scott Bauerae473362015-06-08 16:32:36 -0700166 { "binder_driver", "Binder Kernel driver", 0, {
167 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction/enable" },
168 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction_received/enable" },
169 } },
170 { "binder_lock", "Binder global lock trace", 0, {
171 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_lock/enable" },
172 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_locked/enable" },
173 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_unlock/enable" },
174 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200175 { "pagecache", "Page cache", 0, {
176 { REQ, "/sys/kernel/debug/tracing/events/filemap/enable" },
177 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800178};
179
180/* Command line options */
181static int g_traceDurationSeconds = 5;
182static bool g_traceOverwrite = false;
183static int g_traceBufferSizeKB = 2048;
184static bool g_compress = false;
185static bool g_nohup = false;
186static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900187static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700188static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700189static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700190static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800191
192/* Global state */
193static bool g_traceAborted = false;
194static bool g_categoryEnables[NELEM(k_categories)] = {};
195
196/* Sys file paths */
197static const char* k_traceClockPath =
198 "/sys/kernel/debug/tracing/trace_clock";
199
200static const char* k_traceBufferSizePath =
201 "/sys/kernel/debug/tracing/buffer_size_kb";
202
203static const char* k_tracingOverwriteEnablePath =
204 "/sys/kernel/debug/tracing/options/overwrite";
205
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700206static const char* k_currentTracerPath =
207 "/sys/kernel/debug/tracing/current_tracer";
208
209static const char* k_printTgidPath =
210 "/sys/kernel/debug/tracing/options/print-tgid";
211
212static const char* k_funcgraphAbsTimePath =
213 "/sys/kernel/debug/tracing/options/funcgraph-abstime";
214
215static const char* k_funcgraphCpuPath =
216 "/sys/kernel/debug/tracing/options/funcgraph-cpu";
217
218static const char* k_funcgraphProcPath =
219 "/sys/kernel/debug/tracing/options/funcgraph-proc";
220
221static const char* k_funcgraphFlatPath =
222 "/sys/kernel/debug/tracing/options/funcgraph-flat";
223
224static const char* k_funcgraphDurationPath =
225 "/sys/kernel/debug/tracing/options/funcgraph-duration";
226
227static const char* k_ftraceFilterPath =
228 "/sys/kernel/debug/tracing/set_ftrace_filter";
229
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800230static const char* k_tracingOnPath =
231 "/sys/kernel/debug/tracing/tracing_on";
232
233static const char* k_tracePath =
234 "/sys/kernel/debug/tracing/trace";
235
Martijn Coenend9535872015-11-26 10:00:55 +0100236static const char* k_traceStreamPath =
237 "/sys/kernel/debug/tracing/trace_pipe";
238
John Reck469a1942015-03-26 15:31:35 -0700239static const char* k_traceMarkerPath =
240 "/sys/kernel/debug/tracing/trace_marker";
241
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800242// Check whether a file exists.
243static bool fileExists(const char* filename) {
244 return access(filename, F_OK) != -1;
245}
246
247// Check whether a file is writable.
248static bool fileIsWritable(const char* filename) {
249 return access(filename, W_OK) != -1;
250}
251
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700252// Truncate a file.
253static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800254{
Jamie Gennis43122e72013-03-21 14:06:31 -0700255 // This uses creat rather than truncate because some of the debug kernel
256 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
257 // calls to truncate, but they are cleared by calls to creat.
258 int traceFD = creat(path, 0);
259 if (traceFD == -1) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700260 fprintf(stderr, "error truncating %s: %s (%d)\n", path,
Jamie Gennis43122e72013-03-21 14:06:31 -0700261 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700262 return false;
263 }
264
Jamie Gennis43122e72013-03-21 14:06:31 -0700265 close(traceFD);
266
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700267 return true;
268}
269
270static bool _writeStr(const char* filename, const char* str, int flags)
271{
272 int fd = open(filename, flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800273 if (fd == -1) {
274 fprintf(stderr, "error opening %s: %s (%d)\n", filename,
275 strerror(errno), errno);
276 return false;
277 }
278
279 bool ok = true;
280 ssize_t len = strlen(str);
281 if (write(fd, str, len) != len) {
282 fprintf(stderr, "error writing to %s: %s (%d)\n", filename,
283 strerror(errno), errno);
284 ok = false;
285 }
286
287 close(fd);
288
289 return ok;
290}
291
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700292// Write a string to a file, returning true if the write was successful.
293static bool writeStr(const char* filename, const char* str)
294{
295 return _writeStr(filename, str, O_WRONLY);
296}
297
298// Append a string to a file, returning true if the write was successful.
299static bool appendStr(const char* filename, const char* str)
300{
301 return _writeStr(filename, str, O_APPEND|O_WRONLY);
302}
303
John Reck469a1942015-03-26 15:31:35 -0700304static void writeClockSyncMarker()
305{
306 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200307 int len = 0;
308 int fd = open(k_traceMarkerPath, O_WRONLY);
309 if (fd == -1) {
310 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
311 strerror(errno), errno);
312 return;
313 }
John Reck469a1942015-03-26 15:31:35 -0700314 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200315
316 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
317 if (write(fd, buffer, len) != len) {
318 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
319 }
320
321 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
322 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
323 if (write(fd, buffer, len) != len) {
324 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
325 }
326
327 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700328}
329
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800330// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
331// file.
332static bool setKernelOptionEnable(const char* filename, bool enable)
333{
334 return writeStr(filename, enable ? "1" : "0");
335}
336
337// Check whether the category is supported on the device with the current
338// rootness. A category is supported only if all its required /sys/ files are
339// writable and if enabling the category will enable one or more tracing tags
340// or /sys/ files.
341static bool isCategorySupported(const TracingCategory& category)
342{
sergeyvdb404152016-05-02 19:26:07 -0700343 if (strcmp(category.name, k_coreServiceCategory) == 0) {
344 char value[PROPERTY_VALUE_MAX];
345 property_get(k_coreServicesProp, value, "");
346 return strlen(value) != 0;
347 }
348
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800349 bool ok = category.tags != 0;
350 for (int i = 0; i < MAX_SYS_FILES; i++) {
351 const char* path = category.sysfiles[i].path;
352 bool req = category.sysfiles[i].required == REQ;
353 if (path != NULL) {
354 if (req) {
355 if (!fileIsWritable(path)) {
356 return false;
357 } else {
358 ok = true;
359 }
360 } else {
361 ok |= fileIsWritable(path);
362 }
363 }
364 }
365 return ok;
366}
367
368// Check whether the category would be supported on the device if the user
369// were root. This function assumes that root is able to write to any file
370// that exists. It performs the same logic as isCategorySupported, but it
371// uses file existance rather than writability in the /sys/ file checks.
372static bool isCategorySupportedForRoot(const TracingCategory& category)
373{
374 bool ok = category.tags != 0;
375 for (int i = 0; i < MAX_SYS_FILES; i++) {
376 const char* path = category.sysfiles[i].path;
377 bool req = category.sysfiles[i].required == REQ;
378 if (path != NULL) {
379 if (req) {
380 if (!fileExists(path)) {
381 return false;
382 } else {
383 ok = true;
384 }
385 } else {
386 ok |= fileExists(path);
387 }
388 }
389 }
390 return ok;
391}
392
393// Enable or disable overwriting of the kernel trace buffers. Disabling this
394// will cause tracing to stop once the trace buffers have filled up.
395static bool setTraceOverwriteEnable(bool enable)
396{
397 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
398}
399
400// Enable or disable kernel tracing.
401static bool setTracingEnabled(bool enable)
402{
403 return setKernelOptionEnable(k_tracingOnPath, enable);
404}
405
406// Clear the contents of the kernel trace.
407static bool clearTrace()
408{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700409 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800410}
411
412// Set the size of the kernel's trace buffer in kilobytes.
413static bool setTraceBufferSizeKB(int size)
414{
415 char str[32] = "1";
416 int len;
417 if (size < 1) {
418 size = 1;
419 }
420 snprintf(str, 32, "%d", size);
421 return writeStr(k_traceBufferSizePath, str);
422}
423
Colin Crossb1ce49b2014-08-20 14:28:47 -0700424// Read the trace_clock sysfs file and return true if it matches the requested
425// value. The trace_clock file format is:
426// local [global] counter uptime perf
427static bool isTraceClock(const char *mode)
428{
429 int fd = open(k_traceClockPath, O_RDONLY);
430 if (fd == -1) {
431 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceClockPath,
432 strerror(errno), errno);
433 return false;
434 }
435
436 char buf[4097];
437 ssize_t n = read(fd, buf, 4096);
438 close(fd);
439 if (n == -1) {
440 fprintf(stderr, "error reading %s: %s (%d)\n", k_traceClockPath,
441 strerror(errno), errno);
442 return false;
443 }
444 buf[n] = '\0';
445
446 char *start = strchr(buf, '[');
447 if (start == NULL) {
448 return false;
449 }
450 start++;
451
452 char *end = strchr(start, ']');
453 if (end == NULL) {
454 return false;
455 }
456 *end = '\0';
457
458 return strcmp(mode, start) == 0;
459}
460
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800461// Enable or disable the kernel's use of the global clock. Disabling the global
462// clock will result in the kernel using a per-CPU local clock.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700463// Any write to the trace_clock sysfs file will reset the buffer, so only
464// update it if the requested value is not the current value.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800465static bool setGlobalClockEnable(bool enable)
466{
Colin Crossb1ce49b2014-08-20 14:28:47 -0700467 const char *clock = enable ? "global" : "local";
468
469 if (isTraceClock(clock)) {
470 return true;
471 }
472
473 return writeStr(k_traceClockPath, clock);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800474}
475
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700476static bool setPrintTgidEnableIfPresent(bool enable)
477{
478 if (fileExists(k_printTgidPath)) {
479 return setKernelOptionEnable(k_printTgidPath, enable);
480 }
481 return true;
482}
483
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800484// Poke all the binder-enabled processes in the system to get them to re-read
485// their system properties.
486static bool pokeBinderServices()
487{
488 sp<IServiceManager> sm = defaultServiceManager();
489 Vector<String16> services = sm->listServices();
490 for (size_t i = 0; i < services.size(); i++) {
491 sp<IBinder> obj = sm->checkService(services[i]);
492 if (obj != NULL) {
493 Parcel data;
494 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
495 NULL, 0) != OK) {
496 if (false) {
497 // XXX: For some reason this fails on tablets trying to
498 // poke the "phone" service. It's not clear whether some
499 // are expected to fail.
500 String8 svc(services[i]);
501 fprintf(stderr, "error poking binder service %s\n",
502 svc.string());
503 return false;
504 }
505 }
506 }
507 }
508 return true;
509}
510
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100511// Poke all the HAL processes in the system to get them to re-read
512// their system properties.
513static void pokeHalServices()
514{
515 using ::android::hidl::manager::V1_0::IServiceManager;
516 using ::android::hardware::IBinder;
517 using ::android::hardware::hidl_string;
518 using ::android::hardware::Parcel;
519
520 Parcel data;
521
522 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
523 sm->list([&](const auto &interfaces) {
524 for (size_t i = 0; i < interfaces.size(); i++) {
525 string fqInstanceName = interfaces[i];
526 string::size_type n = fqInstanceName.find("/");
527 if (n == std::string::npos || interfaces[i].size() == n+1)
528 continue;
529 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
530 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
531 sm->get(fqInterfaceName, instanceName, [&](const auto &interface) {
532 // TODO(b/32756130)
533 // Once IServiceManager returns IBase, use interface->notifySyspropsChanged() here
534 interface->transact(IBinder::SYSPROPS_TRANSACTION, data, nullptr, 0, nullptr);
535 });
536 }
537 });
538}
539
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800540// Set the trace tags that userland tracing uses, and poke the running
541// processes to pick up the new value.
542static bool setTagsProperty(uint64_t tags)
543{
sergeyv4144eff2016-04-28 11:40:04 -0700544 char buf[PROPERTY_VALUE_MAX];
545 snprintf(buf, sizeof(buf), "%#" PRIx64, tags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800546 if (property_set(k_traceTagsProperty, buf) < 0) {
547 fprintf(stderr, "error setting trace tags system property\n");
548 return false;
549 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700550 return true;
551}
552
sergeyv4144eff2016-04-28 11:40:04 -0700553static void clearAppProperties()
554{
555 char buf[PROPERTY_KEY_MAX];
556 for (int i = 0; i < MAX_PACKAGES; i++) {
557 snprintf(buf, sizeof(buf), k_traceAppsPropertyTemplate, i);
558 if (property_set(buf, "") < 0) {
559 fprintf(stderr, "failed to clear system property: %s\n", buf);
560 }
561 }
562 if (property_set(k_traceAppsNumberProperty, "") < 0) {
563 fprintf(stderr, "failed to clear system property: %s",
564 k_traceAppsNumberProperty);
565 }
566}
567
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700568// Set the system property that indicates which apps should perform
569// application-level tracing.
Dan Austin497951c2016-05-31 13:27:03 -0700570static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700571{
sergeyv4144eff2016-04-28 11:40:04 -0700572 char buf[PROPERTY_KEY_MAX];
573 int i = 0;
Dan Austin497951c2016-05-31 13:27:03 -0700574 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700575 while (start != NULL) {
576 if (i == MAX_PACKAGES) {
577 fprintf(stderr, "error: only 16 packages could be traced at once\n");
578 clearAppProperties();
579 return false;
580 }
581 char* end = strchr(start, ',');
582 if (end != NULL) {
583 *end = '\0';
584 end++;
585 }
586 snprintf(buf, sizeof(buf), k_traceAppsPropertyTemplate, i);
587 if (property_set(buf, start) < 0) {
588 fprintf(stderr, "error setting trace app %d property to %s\n", i, buf);
589 clearAppProperties();
590 return false;
591 }
592 start = end;
593 i++;
594 }
595
596 snprintf(buf, sizeof(buf), "%d", i);
597 if (property_set(k_traceAppsNumberProperty, buf) < 0) {
598 fprintf(stderr, "error setting trace app number property to %s\n", buf);
599 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700600 return false;
601 }
602 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800603}
604
605// Disable all /sys/ enable files.
606static bool disableKernelTraceEvents() {
607 bool ok = true;
608 for (int i = 0; i < NELEM(k_categories); i++) {
609 const TracingCategory &c = k_categories[i];
610 for (int j = 0; j < MAX_SYS_FILES; j++) {
611 const char* path = c.sysfiles[j].path;
612 if (path != NULL && fileIsWritable(path)) {
613 ok &= setKernelOptionEnable(path, false);
614 }
615 }
616 }
617 return ok;
618}
619
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700620// Verify that the comma separated list of functions are being traced by the
621// kernel.
622static bool verifyKernelTraceFuncs(const char* funcs)
623{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100624 std::string buf;
625 if (!android::base::ReadFileToString(k_ftraceFilterPath, &buf)) {
626 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700627 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100628 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700629 }
630
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100631 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700632
633 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100634 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700635 bool ok = true;
636 char* myFuncs = strdup(funcs);
637 char* func = strtok(myFuncs, ",");
638 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100639 if (!strchr(func, '*')) {
640 String8 fancyFunc = String8::format("\n%s\n", func);
641 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
642 if (!found || func[0] == '\0') {
643 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
644 "to trace.\n", func);
645 ok = false;
646 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700647 }
648 func = strtok(NULL, ",");
649 }
650 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700651 return ok;
652}
653
654// Set the comma separated list of functions that the kernel is to trace.
655static bool setKernelTraceFuncs(const char* funcs)
656{
657 bool ok = true;
658
659 if (funcs == NULL || funcs[0] == '\0') {
660 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700661 if (fileIsWritable(k_currentTracerPath)) {
662 ok &= writeStr(k_currentTracerPath, "nop");
663 }
664 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700665 ok &= truncateFile(k_ftraceFilterPath);
666 }
667 } else {
668 // Enable kernel function tracing.
669 ok &= writeStr(k_currentTracerPath, "function_graph");
670 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
671 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
672 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
673 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
674
675 // Set the requested filter functions.
676 ok &= truncateFile(k_ftraceFilterPath);
677 char* myFuncs = strdup(funcs);
678 char* func = strtok(myFuncs, ",");
679 while (func) {
680 ok &= appendStr(k_ftraceFilterPath, func);
681 func = strtok(NULL, ",");
682 }
683 free(myFuncs);
684
685 // Verify that the set functions are being traced.
686 if (ok) {
687 ok &= verifyKernelTraceFuncs(funcs);
688 }
689 }
690
691 return ok;
692}
693
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900694static bool setCategoryEnable(const char* name, bool enable)
695{
696 for (int i = 0; i < NELEM(k_categories); i++) {
697 const TracingCategory& c = k_categories[i];
698 if (strcmp(name, c.name) == 0) {
699 if (isCategorySupported(c)) {
700 g_categoryEnables[i] = enable;
701 return true;
702 } else {
703 if (isCategorySupportedForRoot(c)) {
704 fprintf(stderr, "error: category \"%s\" requires root "
705 "privileges.\n", name);
706 } else {
707 fprintf(stderr, "error: category \"%s\" is not supported "
708 "on this device.\n", name);
709 }
710 return false;
711 }
712 }
713 }
714 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
715 return false;
716}
717
718static bool setCategoriesEnableFromFile(const char* categories_file)
719{
720 if (!categories_file) {
721 return true;
722 }
723 Tokenizer* tokenizer = NULL;
724 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
725 return false;
726 }
727 bool ok = true;
728 while (!tokenizer->isEol()) {
729 String8 token = tokenizer->nextToken(" ");
730 if (token.isEmpty()) {
731 tokenizer->skipDelimiters(" ");
732 continue;
733 }
734 ok &= setCategoryEnable(token.string(), true);
735 }
736 delete tokenizer;
737 return ok;
738}
739
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700740// Set all the kernel tracing settings to the desired state for this trace
741// capture.
742static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800743{
744 bool ok = true;
745
746 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900747 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800748 ok &= setTraceOverwriteEnable(g_traceOverwrite);
749 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
750 ok &= setGlobalClockEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700751 ok &= setPrintTgidEnableIfPresent(true);
752 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800753
754 // Set up the tags property.
755 uint64_t tags = 0;
756 for (int i = 0; i < NELEM(k_categories); i++) {
757 if (g_categoryEnables[i]) {
758 const TracingCategory &c = k_categories[i];
759 tags |= c.tags;
760 }
761 }
762 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700763
764 bool coreServicesTagEnabled = false;
765 for (int i = 0; i < NELEM(k_categories); i++) {
766 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
767 coreServicesTagEnabled = g_categoryEnables[i];
768 }
769 }
770
771 std::string packageList(g_debugAppCmdLine);
772 if (coreServicesTagEnabled) {
773 char value[PROPERTY_VALUE_MAX];
774 property_get(k_coreServicesProp, value, "");
775 if (!packageList.empty()) {
776 packageList += ",";
777 }
778 packageList += value;
779 }
Dan Austin497951c2016-05-31 13:27:03 -0700780 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700781 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100782 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800783
784 // Disable all the sysfs enables. This is done as a separate loop from
785 // the enables to allow the same enable to exist in multiple categories.
786 ok &= disableKernelTraceEvents();
787
788 // Enable all the sysfs enables that are in an enabled category.
789 for (int i = 0; i < NELEM(k_categories); i++) {
790 if (g_categoryEnables[i]) {
791 const TracingCategory &c = k_categories[i];
792 for (int j = 0; j < MAX_SYS_FILES; j++) {
793 const char* path = c.sysfiles[j].path;
794 bool required = c.sysfiles[j].required == REQ;
795 if (path != NULL) {
796 if (fileIsWritable(path)) {
797 ok &= setKernelOptionEnable(path, true);
798 } else if (required) {
799 fprintf(stderr, "error writing file %s\n", path);
800 ok = false;
801 }
802 }
803 }
804 }
805 }
806
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800807 return ok;
808}
809
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700810// Reset all the kernel tracing settings to their default state.
811static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800812{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800813 // Disable all tracing that we're able to.
814 disableKernelTraceEvents();
815
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700816 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800817 setTagsProperty(0);
sergeyv4144eff2016-04-28 11:40:04 -0700818 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700819 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800820
821 // Set the options back to their defaults.
822 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700823 setTraceBufferSizeKB(1);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800824 setGlobalClockEnable(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700825 setPrintTgidEnableIfPresent(false);
826 setKernelTraceFuncs(NULL);
827}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800828
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700829
830// Enable tracing in the kernel.
831static bool startTrace()
832{
833 return setTracingEnabled(true);
834}
835
836// Disable tracing in the kernel.
837static void stopTrace()
838{
839 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800840}
841
Martijn Coenend9535872015-11-26 10:00:55 +0100842// Read data from the tracing pipe and forward to stdout
843static void streamTrace()
844{
845 char trace_data[4096];
846 int traceFD = open(k_traceStreamPath, O_RDWR);
847 if (traceFD == -1) {
848 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
849 strerror(errno), errno);
850 return;
851 }
852 while (!g_traceAborted) {
853 ssize_t bytes_read = read(traceFD, trace_data, 4096);
854 if (bytes_read > 0) {
855 write(STDOUT_FILENO, trace_data, bytes_read);
856 fflush(stdout);
857 } else {
858 if (!g_traceAborted) {
859 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
860 bytes_read, errno, strerror(errno));
861 }
862 break;
863 }
864 }
865}
866
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800867// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700868static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800869{
John Reck6c8ac922016-03-28 11:25:30 -0700870 ALOGI("Dumping trace");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800871 int traceFD = open(k_tracePath, O_RDWR);
872 if (traceFD == -1) {
873 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
874 strerror(errno), errno);
875 return;
876 }
877
878 if (g_compress) {
879 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800880 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700881
882 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800883 if (result != Z_OK) {
884 fprintf(stderr, "error initializing zlib: %d\n", result);
885 close(traceFD);
886 return;
887 }
888
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700889 constexpr size_t bufSize = 64*1024;
890 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
891 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
892 if (!in || !out) {
893 fprintf(stderr, "couldn't allocate buffers\n");
894 close(traceFD);
895 return;
896 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800897
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700898 int flush = Z_NO_FLUSH;
899
900 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800901 zs.avail_out = bufSize;
902
903 do {
904
905 if (zs.avail_in == 0) {
906 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700907 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800908 if (result < 0) {
909 fprintf(stderr, "error reading trace: %s (%d)\n",
910 strerror(errno), errno);
911 result = Z_STREAM_END;
912 break;
913 } else if (result == 0) {
914 flush = Z_FINISH;
915 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700916 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800917 zs.avail_in = result;
918 }
919 }
920
921 if (zs.avail_out == 0) {
922 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700923 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800924 if ((size_t)result < bufSize) {
925 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
926 strerror(errno), errno);
927 result = Z_STREAM_END; // skip deflate error message
928 zs.avail_out = bufSize; // skip the final write
929 break;
930 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700931 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800932 zs.avail_out = bufSize;
933 }
934
935 } while ((result = deflate(&zs, flush)) == Z_OK);
936
937 if (result != Z_STREAM_END) {
938 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
939 }
940
941 if (zs.avail_out < bufSize) {
942 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -0700943 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800944 if ((size_t)result < bytes) {
945 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
946 strerror(errno), errno);
947 }
948 }
949
950 result = deflateEnd(&zs);
951 if (result != Z_OK) {
952 fprintf(stderr, "error cleaning up zlib: %d\n", result);
953 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800954 } else {
955 ssize_t sent = 0;
John Reck40b26b42016-03-30 09:44:36 -0700956 while ((sent = sendfile(outFd, traceFD, NULL, 64*1024*1024)) > 0);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800957 if (sent == -1) {
958 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
959 errno);
960 }
961 }
962
963 close(traceFD);
964}
965
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700966static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800967{
968 if (!g_nohup) {
969 g_traceAborted = true;
970 }
971}
972
973static void registerSigHandler()
974{
975 struct sigaction sa;
976 sigemptyset(&sa.sa_mask);
977 sa.sa_flags = 0;
978 sa.sa_handler = handleSignal;
979 sigaction(SIGHUP, &sa, NULL);
980 sigaction(SIGINT, &sa, NULL);
981 sigaction(SIGQUIT, &sa, NULL);
982 sigaction(SIGTERM, &sa, NULL);
983}
984
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800985static void listSupportedCategories()
986{
987 for (int i = 0; i < NELEM(k_categories); i++) {
988 const TracingCategory& c = k_categories[i];
989 if (isCategorySupported(c)) {
990 printf(" %10s - %s\n", c.name, c.longname);
991 }
992 }
993}
994
995// Print the command usage help to stderr.
996static void showHelp(const char *cmd)
997{
998 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
999 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001000 " -a appname enable app-level tracing for a comma "
1001 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001002 " -b N use a trace buffer size of N KB\n"
1003 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001004 " -f filename use the categories written in a file as space-separated\n"
1005 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001006 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001007 " -n ignore signals\n"
1008 " -s N sleep for N seconds before tracing [default 0]\n"
Elliott Hughesf884a062016-07-22 09:38:44 -07001009 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001010 " -z compress the trace dump\n"
1011 " --async_start start circular trace and return immediatly\n"
1012 " --async_dump dump the current contents of circular trace buffer\n"
1013 " --async_stop stop tracing and dump the current contents of circular\n"
1014 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001015 " --stream stream trace to stdout as it enters the trace buffer\n"
1016 " Note: this can take significant CPU time, and is best\n"
1017 " used for measuring things that are not affected by\n"
1018 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001019 " --list_categories\n"
1020 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001021 " -o filename write the trace to the specified file instead\n"
1022 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001023 );
1024}
1025
1026int main(int argc, char **argv)
1027{
1028 bool async = false;
1029 bool traceStart = true;
1030 bool traceStop = true;
1031 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001032 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001033
1034 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1035 showHelp(argv[0]);
1036 exit(0);
1037 }
1038
1039 for (;;) {
1040 int ret;
1041 int option_index = 0;
1042 static struct option long_options[] = {
1043 {"async_start", no_argument, 0, 0 },
1044 {"async_stop", no_argument, 0, 0 },
1045 {"async_dump", no_argument, 0, 0 },
1046 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +01001047 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001048 { 0, 0, 0, 0 }
1049 };
1050
John Reck40b26b42016-03-30 09:44:36 -07001051 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001052 long_options, &option_index);
1053
1054 if (ret < 0) {
1055 for (int i = optind; i < argc; i++) {
1056 if (!setCategoryEnable(argv[i], true)) {
1057 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1058 exit(1);
1059 }
1060 }
1061 break;
1062 }
1063
1064 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001065 case 'a':
1066 g_debugAppCmdLine = optarg;
1067 break;
1068
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001069 case 'b':
1070 g_traceBufferSizeKB = atoi(optarg);
1071 break;
1072
1073 case 'c':
1074 g_traceOverwrite = true;
1075 break;
1076
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001077 case 'f':
1078 g_categoriesFile = optarg;
1079 break;
1080
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001081 case 'k':
1082 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001083 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001084
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001085 case 'n':
1086 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001087 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001088
1089 case 's':
1090 g_initialSleepSecs = atoi(optarg);
1091 break;
1092
1093 case 't':
1094 g_traceDurationSeconds = atoi(optarg);
1095 break;
1096
1097 case 'z':
1098 g_compress = true;
1099 break;
1100
John Reck40b26b42016-03-30 09:44:36 -07001101 case 'o':
1102 g_outputFile = optarg;
1103 break;
1104
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001105 case 0:
1106 if (!strcmp(long_options[option_index].name, "async_start")) {
1107 async = true;
1108 traceStop = false;
1109 traceDump = false;
1110 g_traceOverwrite = true;
1111 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1112 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001113 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001114 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1115 async = true;
1116 traceStart = false;
1117 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001118 } else if (!strcmp(long_options[option_index].name, "stream")) {
1119 traceStream = true;
1120 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001121 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1122 listSupportedCategories();
1123 exit(0);
1124 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001125 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001126
1127 default:
1128 fprintf(stderr, "\n");
1129 showHelp(argv[0]);
1130 exit(-1);
1131 break;
1132 }
1133 }
1134
1135 registerSigHandler();
1136
1137 if (g_initialSleepSecs > 0) {
1138 sleep(g_initialSleepSecs);
1139 }
1140
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001141 bool ok = true;
1142 ok &= setUpTrace();
1143 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001144
1145 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001146 if (!traceStream) {
1147 printf("capturing trace...");
1148 fflush(stdout);
1149 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001150
1151 // We clear the trace after starting it because tracing gets enabled for
1152 // each CPU individually in the kernel. Having the beginning of the trace
1153 // contain entries from only one CPU can cause "begin" entries without a
1154 // matching "end" entry to show up if a task gets migrated from one CPU to
1155 // another.
1156 ok = clearTrace();
1157
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001158 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001159 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001160 // Sleep to allow the trace to be captured.
1161 struct timespec timeLeft;
1162 timeLeft.tv_sec = g_traceDurationSeconds;
1163 timeLeft.tv_nsec = 0;
1164 do {
1165 if (g_traceAborted) {
1166 break;
1167 }
1168 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1169 }
Martijn Coenend9535872015-11-26 10:00:55 +01001170
1171 if (traceStream) {
1172 streamTrace();
1173 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001174 }
1175
1176 // Stop the trace and restore the default settings.
1177 if (traceStop)
1178 stopTrace();
1179
1180 if (ok && traceDump) {
1181 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001182 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001183 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001184 int outFd = STDOUT_FILENO;
1185 if (g_outputFile) {
1186 outFd = open(g_outputFile, O_WRONLY | O_CREAT);
1187 }
1188 if (outFd == -1) {
1189 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1190 } else {
1191 dprintf(outFd, "TRACE:\n");
1192 dumpTrace(outFd);
1193 if (g_outputFile) {
1194 close(outFd);
1195 }
1196 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001197 } else {
1198 printf("\ntrace aborted.\n");
1199 fflush(stdout);
1200 }
1201 clearTrace();
1202 } else if (!ok) {
1203 fprintf(stderr, "unable to start tracing\n");
1204 }
1205
1206 // Reset the trace buffer size to 1.
1207 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001208 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001209
1210 return g_traceAborted ? 1 : 0;
1211}