blob: 4c0e242bb42f3e6f1bd185decc4eb86486a6e0df [file] [log] [blame]
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
John Reck40b26b42016-03-30 09:44:36 -070017 #define LOG_TAG "atrace"
18
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080019#include <errno.h>
20#include <fcntl.h>
21#include <getopt.h>
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070022#include <inttypes.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080023#include <signal.h>
24#include <stdarg.h>
25#include <stdbool.h>
26#include <stdio.h>
27#include <stdlib.h>
Elliott Hughes3da5d232015-01-25 08:35:20 -080028#include <string.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080029#include <sys/sendfile.h>
30#include <time.h>
Martijn Coenend9535872015-11-26 10:00:55 +010031#include <unistd.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080032#include <zlib.h>
33
Elliott Hughesa252f4d2016-07-21 17:12:15 -070034#include <memory>
35
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080036#include <binder/IBinder.h>
37#include <binder/IServiceManager.h>
38#include <binder/Parcel.h>
39
40#include <cutils/properties.h>
41
42#include <utils/String8.h>
John Reck469a1942015-03-26 15:31:35 -070043#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +090044#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080045#include <utils/Trace.h>
Stephane Gasparinid8419c22016-03-02 13:45:15 +010046#include <android-base/file.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080047
48using namespace android;
49
50#define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0])))
51
sergeyv4144eff2016-04-28 11:40:04 -070052#define MAX_SYS_FILES 10
53#define MAX_PACKAGES 16
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080054
55const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
sergeyv4144eff2016-04-28 11:40:04 -070056
57const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
58const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070059const char* k_coreServiceCategory = "core_services";
60const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080061
62typedef enum { OPT, REQ } requiredness ;
63
64struct TracingCategory {
65 // The name identifying the category.
66 const char* name;
67
68 // A longer description of the category.
69 const char* longname;
70
71 // The userland tracing tags that the category enables.
72 uint64_t tags;
73
74 // The fname==NULL terminated list of /sys/ files that the category
75 // enables.
76 struct {
77 // Whether the file must be writable in order to enable the tracing
78 // category.
79 requiredness required;
80
81 // The path to the enable file.
82 const char* path;
83 } sysfiles[MAX_SYS_FILES];
84};
85
86/* Tracing categories */
87static const TracingCategory k_categories[] = {
Jamie Gennisb2a89e32013-03-11 19:37:53 -070088 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, { } },
89 { "input", "Input", ATRACE_TAG_INPUT, { } },
90 { "view", "View System", ATRACE_TAG_VIEW, { } },
91 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
92 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
93 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -050094 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070095 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
96 { "video", "Video", ATRACE_TAG_VIDEO, { } },
97 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
98 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -070099 { "app", "Application", ATRACE_TAG_APP, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -0700100 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -0700101 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -0700102 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -0700103 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700104 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 14:36:20 -0700105 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-07-01 01:46:25 +0900106 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Greg Hackmannbbd7d992014-12-01 14:43:34 -0800107 { "database", "Database", ATRACE_TAG_DATABASE, { } },
Felipe Leme0f97c1d2016-09-07 11:33:26 -0700108 { "network", "Network", ATRACE_TAG_NETWORK, { } },
sergeyvdb404152016-05-02 19:26:07 -0700109 { k_coreServiceCategory, "Core services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700110 { "sched", "CPU Scheduling", 0, {
111 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_switch/enable" },
112 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_wakeup/enable" },
Riley Andrews5672bb72015-11-19 13:31:17 -0800113 { OPT, "/sys/kernel/debug/tracing/events/sched/sched_blocked_reason/enable" },
Ruchi Kandoicfe500d2015-11-23 13:47:20 -0800114 { OPT, "/sys/kernel/debug/tracing/events/sched/sched_cpu_hotplug/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800115 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700116 { "irq", "IRQ Events", 0, {
117 { REQ, "/sys/kernel/debug/tracing/events/irq/enable" },
Riley Andrews412e4f62015-11-02 21:01:34 -0800118 { OPT, "/sys/kernel/debug/tracing/events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700119 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700120 { "freq", "CPU Frequency", 0, {
121 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_frequency/enable" },
122 { OPT, "/sys/kernel/debug/tracing/events/power/clock_set_rate/enable" },
Ruchi Kandoiffcc7112015-11-19 18:32:00 -0800123 { OPT, "/sys/kernel/debug/tracing/events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800124 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700125 { "membus", "Memory Bus Utilization", 0, {
126 { REQ, "/sys/kernel/debug/tracing/events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800127 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700128 { "idle", "CPU Idle", 0, {
129 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800130 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700131 { "disk", "Disk I/O", 0, {
Greg Hackmanne80d32c2014-11-20 12:59:44 -0800132 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_enter/enable" },
133 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_exit/enable" },
134 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_begin/enable" },
135 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_end/enable" },
136 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_begin/enable" },
137 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_end/enable" },
138 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable" },
139 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable" },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700140 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" },
141 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800142 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700143 { "mmc", "eMMC commands", 0, {
144 { REQ, "/sys/kernel/debug/tracing/events/mmc/enable" },
145 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700146 { "load", "CPU Load", 0, {
147 { REQ, "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800148 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700149 { "sync", "Synchronization", 0, {
150 { REQ, "/sys/kernel/debug/tracing/events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800151 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700152 { "workq", "Kernel Workqueues", 0, {
153 { REQ, "/sys/kernel/debug/tracing/events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800154 } },
Colin Cross580407f2014-08-18 15:22:13 -0700155 { "memreclaim", "Kernel Memory Reclaim", 0, {
156 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
157 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
158 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_wake/enable" },
159 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_sleep/enable" },
160 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800161 { "regulators", "Voltage and Current Regulators", 0, {
162 { REQ, "/sys/kernel/debug/tracing/events/regulator/enable" },
163 } },
Scott Bauerae473362015-06-08 16:32:36 -0700164 { "binder_driver", "Binder Kernel driver", 0, {
165 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction/enable" },
166 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction_received/enable" },
167 } },
168 { "binder_lock", "Binder global lock trace", 0, {
169 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_lock/enable" },
170 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_locked/enable" },
171 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_unlock/enable" },
172 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200173 { "pagecache", "Page cache", 0, {
174 { REQ, "/sys/kernel/debug/tracing/events/filemap/enable" },
175 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800176};
177
178/* Command line options */
179static int g_traceDurationSeconds = 5;
180static bool g_traceOverwrite = false;
181static int g_traceBufferSizeKB = 2048;
182static bool g_compress = false;
183static bool g_nohup = false;
184static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900185static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700186static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700187static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700188static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800189
190/* Global state */
191static bool g_traceAborted = false;
192static bool g_categoryEnables[NELEM(k_categories)] = {};
193
194/* Sys file paths */
195static const char* k_traceClockPath =
196 "/sys/kernel/debug/tracing/trace_clock";
197
198static const char* k_traceBufferSizePath =
199 "/sys/kernel/debug/tracing/buffer_size_kb";
200
201static const char* k_tracingOverwriteEnablePath =
202 "/sys/kernel/debug/tracing/options/overwrite";
203
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700204static const char* k_currentTracerPath =
205 "/sys/kernel/debug/tracing/current_tracer";
206
207static const char* k_printTgidPath =
208 "/sys/kernel/debug/tracing/options/print-tgid";
209
210static const char* k_funcgraphAbsTimePath =
211 "/sys/kernel/debug/tracing/options/funcgraph-abstime";
212
213static const char* k_funcgraphCpuPath =
214 "/sys/kernel/debug/tracing/options/funcgraph-cpu";
215
216static const char* k_funcgraphProcPath =
217 "/sys/kernel/debug/tracing/options/funcgraph-proc";
218
219static const char* k_funcgraphFlatPath =
220 "/sys/kernel/debug/tracing/options/funcgraph-flat";
221
222static const char* k_funcgraphDurationPath =
223 "/sys/kernel/debug/tracing/options/funcgraph-duration";
224
225static const char* k_ftraceFilterPath =
226 "/sys/kernel/debug/tracing/set_ftrace_filter";
227
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800228static const char* k_tracingOnPath =
229 "/sys/kernel/debug/tracing/tracing_on";
230
231static const char* k_tracePath =
232 "/sys/kernel/debug/tracing/trace";
233
Martijn Coenend9535872015-11-26 10:00:55 +0100234static const char* k_traceStreamPath =
235 "/sys/kernel/debug/tracing/trace_pipe";
236
John Reck469a1942015-03-26 15:31:35 -0700237static const char* k_traceMarkerPath =
238 "/sys/kernel/debug/tracing/trace_marker";
239
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800240// Check whether a file exists.
241static bool fileExists(const char* filename) {
242 return access(filename, F_OK) != -1;
243}
244
245// Check whether a file is writable.
246static bool fileIsWritable(const char* filename) {
247 return access(filename, W_OK) != -1;
248}
249
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700250// Truncate a file.
251static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800252{
Jamie Gennis43122e72013-03-21 14:06:31 -0700253 // This uses creat rather than truncate because some of the debug kernel
254 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
255 // calls to truncate, but they are cleared by calls to creat.
256 int traceFD = creat(path, 0);
257 if (traceFD == -1) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700258 fprintf(stderr, "error truncating %s: %s (%d)\n", path,
Jamie Gennis43122e72013-03-21 14:06:31 -0700259 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700260 return false;
261 }
262
Jamie Gennis43122e72013-03-21 14:06:31 -0700263 close(traceFD);
264
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700265 return true;
266}
267
268static bool _writeStr(const char* filename, const char* str, int flags)
269{
270 int fd = open(filename, flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800271 if (fd == -1) {
272 fprintf(stderr, "error opening %s: %s (%d)\n", filename,
273 strerror(errno), errno);
274 return false;
275 }
276
277 bool ok = true;
278 ssize_t len = strlen(str);
279 if (write(fd, str, len) != len) {
280 fprintf(stderr, "error writing to %s: %s (%d)\n", filename,
281 strerror(errno), errno);
282 ok = false;
283 }
284
285 close(fd);
286
287 return ok;
288}
289
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700290// Write a string to a file, returning true if the write was successful.
291static bool writeStr(const char* filename, const char* str)
292{
293 return _writeStr(filename, str, O_WRONLY);
294}
295
296// Append a string to a file, returning true if the write was successful.
297static bool appendStr(const char* filename, const char* str)
298{
299 return _writeStr(filename, str, O_APPEND|O_WRONLY);
300}
301
John Reck469a1942015-03-26 15:31:35 -0700302static void writeClockSyncMarker()
303{
304 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200305 int len = 0;
306 int fd = open(k_traceMarkerPath, O_WRONLY);
307 if (fd == -1) {
308 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
309 strerror(errno), errno);
310 return;
311 }
John Reck469a1942015-03-26 15:31:35 -0700312 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200313
314 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
315 if (write(fd, buffer, len) != len) {
316 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
317 }
318
319 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
320 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
321 if (write(fd, buffer, len) != len) {
322 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
323 }
324
325 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700326}
327
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800328// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
329// file.
330static bool setKernelOptionEnable(const char* filename, bool enable)
331{
332 return writeStr(filename, enable ? "1" : "0");
333}
334
335// Check whether the category is supported on the device with the current
336// rootness. A category is supported only if all its required /sys/ files are
337// writable and if enabling the category will enable one or more tracing tags
338// or /sys/ files.
339static bool isCategorySupported(const TracingCategory& category)
340{
sergeyvdb404152016-05-02 19:26:07 -0700341 if (strcmp(category.name, k_coreServiceCategory) == 0) {
342 char value[PROPERTY_VALUE_MAX];
343 property_get(k_coreServicesProp, value, "");
344 return strlen(value) != 0;
345 }
346
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800347 bool ok = category.tags != 0;
348 for (int i = 0; i < MAX_SYS_FILES; i++) {
349 const char* path = category.sysfiles[i].path;
350 bool req = category.sysfiles[i].required == REQ;
351 if (path != NULL) {
352 if (req) {
353 if (!fileIsWritable(path)) {
354 return false;
355 } else {
356 ok = true;
357 }
358 } else {
359 ok |= fileIsWritable(path);
360 }
361 }
362 }
363 return ok;
364}
365
366// Check whether the category would be supported on the device if the user
367// were root. This function assumes that root is able to write to any file
368// that exists. It performs the same logic as isCategorySupported, but it
369// uses file existance rather than writability in the /sys/ file checks.
370static bool isCategorySupportedForRoot(const TracingCategory& category)
371{
372 bool ok = category.tags != 0;
373 for (int i = 0; i < MAX_SYS_FILES; i++) {
374 const char* path = category.sysfiles[i].path;
375 bool req = category.sysfiles[i].required == REQ;
376 if (path != NULL) {
377 if (req) {
378 if (!fileExists(path)) {
379 return false;
380 } else {
381 ok = true;
382 }
383 } else {
384 ok |= fileExists(path);
385 }
386 }
387 }
388 return ok;
389}
390
391// Enable or disable overwriting of the kernel trace buffers. Disabling this
392// will cause tracing to stop once the trace buffers have filled up.
393static bool setTraceOverwriteEnable(bool enable)
394{
395 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
396}
397
398// Enable or disable kernel tracing.
399static bool setTracingEnabled(bool enable)
400{
401 return setKernelOptionEnable(k_tracingOnPath, enable);
402}
403
404// Clear the contents of the kernel trace.
405static bool clearTrace()
406{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700407 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800408}
409
410// Set the size of the kernel's trace buffer in kilobytes.
411static bool setTraceBufferSizeKB(int size)
412{
413 char str[32] = "1";
414 int len;
415 if (size < 1) {
416 size = 1;
417 }
418 snprintf(str, 32, "%d", size);
419 return writeStr(k_traceBufferSizePath, str);
420}
421
Colin Crossb1ce49b2014-08-20 14:28:47 -0700422// Read the trace_clock sysfs file and return true if it matches the requested
423// value. The trace_clock file format is:
424// local [global] counter uptime perf
425static bool isTraceClock(const char *mode)
426{
427 int fd = open(k_traceClockPath, O_RDONLY);
428 if (fd == -1) {
429 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceClockPath,
430 strerror(errno), errno);
431 return false;
432 }
433
434 char buf[4097];
435 ssize_t n = read(fd, buf, 4096);
436 close(fd);
437 if (n == -1) {
438 fprintf(stderr, "error reading %s: %s (%d)\n", k_traceClockPath,
439 strerror(errno), errno);
440 return false;
441 }
442 buf[n] = '\0';
443
444 char *start = strchr(buf, '[');
445 if (start == NULL) {
446 return false;
447 }
448 start++;
449
450 char *end = strchr(start, ']');
451 if (end == NULL) {
452 return false;
453 }
454 *end = '\0';
455
456 return strcmp(mode, start) == 0;
457}
458
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800459// Enable or disable the kernel's use of the global clock. Disabling the global
460// clock will result in the kernel using a per-CPU local clock.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700461// Any write to the trace_clock sysfs file will reset the buffer, so only
462// update it if the requested value is not the current value.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800463static bool setGlobalClockEnable(bool enable)
464{
Colin Crossb1ce49b2014-08-20 14:28:47 -0700465 const char *clock = enable ? "global" : "local";
466
467 if (isTraceClock(clock)) {
468 return true;
469 }
470
471 return writeStr(k_traceClockPath, clock);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800472}
473
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700474static bool setPrintTgidEnableIfPresent(bool enable)
475{
476 if (fileExists(k_printTgidPath)) {
477 return setKernelOptionEnable(k_printTgidPath, enable);
478 }
479 return true;
480}
481
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800482// Poke all the binder-enabled processes in the system to get them to re-read
483// their system properties.
484static bool pokeBinderServices()
485{
486 sp<IServiceManager> sm = defaultServiceManager();
487 Vector<String16> services = sm->listServices();
488 for (size_t i = 0; i < services.size(); i++) {
489 sp<IBinder> obj = sm->checkService(services[i]);
490 if (obj != NULL) {
491 Parcel data;
492 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
493 NULL, 0) != OK) {
494 if (false) {
495 // XXX: For some reason this fails on tablets trying to
496 // poke the "phone" service. It's not clear whether some
497 // are expected to fail.
498 String8 svc(services[i]);
499 fprintf(stderr, "error poking binder service %s\n",
500 svc.string());
501 return false;
502 }
503 }
504 }
505 }
506 return true;
507}
508
509// Set the trace tags that userland tracing uses, and poke the running
510// processes to pick up the new value.
511static bool setTagsProperty(uint64_t tags)
512{
sergeyv4144eff2016-04-28 11:40:04 -0700513 char buf[PROPERTY_VALUE_MAX];
514 snprintf(buf, sizeof(buf), "%#" PRIx64, tags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800515 if (property_set(k_traceTagsProperty, buf) < 0) {
516 fprintf(stderr, "error setting trace tags system property\n");
517 return false;
518 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700519 return true;
520}
521
sergeyv4144eff2016-04-28 11:40:04 -0700522static void clearAppProperties()
523{
524 char buf[PROPERTY_KEY_MAX];
525 for (int i = 0; i < MAX_PACKAGES; i++) {
526 snprintf(buf, sizeof(buf), k_traceAppsPropertyTemplate, i);
527 if (property_set(buf, "") < 0) {
528 fprintf(stderr, "failed to clear system property: %s\n", buf);
529 }
530 }
531 if (property_set(k_traceAppsNumberProperty, "") < 0) {
532 fprintf(stderr, "failed to clear system property: %s",
533 k_traceAppsNumberProperty);
534 }
535}
536
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700537// Set the system property that indicates which apps should perform
538// application-level tracing.
Dan Austin497951c2016-05-31 13:27:03 -0700539static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700540{
sergeyv4144eff2016-04-28 11:40:04 -0700541 char buf[PROPERTY_KEY_MAX];
542 int i = 0;
Dan Austin497951c2016-05-31 13:27:03 -0700543 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700544 while (start != NULL) {
545 if (i == MAX_PACKAGES) {
546 fprintf(stderr, "error: only 16 packages could be traced at once\n");
547 clearAppProperties();
548 return false;
549 }
550 char* end = strchr(start, ',');
551 if (end != NULL) {
552 *end = '\0';
553 end++;
554 }
555 snprintf(buf, sizeof(buf), k_traceAppsPropertyTemplate, i);
556 if (property_set(buf, start) < 0) {
557 fprintf(stderr, "error setting trace app %d property to %s\n", i, buf);
558 clearAppProperties();
559 return false;
560 }
561 start = end;
562 i++;
563 }
564
565 snprintf(buf, sizeof(buf), "%d", i);
566 if (property_set(k_traceAppsNumberProperty, buf) < 0) {
567 fprintf(stderr, "error setting trace app number property to %s\n", buf);
568 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700569 return false;
570 }
571 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800572}
573
574// Disable all /sys/ enable files.
575static bool disableKernelTraceEvents() {
576 bool ok = true;
577 for (int i = 0; i < NELEM(k_categories); i++) {
578 const TracingCategory &c = k_categories[i];
579 for (int j = 0; j < MAX_SYS_FILES; j++) {
580 const char* path = c.sysfiles[j].path;
581 if (path != NULL && fileIsWritable(path)) {
582 ok &= setKernelOptionEnable(path, false);
583 }
584 }
585 }
586 return ok;
587}
588
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700589// Verify that the comma separated list of functions are being traced by the
590// kernel.
591static bool verifyKernelTraceFuncs(const char* funcs)
592{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100593 std::string buf;
594 if (!android::base::ReadFileToString(k_ftraceFilterPath, &buf)) {
595 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700596 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100597 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700598 }
599
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100600 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700601
602 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100603 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700604 bool ok = true;
605 char* myFuncs = strdup(funcs);
606 char* func = strtok(myFuncs, ",");
607 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100608 if (!strchr(func, '*')) {
609 String8 fancyFunc = String8::format("\n%s\n", func);
610 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
611 if (!found || func[0] == '\0') {
612 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
613 "to trace.\n", func);
614 ok = false;
615 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700616 }
617 func = strtok(NULL, ",");
618 }
619 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700620 return ok;
621}
622
623// Set the comma separated list of functions that the kernel is to trace.
624static bool setKernelTraceFuncs(const char* funcs)
625{
626 bool ok = true;
627
628 if (funcs == NULL || funcs[0] == '\0') {
629 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700630 if (fileIsWritable(k_currentTracerPath)) {
631 ok &= writeStr(k_currentTracerPath, "nop");
632 }
633 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700634 ok &= truncateFile(k_ftraceFilterPath);
635 }
636 } else {
637 // Enable kernel function tracing.
638 ok &= writeStr(k_currentTracerPath, "function_graph");
639 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
640 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
641 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
642 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
643
644 // Set the requested filter functions.
645 ok &= truncateFile(k_ftraceFilterPath);
646 char* myFuncs = strdup(funcs);
647 char* func = strtok(myFuncs, ",");
648 while (func) {
649 ok &= appendStr(k_ftraceFilterPath, func);
650 func = strtok(NULL, ",");
651 }
652 free(myFuncs);
653
654 // Verify that the set functions are being traced.
655 if (ok) {
656 ok &= verifyKernelTraceFuncs(funcs);
657 }
658 }
659
660 return ok;
661}
662
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900663static bool setCategoryEnable(const char* name, bool enable)
664{
665 for (int i = 0; i < NELEM(k_categories); i++) {
666 const TracingCategory& c = k_categories[i];
667 if (strcmp(name, c.name) == 0) {
668 if (isCategorySupported(c)) {
669 g_categoryEnables[i] = enable;
670 return true;
671 } else {
672 if (isCategorySupportedForRoot(c)) {
673 fprintf(stderr, "error: category \"%s\" requires root "
674 "privileges.\n", name);
675 } else {
676 fprintf(stderr, "error: category \"%s\" is not supported "
677 "on this device.\n", name);
678 }
679 return false;
680 }
681 }
682 }
683 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
684 return false;
685}
686
687static bool setCategoriesEnableFromFile(const char* categories_file)
688{
689 if (!categories_file) {
690 return true;
691 }
692 Tokenizer* tokenizer = NULL;
693 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
694 return false;
695 }
696 bool ok = true;
697 while (!tokenizer->isEol()) {
698 String8 token = tokenizer->nextToken(" ");
699 if (token.isEmpty()) {
700 tokenizer->skipDelimiters(" ");
701 continue;
702 }
703 ok &= setCategoryEnable(token.string(), true);
704 }
705 delete tokenizer;
706 return ok;
707}
708
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700709// Set all the kernel tracing settings to the desired state for this trace
710// capture.
711static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800712{
713 bool ok = true;
714
715 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900716 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800717 ok &= setTraceOverwriteEnable(g_traceOverwrite);
718 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
719 ok &= setGlobalClockEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700720 ok &= setPrintTgidEnableIfPresent(true);
721 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800722
723 // Set up the tags property.
724 uint64_t tags = 0;
725 for (int i = 0; i < NELEM(k_categories); i++) {
726 if (g_categoryEnables[i]) {
727 const TracingCategory &c = k_categories[i];
728 tags |= c.tags;
729 }
730 }
731 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700732
733 bool coreServicesTagEnabled = false;
734 for (int i = 0; i < NELEM(k_categories); i++) {
735 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
736 coreServicesTagEnabled = g_categoryEnables[i];
737 }
738 }
739
740 std::string packageList(g_debugAppCmdLine);
741 if (coreServicesTagEnabled) {
742 char value[PROPERTY_VALUE_MAX];
743 property_get(k_coreServicesProp, value, "");
744 if (!packageList.empty()) {
745 packageList += ",";
746 }
747 packageList += value;
748 }
Dan Austin497951c2016-05-31 13:27:03 -0700749 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700750 ok &= pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800751
752 // Disable all the sysfs enables. This is done as a separate loop from
753 // the enables to allow the same enable to exist in multiple categories.
754 ok &= disableKernelTraceEvents();
755
756 // Enable all the sysfs enables that are in an enabled category.
757 for (int i = 0; i < NELEM(k_categories); i++) {
758 if (g_categoryEnables[i]) {
759 const TracingCategory &c = k_categories[i];
760 for (int j = 0; j < MAX_SYS_FILES; j++) {
761 const char* path = c.sysfiles[j].path;
762 bool required = c.sysfiles[j].required == REQ;
763 if (path != NULL) {
764 if (fileIsWritable(path)) {
765 ok &= setKernelOptionEnable(path, true);
766 } else if (required) {
767 fprintf(stderr, "error writing file %s\n", path);
768 ok = false;
769 }
770 }
771 }
772 }
773 }
774
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800775 return ok;
776}
777
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700778// Reset all the kernel tracing settings to their default state.
779static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800780{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800781 // Disable all tracing that we're able to.
782 disableKernelTraceEvents();
783
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700784 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800785 setTagsProperty(0);
sergeyv4144eff2016-04-28 11:40:04 -0700786 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700787 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800788
789 // Set the options back to their defaults.
790 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700791 setTraceBufferSizeKB(1);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800792 setGlobalClockEnable(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700793 setPrintTgidEnableIfPresent(false);
794 setKernelTraceFuncs(NULL);
795}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800796
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700797
798// Enable tracing in the kernel.
799static bool startTrace()
800{
801 return setTracingEnabled(true);
802}
803
804// Disable tracing in the kernel.
805static void stopTrace()
806{
807 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800808}
809
Martijn Coenend9535872015-11-26 10:00:55 +0100810// Read data from the tracing pipe and forward to stdout
811static void streamTrace()
812{
813 char trace_data[4096];
814 int traceFD = open(k_traceStreamPath, O_RDWR);
815 if (traceFD == -1) {
816 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
817 strerror(errno), errno);
818 return;
819 }
820 while (!g_traceAborted) {
821 ssize_t bytes_read = read(traceFD, trace_data, 4096);
822 if (bytes_read > 0) {
823 write(STDOUT_FILENO, trace_data, bytes_read);
824 fflush(stdout);
825 } else {
826 if (!g_traceAborted) {
827 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
828 bytes_read, errno, strerror(errno));
829 }
830 break;
831 }
832 }
833}
834
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800835// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700836static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800837{
John Reck6c8ac922016-03-28 11:25:30 -0700838 ALOGI("Dumping trace");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800839 int traceFD = open(k_tracePath, O_RDWR);
840 if (traceFD == -1) {
841 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
842 strerror(errno), errno);
843 return;
844 }
845
846 if (g_compress) {
847 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800848 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700849
850 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800851 if (result != Z_OK) {
852 fprintf(stderr, "error initializing zlib: %d\n", result);
853 close(traceFD);
854 return;
855 }
856
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700857 constexpr size_t bufSize = 64*1024;
858 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
859 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
860 if (!in || !out) {
861 fprintf(stderr, "couldn't allocate buffers\n");
862 close(traceFD);
863 return;
864 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800865
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700866 int flush = Z_NO_FLUSH;
867
868 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800869 zs.avail_out = bufSize;
870
871 do {
872
873 if (zs.avail_in == 0) {
874 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700875 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800876 if (result < 0) {
877 fprintf(stderr, "error reading trace: %s (%d)\n",
878 strerror(errno), errno);
879 result = Z_STREAM_END;
880 break;
881 } else if (result == 0) {
882 flush = Z_FINISH;
883 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700884 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800885 zs.avail_in = result;
886 }
887 }
888
889 if (zs.avail_out == 0) {
890 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700891 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800892 if ((size_t)result < bufSize) {
893 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
894 strerror(errno), errno);
895 result = Z_STREAM_END; // skip deflate error message
896 zs.avail_out = bufSize; // skip the final write
897 break;
898 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700899 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800900 zs.avail_out = bufSize;
901 }
902
903 } while ((result = deflate(&zs, flush)) == Z_OK);
904
905 if (result != Z_STREAM_END) {
906 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
907 }
908
909 if (zs.avail_out < bufSize) {
910 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -0700911 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800912 if ((size_t)result < bytes) {
913 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
914 strerror(errno), errno);
915 }
916 }
917
918 result = deflateEnd(&zs);
919 if (result != Z_OK) {
920 fprintf(stderr, "error cleaning up zlib: %d\n", result);
921 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800922 } else {
923 ssize_t sent = 0;
John Reck40b26b42016-03-30 09:44:36 -0700924 while ((sent = sendfile(outFd, traceFD, NULL, 64*1024*1024)) > 0);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800925 if (sent == -1) {
926 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
927 errno);
928 }
929 }
930
931 close(traceFD);
932}
933
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700934static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800935{
936 if (!g_nohup) {
937 g_traceAborted = true;
938 }
939}
940
941static void registerSigHandler()
942{
943 struct sigaction sa;
944 sigemptyset(&sa.sa_mask);
945 sa.sa_flags = 0;
946 sa.sa_handler = handleSignal;
947 sigaction(SIGHUP, &sa, NULL);
948 sigaction(SIGINT, &sa, NULL);
949 sigaction(SIGQUIT, &sa, NULL);
950 sigaction(SIGTERM, &sa, NULL);
951}
952
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800953static void listSupportedCategories()
954{
955 for (int i = 0; i < NELEM(k_categories); i++) {
956 const TracingCategory& c = k_categories[i];
957 if (isCategorySupported(c)) {
958 printf(" %10s - %s\n", c.name, c.longname);
959 }
960 }
961}
962
963// Print the command usage help to stderr.
964static void showHelp(const char *cmd)
965{
966 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
967 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700968 " -a appname enable app-level tracing for a comma "
969 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800970 " -b N use a trace buffer size of N KB\n"
971 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900972 " -f filename use the categories written in a file as space-separated\n"
973 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700974 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800975 " -n ignore signals\n"
976 " -s N sleep for N seconds before tracing [default 0]\n"
Elliott Hughesf884a062016-07-22 09:38:44 -0700977 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800978 " -z compress the trace dump\n"
979 " --async_start start circular trace and return immediatly\n"
980 " --async_dump dump the current contents of circular trace buffer\n"
981 " --async_stop stop tracing and dump the current contents of circular\n"
982 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +0100983 " --stream stream trace to stdout as it enters the trace buffer\n"
984 " Note: this can take significant CPU time, and is best\n"
985 " used for measuring things that are not affected by\n"
986 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -0800987 " --list_categories\n"
988 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -0700989 " -o filename write the trace to the specified file instead\n"
990 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800991 );
992}
993
994int main(int argc, char **argv)
995{
996 bool async = false;
997 bool traceStart = true;
998 bool traceStop = true;
999 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001000 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001001
1002 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1003 showHelp(argv[0]);
1004 exit(0);
1005 }
1006
1007 for (;;) {
1008 int ret;
1009 int option_index = 0;
1010 static struct option long_options[] = {
1011 {"async_start", no_argument, 0, 0 },
1012 {"async_stop", no_argument, 0, 0 },
1013 {"async_dump", no_argument, 0, 0 },
1014 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +01001015 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001016 { 0, 0, 0, 0 }
1017 };
1018
John Reck40b26b42016-03-30 09:44:36 -07001019 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001020 long_options, &option_index);
1021
1022 if (ret < 0) {
1023 for (int i = optind; i < argc; i++) {
1024 if (!setCategoryEnable(argv[i], true)) {
1025 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1026 exit(1);
1027 }
1028 }
1029 break;
1030 }
1031
1032 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001033 case 'a':
1034 g_debugAppCmdLine = optarg;
1035 break;
1036
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001037 case 'b':
1038 g_traceBufferSizeKB = atoi(optarg);
1039 break;
1040
1041 case 'c':
1042 g_traceOverwrite = true;
1043 break;
1044
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001045 case 'f':
1046 g_categoriesFile = optarg;
1047 break;
1048
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001049 case 'k':
1050 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001051 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001052
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001053 case 'n':
1054 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001055 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001056
1057 case 's':
1058 g_initialSleepSecs = atoi(optarg);
1059 break;
1060
1061 case 't':
1062 g_traceDurationSeconds = atoi(optarg);
1063 break;
1064
1065 case 'z':
1066 g_compress = true;
1067 break;
1068
John Reck40b26b42016-03-30 09:44:36 -07001069 case 'o':
1070 g_outputFile = optarg;
1071 break;
1072
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001073 case 0:
1074 if (!strcmp(long_options[option_index].name, "async_start")) {
1075 async = true;
1076 traceStop = false;
1077 traceDump = false;
1078 g_traceOverwrite = true;
1079 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1080 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001081 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001082 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1083 async = true;
1084 traceStart = false;
1085 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001086 } else if (!strcmp(long_options[option_index].name, "stream")) {
1087 traceStream = true;
1088 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001089 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1090 listSupportedCategories();
1091 exit(0);
1092 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001093 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001094
1095 default:
1096 fprintf(stderr, "\n");
1097 showHelp(argv[0]);
1098 exit(-1);
1099 break;
1100 }
1101 }
1102
1103 registerSigHandler();
1104
1105 if (g_initialSleepSecs > 0) {
1106 sleep(g_initialSleepSecs);
1107 }
1108
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001109 bool ok = true;
1110 ok &= setUpTrace();
1111 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001112
1113 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001114 if (!traceStream) {
1115 printf("capturing trace...");
1116 fflush(stdout);
1117 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001118
1119 // We clear the trace after starting it because tracing gets enabled for
1120 // each CPU individually in the kernel. Having the beginning of the trace
1121 // contain entries from only one CPU can cause "begin" entries without a
1122 // matching "end" entry to show up if a task gets migrated from one CPU to
1123 // another.
1124 ok = clearTrace();
1125
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001126 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001127 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001128 // Sleep to allow the trace to be captured.
1129 struct timespec timeLeft;
1130 timeLeft.tv_sec = g_traceDurationSeconds;
1131 timeLeft.tv_nsec = 0;
1132 do {
1133 if (g_traceAborted) {
1134 break;
1135 }
1136 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1137 }
Martijn Coenend9535872015-11-26 10:00:55 +01001138
1139 if (traceStream) {
1140 streamTrace();
1141 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001142 }
1143
1144 // Stop the trace and restore the default settings.
1145 if (traceStop)
1146 stopTrace();
1147
1148 if (ok && traceDump) {
1149 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001150 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001151 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001152 int outFd = STDOUT_FILENO;
1153 if (g_outputFile) {
1154 outFd = open(g_outputFile, O_WRONLY | O_CREAT);
1155 }
1156 if (outFd == -1) {
1157 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1158 } else {
1159 dprintf(outFd, "TRACE:\n");
1160 dumpTrace(outFd);
1161 if (g_outputFile) {
1162 close(outFd);
1163 }
1164 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001165 } else {
1166 printf("\ntrace aborted.\n");
1167 fflush(stdout);
1168 }
1169 clearTrace();
1170 } else if (!ok) {
1171 fprintf(stderr, "unable to start tracing\n");
1172 }
1173
1174 // Reset the trace buffer size to 1.
1175 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001176 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001177
1178 return g_traceAborted ? 1 : 0;
1179}