blob: 290d7a85a612a6465c32b39ed578968a71508d3c [file] [log] [blame]
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
John Reck40b26b42016-03-30 09:44:36 -070017 #define LOG_TAG "atrace"
18
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080019#include <errno.h>
20#include <fcntl.h>
21#include <getopt.h>
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070022#include <inttypes.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080023#include <signal.h>
24#include <stdarg.h>
25#include <stdbool.h>
26#include <stdio.h>
27#include <stdlib.h>
Elliott Hughes3da5d232015-01-25 08:35:20 -080028#include <string.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080029#include <sys/sendfile.h>
30#include <time.h>
Martijn Coenend9535872015-11-26 10:00:55 +010031#include <unistd.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080032#include <zlib.h>
33
Elliott Hughesa252f4d2016-07-21 17:12:15 -070034#include <memory>
35
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080036#include <binder/IBinder.h>
37#include <binder/IServiceManager.h>
38#include <binder/Parcel.h>
39
40#include <cutils/properties.h>
41
42#include <utils/String8.h>
John Reck469a1942015-03-26 15:31:35 -070043#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +090044#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080045#include <utils/Trace.h>
Stephane Gasparinid8419c22016-03-02 13:45:15 +010046#include <android-base/file.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080047
48using namespace android;
49
50#define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0])))
51
sergeyv4144eff2016-04-28 11:40:04 -070052#define MAX_SYS_FILES 10
53#define MAX_PACKAGES 16
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080054
55const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
sergeyv4144eff2016-04-28 11:40:04 -070056
57const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
58const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070059const char* k_coreServiceCategory = "core_services";
60const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080061
62typedef enum { OPT, REQ } requiredness ;
63
64struct TracingCategory {
65 // The name identifying the category.
66 const char* name;
67
68 // A longer description of the category.
69 const char* longname;
70
71 // The userland tracing tags that the category enables.
72 uint64_t tags;
73
74 // The fname==NULL terminated list of /sys/ files that the category
75 // enables.
76 struct {
77 // Whether the file must be writable in order to enable the tracing
78 // category.
79 requiredness required;
80
81 // The path to the enable file.
82 const char* path;
83 } sysfiles[MAX_SYS_FILES];
84};
85
86/* Tracing categories */
87static const TracingCategory k_categories[] = {
Jamie Gennisb2a89e32013-03-11 19:37:53 -070088 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, { } },
89 { "input", "Input", ATRACE_TAG_INPUT, { } },
90 { "view", "View System", ATRACE_TAG_VIEW, { } },
91 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
92 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
93 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -050094 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070095 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
96 { "video", "Video", ATRACE_TAG_VIDEO, { } },
97 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
98 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -070099 { "app", "Application", ATRACE_TAG_APP, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -0700100 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -0700101 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -0700102 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -0700103 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700104 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 14:36:20 -0700105 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-07-01 01:46:25 +0900106 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Greg Hackmannbbd7d992014-12-01 14:43:34 -0800107 { "database", "Database", ATRACE_TAG_DATABASE, { } },
sergeyvdb404152016-05-02 19:26:07 -0700108 { k_coreServiceCategory, "Core services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700109 { "sched", "CPU Scheduling", 0, {
110 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_switch/enable" },
111 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_wakeup/enable" },
Riley Andrews5672bb72015-11-19 13:31:17 -0800112 { OPT, "/sys/kernel/debug/tracing/events/sched/sched_blocked_reason/enable" },
Ruchi Kandoicfe500d2015-11-23 13:47:20 -0800113 { OPT, "/sys/kernel/debug/tracing/events/sched/sched_cpu_hotplug/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800114 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700115 { "irq", "IRQ Events", 0, {
116 { REQ, "/sys/kernel/debug/tracing/events/irq/enable" },
Riley Andrews412e4f62015-11-02 21:01:34 -0800117 { OPT, "/sys/kernel/debug/tracing/events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700118 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700119 { "freq", "CPU Frequency", 0, {
120 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_frequency/enable" },
121 { OPT, "/sys/kernel/debug/tracing/events/power/clock_set_rate/enable" },
Ruchi Kandoiffcc7112015-11-19 18:32:00 -0800122 { OPT, "/sys/kernel/debug/tracing/events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800123 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700124 { "membus", "Memory Bus Utilization", 0, {
125 { REQ, "/sys/kernel/debug/tracing/events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800126 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700127 { "idle", "CPU Idle", 0, {
128 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800129 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700130 { "disk", "Disk I/O", 0, {
Greg Hackmanne80d32c2014-11-20 12:59:44 -0800131 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_enter/enable" },
132 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_exit/enable" },
133 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_begin/enable" },
134 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_end/enable" },
135 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_begin/enable" },
136 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_end/enable" },
137 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable" },
138 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable" },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700139 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" },
140 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800141 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700142 { "mmc", "eMMC commands", 0, {
143 { REQ, "/sys/kernel/debug/tracing/events/mmc/enable" },
144 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700145 { "load", "CPU Load", 0, {
146 { REQ, "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800147 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700148 { "sync", "Synchronization", 0, {
149 { REQ, "/sys/kernel/debug/tracing/events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800150 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700151 { "workq", "Kernel Workqueues", 0, {
152 { REQ, "/sys/kernel/debug/tracing/events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800153 } },
Colin Cross580407f2014-08-18 15:22:13 -0700154 { "memreclaim", "Kernel Memory Reclaim", 0, {
155 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
156 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
157 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_wake/enable" },
158 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_sleep/enable" },
159 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800160 { "regulators", "Voltage and Current Regulators", 0, {
161 { REQ, "/sys/kernel/debug/tracing/events/regulator/enable" },
162 } },
Scott Bauerae473362015-06-08 16:32:36 -0700163 { "binder_driver", "Binder Kernel driver", 0, {
164 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction/enable" },
165 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction_received/enable" },
166 } },
167 { "binder_lock", "Binder global lock trace", 0, {
168 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_lock/enable" },
169 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_locked/enable" },
170 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_unlock/enable" },
171 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200172 { "pagecache", "Page cache", 0, {
173 { REQ, "/sys/kernel/debug/tracing/events/filemap/enable" },
174 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800175};
176
177/* Command line options */
178static int g_traceDurationSeconds = 5;
179static bool g_traceOverwrite = false;
180static int g_traceBufferSizeKB = 2048;
181static bool g_compress = false;
182static bool g_nohup = false;
183static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900184static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700185static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700186static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700187static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800188
189/* Global state */
190static bool g_traceAborted = false;
191static bool g_categoryEnables[NELEM(k_categories)] = {};
192
193/* Sys file paths */
194static const char* k_traceClockPath =
195 "/sys/kernel/debug/tracing/trace_clock";
196
197static const char* k_traceBufferSizePath =
198 "/sys/kernel/debug/tracing/buffer_size_kb";
199
200static const char* k_tracingOverwriteEnablePath =
201 "/sys/kernel/debug/tracing/options/overwrite";
202
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700203static const char* k_currentTracerPath =
204 "/sys/kernel/debug/tracing/current_tracer";
205
206static const char* k_printTgidPath =
207 "/sys/kernel/debug/tracing/options/print-tgid";
208
209static const char* k_funcgraphAbsTimePath =
210 "/sys/kernel/debug/tracing/options/funcgraph-abstime";
211
212static const char* k_funcgraphCpuPath =
213 "/sys/kernel/debug/tracing/options/funcgraph-cpu";
214
215static const char* k_funcgraphProcPath =
216 "/sys/kernel/debug/tracing/options/funcgraph-proc";
217
218static const char* k_funcgraphFlatPath =
219 "/sys/kernel/debug/tracing/options/funcgraph-flat";
220
221static const char* k_funcgraphDurationPath =
222 "/sys/kernel/debug/tracing/options/funcgraph-duration";
223
224static const char* k_ftraceFilterPath =
225 "/sys/kernel/debug/tracing/set_ftrace_filter";
226
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800227static const char* k_tracingOnPath =
228 "/sys/kernel/debug/tracing/tracing_on";
229
230static const char* k_tracePath =
231 "/sys/kernel/debug/tracing/trace";
232
Martijn Coenend9535872015-11-26 10:00:55 +0100233static const char* k_traceStreamPath =
234 "/sys/kernel/debug/tracing/trace_pipe";
235
John Reck469a1942015-03-26 15:31:35 -0700236static const char* k_traceMarkerPath =
237 "/sys/kernel/debug/tracing/trace_marker";
238
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800239// Check whether a file exists.
240static bool fileExists(const char* filename) {
241 return access(filename, F_OK) != -1;
242}
243
244// Check whether a file is writable.
245static bool fileIsWritable(const char* filename) {
246 return access(filename, W_OK) != -1;
247}
248
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700249// Truncate a file.
250static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800251{
Jamie Gennis43122e72013-03-21 14:06:31 -0700252 // This uses creat rather than truncate because some of the debug kernel
253 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
254 // calls to truncate, but they are cleared by calls to creat.
255 int traceFD = creat(path, 0);
256 if (traceFD == -1) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700257 fprintf(stderr, "error truncating %s: %s (%d)\n", path,
Jamie Gennis43122e72013-03-21 14:06:31 -0700258 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700259 return false;
260 }
261
Jamie Gennis43122e72013-03-21 14:06:31 -0700262 close(traceFD);
263
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700264 return true;
265}
266
267static bool _writeStr(const char* filename, const char* str, int flags)
268{
269 int fd = open(filename, flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800270 if (fd == -1) {
271 fprintf(stderr, "error opening %s: %s (%d)\n", filename,
272 strerror(errno), errno);
273 return false;
274 }
275
276 bool ok = true;
277 ssize_t len = strlen(str);
278 if (write(fd, str, len) != len) {
279 fprintf(stderr, "error writing to %s: %s (%d)\n", filename,
280 strerror(errno), errno);
281 ok = false;
282 }
283
284 close(fd);
285
286 return ok;
287}
288
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700289// Write a string to a file, returning true if the write was successful.
290static bool writeStr(const char* filename, const char* str)
291{
292 return _writeStr(filename, str, O_WRONLY);
293}
294
295// Append a string to a file, returning true if the write was successful.
296static bool appendStr(const char* filename, const char* str)
297{
298 return _writeStr(filename, str, O_APPEND|O_WRONLY);
299}
300
John Reck469a1942015-03-26 15:31:35 -0700301static void writeClockSyncMarker()
302{
303 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200304 int len = 0;
305 int fd = open(k_traceMarkerPath, O_WRONLY);
306 if (fd == -1) {
307 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
308 strerror(errno), errno);
309 return;
310 }
John Reck469a1942015-03-26 15:31:35 -0700311 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200312
313 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
314 if (write(fd, buffer, len) != len) {
315 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
316 }
317
318 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
319 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
320 if (write(fd, buffer, len) != len) {
321 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
322 }
323
324 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700325}
326
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800327// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
328// file.
329static bool setKernelOptionEnable(const char* filename, bool enable)
330{
331 return writeStr(filename, enable ? "1" : "0");
332}
333
334// Check whether the category is supported on the device with the current
335// rootness. A category is supported only if all its required /sys/ files are
336// writable and if enabling the category will enable one or more tracing tags
337// or /sys/ files.
338static bool isCategorySupported(const TracingCategory& category)
339{
sergeyvdb404152016-05-02 19:26:07 -0700340 if (strcmp(category.name, k_coreServiceCategory) == 0) {
341 char value[PROPERTY_VALUE_MAX];
342 property_get(k_coreServicesProp, value, "");
343 return strlen(value) != 0;
344 }
345
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800346 bool ok = category.tags != 0;
347 for (int i = 0; i < MAX_SYS_FILES; i++) {
348 const char* path = category.sysfiles[i].path;
349 bool req = category.sysfiles[i].required == REQ;
350 if (path != NULL) {
351 if (req) {
352 if (!fileIsWritable(path)) {
353 return false;
354 } else {
355 ok = true;
356 }
357 } else {
358 ok |= fileIsWritable(path);
359 }
360 }
361 }
362 return ok;
363}
364
365// Check whether the category would be supported on the device if the user
366// were root. This function assumes that root is able to write to any file
367// that exists. It performs the same logic as isCategorySupported, but it
368// uses file existance rather than writability in the /sys/ file checks.
369static bool isCategorySupportedForRoot(const TracingCategory& category)
370{
371 bool ok = category.tags != 0;
372 for (int i = 0; i < MAX_SYS_FILES; i++) {
373 const char* path = category.sysfiles[i].path;
374 bool req = category.sysfiles[i].required == REQ;
375 if (path != NULL) {
376 if (req) {
377 if (!fileExists(path)) {
378 return false;
379 } else {
380 ok = true;
381 }
382 } else {
383 ok |= fileExists(path);
384 }
385 }
386 }
387 return ok;
388}
389
390// Enable or disable overwriting of the kernel trace buffers. Disabling this
391// will cause tracing to stop once the trace buffers have filled up.
392static bool setTraceOverwriteEnable(bool enable)
393{
394 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
395}
396
397// Enable or disable kernel tracing.
398static bool setTracingEnabled(bool enable)
399{
400 return setKernelOptionEnable(k_tracingOnPath, enable);
401}
402
403// Clear the contents of the kernel trace.
404static bool clearTrace()
405{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700406 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800407}
408
409// Set the size of the kernel's trace buffer in kilobytes.
410static bool setTraceBufferSizeKB(int size)
411{
412 char str[32] = "1";
413 int len;
414 if (size < 1) {
415 size = 1;
416 }
417 snprintf(str, 32, "%d", size);
418 return writeStr(k_traceBufferSizePath, str);
419}
420
Colin Crossb1ce49b2014-08-20 14:28:47 -0700421// Read the trace_clock sysfs file and return true if it matches the requested
422// value. The trace_clock file format is:
423// local [global] counter uptime perf
424static bool isTraceClock(const char *mode)
425{
426 int fd = open(k_traceClockPath, O_RDONLY);
427 if (fd == -1) {
428 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceClockPath,
429 strerror(errno), errno);
430 return false;
431 }
432
433 char buf[4097];
434 ssize_t n = read(fd, buf, 4096);
435 close(fd);
436 if (n == -1) {
437 fprintf(stderr, "error reading %s: %s (%d)\n", k_traceClockPath,
438 strerror(errno), errno);
439 return false;
440 }
441 buf[n] = '\0';
442
443 char *start = strchr(buf, '[');
444 if (start == NULL) {
445 return false;
446 }
447 start++;
448
449 char *end = strchr(start, ']');
450 if (end == NULL) {
451 return false;
452 }
453 *end = '\0';
454
455 return strcmp(mode, start) == 0;
456}
457
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800458// Enable or disable the kernel's use of the global clock. Disabling the global
459// clock will result in the kernel using a per-CPU local clock.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700460// Any write to the trace_clock sysfs file will reset the buffer, so only
461// update it if the requested value is not the current value.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800462static bool setGlobalClockEnable(bool enable)
463{
Colin Crossb1ce49b2014-08-20 14:28:47 -0700464 const char *clock = enable ? "global" : "local";
465
466 if (isTraceClock(clock)) {
467 return true;
468 }
469
470 return writeStr(k_traceClockPath, clock);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800471}
472
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700473static bool setPrintTgidEnableIfPresent(bool enable)
474{
475 if (fileExists(k_printTgidPath)) {
476 return setKernelOptionEnable(k_printTgidPath, enable);
477 }
478 return true;
479}
480
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800481// Poke all the binder-enabled processes in the system to get them to re-read
482// their system properties.
483static bool pokeBinderServices()
484{
485 sp<IServiceManager> sm = defaultServiceManager();
486 Vector<String16> services = sm->listServices();
487 for (size_t i = 0; i < services.size(); i++) {
488 sp<IBinder> obj = sm->checkService(services[i]);
489 if (obj != NULL) {
490 Parcel data;
491 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
492 NULL, 0) != OK) {
493 if (false) {
494 // XXX: For some reason this fails on tablets trying to
495 // poke the "phone" service. It's not clear whether some
496 // are expected to fail.
497 String8 svc(services[i]);
498 fprintf(stderr, "error poking binder service %s\n",
499 svc.string());
500 return false;
501 }
502 }
503 }
504 }
505 return true;
506}
507
508// Set the trace tags that userland tracing uses, and poke the running
509// processes to pick up the new value.
510static bool setTagsProperty(uint64_t tags)
511{
sergeyv4144eff2016-04-28 11:40:04 -0700512 char buf[PROPERTY_VALUE_MAX];
513 snprintf(buf, sizeof(buf), "%#" PRIx64, tags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800514 if (property_set(k_traceTagsProperty, buf) < 0) {
515 fprintf(stderr, "error setting trace tags system property\n");
516 return false;
517 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700518 return true;
519}
520
sergeyv4144eff2016-04-28 11:40:04 -0700521static void clearAppProperties()
522{
523 char buf[PROPERTY_KEY_MAX];
524 for (int i = 0; i < MAX_PACKAGES; i++) {
525 snprintf(buf, sizeof(buf), k_traceAppsPropertyTemplate, i);
526 if (property_set(buf, "") < 0) {
527 fprintf(stderr, "failed to clear system property: %s\n", buf);
528 }
529 }
530 if (property_set(k_traceAppsNumberProperty, "") < 0) {
531 fprintf(stderr, "failed to clear system property: %s",
532 k_traceAppsNumberProperty);
533 }
534}
535
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700536// Set the system property that indicates which apps should perform
537// application-level tracing.
Dan Austin497951c2016-05-31 13:27:03 -0700538static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700539{
sergeyv4144eff2016-04-28 11:40:04 -0700540 char buf[PROPERTY_KEY_MAX];
541 int i = 0;
Dan Austin497951c2016-05-31 13:27:03 -0700542 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700543 while (start != NULL) {
544 if (i == MAX_PACKAGES) {
545 fprintf(stderr, "error: only 16 packages could be traced at once\n");
546 clearAppProperties();
547 return false;
548 }
549 char* end = strchr(start, ',');
550 if (end != NULL) {
551 *end = '\0';
552 end++;
553 }
554 snprintf(buf, sizeof(buf), k_traceAppsPropertyTemplate, i);
555 if (property_set(buf, start) < 0) {
556 fprintf(stderr, "error setting trace app %d property to %s\n", i, buf);
557 clearAppProperties();
558 return false;
559 }
560 start = end;
561 i++;
562 }
563
564 snprintf(buf, sizeof(buf), "%d", i);
565 if (property_set(k_traceAppsNumberProperty, buf) < 0) {
566 fprintf(stderr, "error setting trace app number property to %s\n", buf);
567 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700568 return false;
569 }
570 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800571}
572
573// Disable all /sys/ enable files.
574static bool disableKernelTraceEvents() {
575 bool ok = true;
576 for (int i = 0; i < NELEM(k_categories); i++) {
577 const TracingCategory &c = k_categories[i];
578 for (int j = 0; j < MAX_SYS_FILES; j++) {
579 const char* path = c.sysfiles[j].path;
580 if (path != NULL && fileIsWritable(path)) {
581 ok &= setKernelOptionEnable(path, false);
582 }
583 }
584 }
585 return ok;
586}
587
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700588// Verify that the comma separated list of functions are being traced by the
589// kernel.
590static bool verifyKernelTraceFuncs(const char* funcs)
591{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100592 std::string buf;
593 if (!android::base::ReadFileToString(k_ftraceFilterPath, &buf)) {
594 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700595 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100596 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700597 }
598
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100599 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700600
601 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100602 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700603 bool ok = true;
604 char* myFuncs = strdup(funcs);
605 char* func = strtok(myFuncs, ",");
606 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100607 if (!strchr(func, '*')) {
608 String8 fancyFunc = String8::format("\n%s\n", func);
609 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
610 if (!found || func[0] == '\0') {
611 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
612 "to trace.\n", func);
613 ok = false;
614 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700615 }
616 func = strtok(NULL, ",");
617 }
618 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700619 return ok;
620}
621
622// Set the comma separated list of functions that the kernel is to trace.
623static bool setKernelTraceFuncs(const char* funcs)
624{
625 bool ok = true;
626
627 if (funcs == NULL || funcs[0] == '\0') {
628 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700629 if (fileIsWritable(k_currentTracerPath)) {
630 ok &= writeStr(k_currentTracerPath, "nop");
631 }
632 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700633 ok &= truncateFile(k_ftraceFilterPath);
634 }
635 } else {
636 // Enable kernel function tracing.
637 ok &= writeStr(k_currentTracerPath, "function_graph");
638 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
639 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
640 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
641 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
642
643 // Set the requested filter functions.
644 ok &= truncateFile(k_ftraceFilterPath);
645 char* myFuncs = strdup(funcs);
646 char* func = strtok(myFuncs, ",");
647 while (func) {
648 ok &= appendStr(k_ftraceFilterPath, func);
649 func = strtok(NULL, ",");
650 }
651 free(myFuncs);
652
653 // Verify that the set functions are being traced.
654 if (ok) {
655 ok &= verifyKernelTraceFuncs(funcs);
656 }
657 }
658
659 return ok;
660}
661
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900662static bool setCategoryEnable(const char* name, bool enable)
663{
664 for (int i = 0; i < NELEM(k_categories); i++) {
665 const TracingCategory& c = k_categories[i];
666 if (strcmp(name, c.name) == 0) {
667 if (isCategorySupported(c)) {
668 g_categoryEnables[i] = enable;
669 return true;
670 } else {
671 if (isCategorySupportedForRoot(c)) {
672 fprintf(stderr, "error: category \"%s\" requires root "
673 "privileges.\n", name);
674 } else {
675 fprintf(stderr, "error: category \"%s\" is not supported "
676 "on this device.\n", name);
677 }
678 return false;
679 }
680 }
681 }
682 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
683 return false;
684}
685
686static bool setCategoriesEnableFromFile(const char* categories_file)
687{
688 if (!categories_file) {
689 return true;
690 }
691 Tokenizer* tokenizer = NULL;
692 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
693 return false;
694 }
695 bool ok = true;
696 while (!tokenizer->isEol()) {
697 String8 token = tokenizer->nextToken(" ");
698 if (token.isEmpty()) {
699 tokenizer->skipDelimiters(" ");
700 continue;
701 }
702 ok &= setCategoryEnable(token.string(), true);
703 }
704 delete tokenizer;
705 return ok;
706}
707
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700708// Set all the kernel tracing settings to the desired state for this trace
709// capture.
710static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800711{
712 bool ok = true;
713
714 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900715 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800716 ok &= setTraceOverwriteEnable(g_traceOverwrite);
717 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
718 ok &= setGlobalClockEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700719 ok &= setPrintTgidEnableIfPresent(true);
720 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800721
722 // Set up the tags property.
723 uint64_t tags = 0;
724 for (int i = 0; i < NELEM(k_categories); i++) {
725 if (g_categoryEnables[i]) {
726 const TracingCategory &c = k_categories[i];
727 tags |= c.tags;
728 }
729 }
730 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700731
732 bool coreServicesTagEnabled = false;
733 for (int i = 0; i < NELEM(k_categories); i++) {
734 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
735 coreServicesTagEnabled = g_categoryEnables[i];
736 }
737 }
738
739 std::string packageList(g_debugAppCmdLine);
740 if (coreServicesTagEnabled) {
741 char value[PROPERTY_VALUE_MAX];
742 property_get(k_coreServicesProp, value, "");
743 if (!packageList.empty()) {
744 packageList += ",";
745 }
746 packageList += value;
747 }
Dan Austin497951c2016-05-31 13:27:03 -0700748 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700749 ok &= pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800750
751 // Disable all the sysfs enables. This is done as a separate loop from
752 // the enables to allow the same enable to exist in multiple categories.
753 ok &= disableKernelTraceEvents();
754
755 // Enable all the sysfs enables that are in an enabled category.
756 for (int i = 0; i < NELEM(k_categories); i++) {
757 if (g_categoryEnables[i]) {
758 const TracingCategory &c = k_categories[i];
759 for (int j = 0; j < MAX_SYS_FILES; j++) {
760 const char* path = c.sysfiles[j].path;
761 bool required = c.sysfiles[j].required == REQ;
762 if (path != NULL) {
763 if (fileIsWritable(path)) {
764 ok &= setKernelOptionEnable(path, true);
765 } else if (required) {
766 fprintf(stderr, "error writing file %s\n", path);
767 ok = false;
768 }
769 }
770 }
771 }
772 }
773
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800774 return ok;
775}
776
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700777// Reset all the kernel tracing settings to their default state.
778static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800779{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800780 // Disable all tracing that we're able to.
781 disableKernelTraceEvents();
782
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700783 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800784 setTagsProperty(0);
sergeyv4144eff2016-04-28 11:40:04 -0700785 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700786 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800787
788 // Set the options back to their defaults.
789 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700790 setTraceBufferSizeKB(1);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800791 setGlobalClockEnable(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700792 setPrintTgidEnableIfPresent(false);
793 setKernelTraceFuncs(NULL);
794}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800795
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700796
797// Enable tracing in the kernel.
798static bool startTrace()
799{
800 return setTracingEnabled(true);
801}
802
803// Disable tracing in the kernel.
804static void stopTrace()
805{
806 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800807}
808
Martijn Coenend9535872015-11-26 10:00:55 +0100809// Read data from the tracing pipe and forward to stdout
810static void streamTrace()
811{
812 char trace_data[4096];
813 int traceFD = open(k_traceStreamPath, O_RDWR);
814 if (traceFD == -1) {
815 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
816 strerror(errno), errno);
817 return;
818 }
819 while (!g_traceAborted) {
820 ssize_t bytes_read = read(traceFD, trace_data, 4096);
821 if (bytes_read > 0) {
822 write(STDOUT_FILENO, trace_data, bytes_read);
823 fflush(stdout);
824 } else {
825 if (!g_traceAborted) {
826 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
827 bytes_read, errno, strerror(errno));
828 }
829 break;
830 }
831 }
832}
833
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800834// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700835static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800836{
John Reck6c8ac922016-03-28 11:25:30 -0700837 ALOGI("Dumping trace");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800838 int traceFD = open(k_tracePath, O_RDWR);
839 if (traceFD == -1) {
840 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
841 strerror(errno), errno);
842 return;
843 }
844
845 if (g_compress) {
846 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800847 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700848
849 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800850 if (result != Z_OK) {
851 fprintf(stderr, "error initializing zlib: %d\n", result);
852 close(traceFD);
853 return;
854 }
855
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700856 constexpr size_t bufSize = 64*1024;
857 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
858 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
859 if (!in || !out) {
860 fprintf(stderr, "couldn't allocate buffers\n");
861 close(traceFD);
862 return;
863 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800864
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700865 int flush = Z_NO_FLUSH;
866
867 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800868 zs.avail_out = bufSize;
869
870 do {
871
872 if (zs.avail_in == 0) {
873 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700874 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800875 if (result < 0) {
876 fprintf(stderr, "error reading trace: %s (%d)\n",
877 strerror(errno), errno);
878 result = Z_STREAM_END;
879 break;
880 } else if (result == 0) {
881 flush = Z_FINISH;
882 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700883 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800884 zs.avail_in = result;
885 }
886 }
887
888 if (zs.avail_out == 0) {
889 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700890 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800891 if ((size_t)result < bufSize) {
892 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
893 strerror(errno), errno);
894 result = Z_STREAM_END; // skip deflate error message
895 zs.avail_out = bufSize; // skip the final write
896 break;
897 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700898 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800899 zs.avail_out = bufSize;
900 }
901
902 } while ((result = deflate(&zs, flush)) == Z_OK);
903
904 if (result != Z_STREAM_END) {
905 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
906 }
907
908 if (zs.avail_out < bufSize) {
909 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -0700910 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800911 if ((size_t)result < bytes) {
912 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
913 strerror(errno), errno);
914 }
915 }
916
917 result = deflateEnd(&zs);
918 if (result != Z_OK) {
919 fprintf(stderr, "error cleaning up zlib: %d\n", result);
920 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800921 } else {
922 ssize_t sent = 0;
John Reck40b26b42016-03-30 09:44:36 -0700923 while ((sent = sendfile(outFd, traceFD, NULL, 64*1024*1024)) > 0);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800924 if (sent == -1) {
925 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
926 errno);
927 }
928 }
929
930 close(traceFD);
931}
932
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700933static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800934{
935 if (!g_nohup) {
936 g_traceAborted = true;
937 }
938}
939
940static void registerSigHandler()
941{
942 struct sigaction sa;
943 sigemptyset(&sa.sa_mask);
944 sa.sa_flags = 0;
945 sa.sa_handler = handleSignal;
946 sigaction(SIGHUP, &sa, NULL);
947 sigaction(SIGINT, &sa, NULL);
948 sigaction(SIGQUIT, &sa, NULL);
949 sigaction(SIGTERM, &sa, NULL);
950}
951
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800952static void listSupportedCategories()
953{
954 for (int i = 0; i < NELEM(k_categories); i++) {
955 const TracingCategory& c = k_categories[i];
956 if (isCategorySupported(c)) {
957 printf(" %10s - %s\n", c.name, c.longname);
958 }
959 }
960}
961
962// Print the command usage help to stderr.
963static void showHelp(const char *cmd)
964{
965 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
966 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700967 " -a appname enable app-level tracing for a comma "
968 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800969 " -b N use a trace buffer size of N KB\n"
970 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900971 " -f filename use the categories written in a file as space-separated\n"
972 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700973 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800974 " -n ignore signals\n"
975 " -s N sleep for N seconds before tracing [default 0]\n"
Elliott Hughesf884a062016-07-22 09:38:44 -0700976 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800977 " -z compress the trace dump\n"
978 " --async_start start circular trace and return immediatly\n"
979 " --async_dump dump the current contents of circular trace buffer\n"
980 " --async_stop stop tracing and dump the current contents of circular\n"
981 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +0100982 " --stream stream trace to stdout as it enters the trace buffer\n"
983 " Note: this can take significant CPU time, and is best\n"
984 " used for measuring things that are not affected by\n"
985 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -0800986 " --list_categories\n"
987 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -0700988 " -o filename write the trace to the specified file instead\n"
989 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800990 );
991}
992
993int main(int argc, char **argv)
994{
995 bool async = false;
996 bool traceStart = true;
997 bool traceStop = true;
998 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +0100999 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001000
1001 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1002 showHelp(argv[0]);
1003 exit(0);
1004 }
1005
1006 for (;;) {
1007 int ret;
1008 int option_index = 0;
1009 static struct option long_options[] = {
1010 {"async_start", no_argument, 0, 0 },
1011 {"async_stop", no_argument, 0, 0 },
1012 {"async_dump", no_argument, 0, 0 },
1013 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +01001014 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001015 { 0, 0, 0, 0 }
1016 };
1017
John Reck40b26b42016-03-30 09:44:36 -07001018 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001019 long_options, &option_index);
1020
1021 if (ret < 0) {
1022 for (int i = optind; i < argc; i++) {
1023 if (!setCategoryEnable(argv[i], true)) {
1024 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1025 exit(1);
1026 }
1027 }
1028 break;
1029 }
1030
1031 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001032 case 'a':
1033 g_debugAppCmdLine = optarg;
1034 break;
1035
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001036 case 'b':
1037 g_traceBufferSizeKB = atoi(optarg);
1038 break;
1039
1040 case 'c':
1041 g_traceOverwrite = true;
1042 break;
1043
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001044 case 'f':
1045 g_categoriesFile = optarg;
1046 break;
1047
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001048 case 'k':
1049 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001050 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001051
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001052 case 'n':
1053 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001054 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001055
1056 case 's':
1057 g_initialSleepSecs = atoi(optarg);
1058 break;
1059
1060 case 't':
1061 g_traceDurationSeconds = atoi(optarg);
1062 break;
1063
1064 case 'z':
1065 g_compress = true;
1066 break;
1067
John Reck40b26b42016-03-30 09:44:36 -07001068 case 'o':
1069 g_outputFile = optarg;
1070 break;
1071
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001072 case 0:
1073 if (!strcmp(long_options[option_index].name, "async_start")) {
1074 async = true;
1075 traceStop = false;
1076 traceDump = false;
1077 g_traceOverwrite = true;
1078 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1079 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001080 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001081 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1082 async = true;
1083 traceStart = false;
1084 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001085 } else if (!strcmp(long_options[option_index].name, "stream")) {
1086 traceStream = true;
1087 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001088 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1089 listSupportedCategories();
1090 exit(0);
1091 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001092 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001093
1094 default:
1095 fprintf(stderr, "\n");
1096 showHelp(argv[0]);
1097 exit(-1);
1098 break;
1099 }
1100 }
1101
1102 registerSigHandler();
1103
1104 if (g_initialSleepSecs > 0) {
1105 sleep(g_initialSleepSecs);
1106 }
1107
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001108 bool ok = true;
1109 ok &= setUpTrace();
1110 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001111
1112 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001113 if (!traceStream) {
1114 printf("capturing trace...");
1115 fflush(stdout);
1116 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001117
1118 // We clear the trace after starting it because tracing gets enabled for
1119 // each CPU individually in the kernel. Having the beginning of the trace
1120 // contain entries from only one CPU can cause "begin" entries without a
1121 // matching "end" entry to show up if a task gets migrated from one CPU to
1122 // another.
1123 ok = clearTrace();
1124
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001125 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001126 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001127 // Sleep to allow the trace to be captured.
1128 struct timespec timeLeft;
1129 timeLeft.tv_sec = g_traceDurationSeconds;
1130 timeLeft.tv_nsec = 0;
1131 do {
1132 if (g_traceAborted) {
1133 break;
1134 }
1135 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1136 }
Martijn Coenend9535872015-11-26 10:00:55 +01001137
1138 if (traceStream) {
1139 streamTrace();
1140 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001141 }
1142
1143 // Stop the trace and restore the default settings.
1144 if (traceStop)
1145 stopTrace();
1146
1147 if (ok && traceDump) {
1148 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001149 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001150 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001151 int outFd = STDOUT_FILENO;
1152 if (g_outputFile) {
1153 outFd = open(g_outputFile, O_WRONLY | O_CREAT);
1154 }
1155 if (outFd == -1) {
1156 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1157 } else {
1158 dprintf(outFd, "TRACE:\n");
1159 dumpTrace(outFd);
1160 if (g_outputFile) {
1161 close(outFd);
1162 }
1163 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001164 } else {
1165 printf("\ntrace aborted.\n");
1166 fflush(stdout);
1167 }
1168 clearTrace();
1169 } else if (!ok) {
1170 fprintf(stderr, "unable to start tracing\n");
1171 }
1172
1173 // Reset the trace buffer size to 1.
1174 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001175 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001176
1177 return g_traceAborted ? 1 : 0;
1178}