blob: 25c2a300be935b1136888c082229224e5dbc2adb [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;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100516 using ::android::hardware::hidl_string;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100517
518 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800519 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100520 for (size_t i = 0; i < interfaces.size(); i++) {
521 string fqInstanceName = interfaces[i];
522 string::size_type n = fqInstanceName.find("/");
523 if (n == std::string::npos || interfaces[i].size() == n+1)
524 continue;
525 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
526 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800527 auto getRet = sm->get(fqInterfaceName, instanceName, [&](const auto &interface) {
Yifan Hong61954a42016-12-05 12:58:05 -0800528 auto notifyRet = interface->notifySyspropsChanged();
529 if (!notifyRet.isOk()) {
530 fprintf(stderr, "failed to notifySyspropsChanged on service %s: %s\n",
531 fqInstanceName.c_str(),
532 notifyRet.getStatus().toString8().string());
533 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100534 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800535 if (!getRet.isOk()) {
536 fprintf(stderr, "failed to get service %s: %s\n",
537 fqInstanceName.c_str(),
538 getRet.getStatus().toString8().string());
539 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100540 }
541 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800542 if (!listRet.isOk()) {
543 fprintf(stderr, "failed to list services: %s\n", listRet.getStatus().toString8().string());
544 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100545}
546
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800547// Set the trace tags that userland tracing uses, and poke the running
548// processes to pick up the new value.
549static bool setTagsProperty(uint64_t tags)
550{
sergeyv4144eff2016-04-28 11:40:04 -0700551 char buf[PROPERTY_VALUE_MAX];
552 snprintf(buf, sizeof(buf), "%#" PRIx64, tags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800553 if (property_set(k_traceTagsProperty, buf) < 0) {
554 fprintf(stderr, "error setting trace tags system property\n");
555 return false;
556 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700557 return true;
558}
559
sergeyv4144eff2016-04-28 11:40:04 -0700560static void clearAppProperties()
561{
562 char buf[PROPERTY_KEY_MAX];
563 for (int i = 0; i < MAX_PACKAGES; i++) {
564 snprintf(buf, sizeof(buf), k_traceAppsPropertyTemplate, i);
565 if (property_set(buf, "") < 0) {
566 fprintf(stderr, "failed to clear system property: %s\n", buf);
567 }
568 }
569 if (property_set(k_traceAppsNumberProperty, "") < 0) {
570 fprintf(stderr, "failed to clear system property: %s",
571 k_traceAppsNumberProperty);
572 }
573}
574
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700575// Set the system property that indicates which apps should perform
576// application-level tracing.
Dan Austin497951c2016-05-31 13:27:03 -0700577static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700578{
sergeyv4144eff2016-04-28 11:40:04 -0700579 char buf[PROPERTY_KEY_MAX];
580 int i = 0;
Dan Austin497951c2016-05-31 13:27:03 -0700581 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700582 while (start != NULL) {
583 if (i == MAX_PACKAGES) {
584 fprintf(stderr, "error: only 16 packages could be traced at once\n");
585 clearAppProperties();
586 return false;
587 }
588 char* end = strchr(start, ',');
589 if (end != NULL) {
590 *end = '\0';
591 end++;
592 }
593 snprintf(buf, sizeof(buf), k_traceAppsPropertyTemplate, i);
594 if (property_set(buf, start) < 0) {
595 fprintf(stderr, "error setting trace app %d property to %s\n", i, buf);
596 clearAppProperties();
597 return false;
598 }
599 start = end;
600 i++;
601 }
602
603 snprintf(buf, sizeof(buf), "%d", i);
604 if (property_set(k_traceAppsNumberProperty, buf) < 0) {
605 fprintf(stderr, "error setting trace app number property to %s\n", buf);
606 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700607 return false;
608 }
609 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800610}
611
612// Disable all /sys/ enable files.
613static bool disableKernelTraceEvents() {
614 bool ok = true;
615 for (int i = 0; i < NELEM(k_categories); i++) {
616 const TracingCategory &c = k_categories[i];
617 for (int j = 0; j < MAX_SYS_FILES; j++) {
618 const char* path = c.sysfiles[j].path;
619 if (path != NULL && fileIsWritable(path)) {
620 ok &= setKernelOptionEnable(path, false);
621 }
622 }
623 }
624 return ok;
625}
626
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700627// Verify that the comma separated list of functions are being traced by the
628// kernel.
629static bool verifyKernelTraceFuncs(const char* funcs)
630{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100631 std::string buf;
632 if (!android::base::ReadFileToString(k_ftraceFilterPath, &buf)) {
633 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700634 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100635 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700636 }
637
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100638 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700639
640 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100641 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700642 bool ok = true;
643 char* myFuncs = strdup(funcs);
644 char* func = strtok(myFuncs, ",");
645 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100646 if (!strchr(func, '*')) {
647 String8 fancyFunc = String8::format("\n%s\n", func);
648 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
649 if (!found || func[0] == '\0') {
650 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
651 "to trace.\n", func);
652 ok = false;
653 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700654 }
655 func = strtok(NULL, ",");
656 }
657 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700658 return ok;
659}
660
661// Set the comma separated list of functions that the kernel is to trace.
662static bool setKernelTraceFuncs(const char* funcs)
663{
664 bool ok = true;
665
666 if (funcs == NULL || funcs[0] == '\0') {
667 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700668 if (fileIsWritable(k_currentTracerPath)) {
669 ok &= writeStr(k_currentTracerPath, "nop");
670 }
671 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700672 ok &= truncateFile(k_ftraceFilterPath);
673 }
674 } else {
675 // Enable kernel function tracing.
676 ok &= writeStr(k_currentTracerPath, "function_graph");
677 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
678 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
679 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
680 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
681
682 // Set the requested filter functions.
683 ok &= truncateFile(k_ftraceFilterPath);
684 char* myFuncs = strdup(funcs);
685 char* func = strtok(myFuncs, ",");
686 while (func) {
687 ok &= appendStr(k_ftraceFilterPath, func);
688 func = strtok(NULL, ",");
689 }
690 free(myFuncs);
691
692 // Verify that the set functions are being traced.
693 if (ok) {
694 ok &= verifyKernelTraceFuncs(funcs);
695 }
696 }
697
698 return ok;
699}
700
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900701static bool setCategoryEnable(const char* name, bool enable)
702{
703 for (int i = 0; i < NELEM(k_categories); i++) {
704 const TracingCategory& c = k_categories[i];
705 if (strcmp(name, c.name) == 0) {
706 if (isCategorySupported(c)) {
707 g_categoryEnables[i] = enable;
708 return true;
709 } else {
710 if (isCategorySupportedForRoot(c)) {
711 fprintf(stderr, "error: category \"%s\" requires root "
712 "privileges.\n", name);
713 } else {
714 fprintf(stderr, "error: category \"%s\" is not supported "
715 "on this device.\n", name);
716 }
717 return false;
718 }
719 }
720 }
721 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
722 return false;
723}
724
725static bool setCategoriesEnableFromFile(const char* categories_file)
726{
727 if (!categories_file) {
728 return true;
729 }
730 Tokenizer* tokenizer = NULL;
731 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
732 return false;
733 }
734 bool ok = true;
735 while (!tokenizer->isEol()) {
736 String8 token = tokenizer->nextToken(" ");
737 if (token.isEmpty()) {
738 tokenizer->skipDelimiters(" ");
739 continue;
740 }
741 ok &= setCategoryEnable(token.string(), true);
742 }
743 delete tokenizer;
744 return ok;
745}
746
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700747// Set all the kernel tracing settings to the desired state for this trace
748// capture.
749static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800750{
751 bool ok = true;
752
753 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900754 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800755 ok &= setTraceOverwriteEnable(g_traceOverwrite);
756 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
757 ok &= setGlobalClockEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700758 ok &= setPrintTgidEnableIfPresent(true);
759 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800760
761 // Set up the tags property.
762 uint64_t tags = 0;
763 for (int i = 0; i < NELEM(k_categories); i++) {
764 if (g_categoryEnables[i]) {
765 const TracingCategory &c = k_categories[i];
766 tags |= c.tags;
767 }
768 }
769 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700770
771 bool coreServicesTagEnabled = false;
772 for (int i = 0; i < NELEM(k_categories); i++) {
773 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
774 coreServicesTagEnabled = g_categoryEnables[i];
775 }
776 }
777
778 std::string packageList(g_debugAppCmdLine);
779 if (coreServicesTagEnabled) {
780 char value[PROPERTY_VALUE_MAX];
781 property_get(k_coreServicesProp, value, "");
782 if (!packageList.empty()) {
783 packageList += ",";
784 }
785 packageList += value;
786 }
Dan Austin497951c2016-05-31 13:27:03 -0700787 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700788 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100789 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800790
791 // Disable all the sysfs enables. This is done as a separate loop from
792 // the enables to allow the same enable to exist in multiple categories.
793 ok &= disableKernelTraceEvents();
794
795 // Enable all the sysfs enables that are in an enabled category.
796 for (int i = 0; i < NELEM(k_categories); i++) {
797 if (g_categoryEnables[i]) {
798 const TracingCategory &c = k_categories[i];
799 for (int j = 0; j < MAX_SYS_FILES; j++) {
800 const char* path = c.sysfiles[j].path;
801 bool required = c.sysfiles[j].required == REQ;
802 if (path != NULL) {
803 if (fileIsWritable(path)) {
804 ok &= setKernelOptionEnable(path, true);
805 } else if (required) {
806 fprintf(stderr, "error writing file %s\n", path);
807 ok = false;
808 }
809 }
810 }
811 }
812 }
813
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800814 return ok;
815}
816
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700817// Reset all the kernel tracing settings to their default state.
818static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800819{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800820 // Disable all tracing that we're able to.
821 disableKernelTraceEvents();
822
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700823 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800824 setTagsProperty(0);
sergeyv4144eff2016-04-28 11:40:04 -0700825 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700826 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800827
828 // Set the options back to their defaults.
829 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700830 setTraceBufferSizeKB(1);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800831 setGlobalClockEnable(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700832 setPrintTgidEnableIfPresent(false);
833 setKernelTraceFuncs(NULL);
834}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800835
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700836
837// Enable tracing in the kernel.
838static bool startTrace()
839{
840 return setTracingEnabled(true);
841}
842
843// Disable tracing in the kernel.
844static void stopTrace()
845{
846 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800847}
848
Martijn Coenend9535872015-11-26 10:00:55 +0100849// Read data from the tracing pipe and forward to stdout
850static void streamTrace()
851{
852 char trace_data[4096];
853 int traceFD = open(k_traceStreamPath, O_RDWR);
854 if (traceFD == -1) {
855 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
856 strerror(errno), errno);
857 return;
858 }
859 while (!g_traceAborted) {
860 ssize_t bytes_read = read(traceFD, trace_data, 4096);
861 if (bytes_read > 0) {
862 write(STDOUT_FILENO, trace_data, bytes_read);
863 fflush(stdout);
864 } else {
865 if (!g_traceAborted) {
866 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
867 bytes_read, errno, strerror(errno));
868 }
869 break;
870 }
871 }
872}
873
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800874// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700875static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800876{
John Reck6c8ac922016-03-28 11:25:30 -0700877 ALOGI("Dumping trace");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800878 int traceFD = open(k_tracePath, O_RDWR);
879 if (traceFD == -1) {
880 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
881 strerror(errno), errno);
882 return;
883 }
884
885 if (g_compress) {
886 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800887 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700888
889 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800890 if (result != Z_OK) {
891 fprintf(stderr, "error initializing zlib: %d\n", result);
892 close(traceFD);
893 return;
894 }
895
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700896 constexpr size_t bufSize = 64*1024;
897 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
898 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
899 if (!in || !out) {
900 fprintf(stderr, "couldn't allocate buffers\n");
901 close(traceFD);
902 return;
903 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800904
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700905 int flush = Z_NO_FLUSH;
906
907 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800908 zs.avail_out = bufSize;
909
910 do {
911
912 if (zs.avail_in == 0) {
913 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700914 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800915 if (result < 0) {
916 fprintf(stderr, "error reading trace: %s (%d)\n",
917 strerror(errno), errno);
918 result = Z_STREAM_END;
919 break;
920 } else if (result == 0) {
921 flush = Z_FINISH;
922 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700923 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800924 zs.avail_in = result;
925 }
926 }
927
928 if (zs.avail_out == 0) {
929 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700930 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800931 if ((size_t)result < bufSize) {
932 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
933 strerror(errno), errno);
934 result = Z_STREAM_END; // skip deflate error message
935 zs.avail_out = bufSize; // skip the final write
936 break;
937 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700938 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800939 zs.avail_out = bufSize;
940 }
941
942 } while ((result = deflate(&zs, flush)) == Z_OK);
943
944 if (result != Z_STREAM_END) {
945 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
946 }
947
948 if (zs.avail_out < bufSize) {
949 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -0700950 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800951 if ((size_t)result < bytes) {
952 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
953 strerror(errno), errno);
954 }
955 }
956
957 result = deflateEnd(&zs);
958 if (result != Z_OK) {
959 fprintf(stderr, "error cleaning up zlib: %d\n", result);
960 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800961 } else {
962 ssize_t sent = 0;
John Reck40b26b42016-03-30 09:44:36 -0700963 while ((sent = sendfile(outFd, traceFD, NULL, 64*1024*1024)) > 0);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800964 if (sent == -1) {
965 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
966 errno);
967 }
968 }
969
970 close(traceFD);
971}
972
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700973static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800974{
975 if (!g_nohup) {
976 g_traceAborted = true;
977 }
978}
979
980static void registerSigHandler()
981{
982 struct sigaction sa;
983 sigemptyset(&sa.sa_mask);
984 sa.sa_flags = 0;
985 sa.sa_handler = handleSignal;
986 sigaction(SIGHUP, &sa, NULL);
987 sigaction(SIGINT, &sa, NULL);
988 sigaction(SIGQUIT, &sa, NULL);
989 sigaction(SIGTERM, &sa, NULL);
990}
991
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800992static void listSupportedCategories()
993{
994 for (int i = 0; i < NELEM(k_categories); i++) {
995 const TracingCategory& c = k_categories[i];
996 if (isCategorySupported(c)) {
997 printf(" %10s - %s\n", c.name, c.longname);
998 }
999 }
1000}
1001
1002// Print the command usage help to stderr.
1003static void showHelp(const char *cmd)
1004{
1005 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1006 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001007 " -a appname enable app-level tracing for a comma "
1008 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001009 " -b N use a trace buffer size of N KB\n"
1010 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001011 " -f filename use the categories written in a file as space-separated\n"
1012 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001013 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001014 " -n ignore signals\n"
1015 " -s N sleep for N seconds before tracing [default 0]\n"
Elliott Hughesf884a062016-07-22 09:38:44 -07001016 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001017 " -z compress the trace dump\n"
1018 " --async_start start circular trace and return immediatly\n"
1019 " --async_dump dump the current contents of circular trace buffer\n"
1020 " --async_stop stop tracing and dump the current contents of circular\n"
1021 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001022 " --stream stream trace to stdout as it enters the trace buffer\n"
1023 " Note: this can take significant CPU time, and is best\n"
1024 " used for measuring things that are not affected by\n"
1025 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001026 " --list_categories\n"
1027 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001028 " -o filename write the trace to the specified file instead\n"
1029 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001030 );
1031}
1032
1033int main(int argc, char **argv)
1034{
1035 bool async = false;
1036 bool traceStart = true;
1037 bool traceStop = true;
1038 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001039 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001040
1041 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1042 showHelp(argv[0]);
1043 exit(0);
1044 }
1045
1046 for (;;) {
1047 int ret;
1048 int option_index = 0;
1049 static struct option long_options[] = {
1050 {"async_start", no_argument, 0, 0 },
1051 {"async_stop", no_argument, 0, 0 },
1052 {"async_dump", no_argument, 0, 0 },
1053 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +01001054 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001055 { 0, 0, 0, 0 }
1056 };
1057
John Reck40b26b42016-03-30 09:44:36 -07001058 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001059 long_options, &option_index);
1060
1061 if (ret < 0) {
1062 for (int i = optind; i < argc; i++) {
1063 if (!setCategoryEnable(argv[i], true)) {
1064 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1065 exit(1);
1066 }
1067 }
1068 break;
1069 }
1070
1071 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001072 case 'a':
1073 g_debugAppCmdLine = optarg;
1074 break;
1075
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001076 case 'b':
1077 g_traceBufferSizeKB = atoi(optarg);
1078 break;
1079
1080 case 'c':
1081 g_traceOverwrite = true;
1082 break;
1083
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001084 case 'f':
1085 g_categoriesFile = optarg;
1086 break;
1087
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001088 case 'k':
1089 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001090 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001091
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001092 case 'n':
1093 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001094 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001095
1096 case 's':
1097 g_initialSleepSecs = atoi(optarg);
1098 break;
1099
1100 case 't':
1101 g_traceDurationSeconds = atoi(optarg);
1102 break;
1103
1104 case 'z':
1105 g_compress = true;
1106 break;
1107
John Reck40b26b42016-03-30 09:44:36 -07001108 case 'o':
1109 g_outputFile = optarg;
1110 break;
1111
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001112 case 0:
1113 if (!strcmp(long_options[option_index].name, "async_start")) {
1114 async = true;
1115 traceStop = false;
1116 traceDump = false;
1117 g_traceOverwrite = true;
1118 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1119 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001120 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001121 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1122 async = true;
1123 traceStart = false;
1124 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001125 } else if (!strcmp(long_options[option_index].name, "stream")) {
1126 traceStream = true;
1127 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001128 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1129 listSupportedCategories();
1130 exit(0);
1131 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001132 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001133
1134 default:
1135 fprintf(stderr, "\n");
1136 showHelp(argv[0]);
1137 exit(-1);
1138 break;
1139 }
1140 }
1141
1142 registerSigHandler();
1143
1144 if (g_initialSleepSecs > 0) {
1145 sleep(g_initialSleepSecs);
1146 }
1147
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001148 bool ok = true;
1149 ok &= setUpTrace();
1150 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001151
1152 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001153 if (!traceStream) {
1154 printf("capturing trace...");
1155 fflush(stdout);
1156 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001157
1158 // We clear the trace after starting it because tracing gets enabled for
1159 // each CPU individually in the kernel. Having the beginning of the trace
1160 // contain entries from only one CPU can cause "begin" entries without a
1161 // matching "end" entry to show up if a task gets migrated from one CPU to
1162 // another.
1163 ok = clearTrace();
1164
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001165 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001166 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001167 // Sleep to allow the trace to be captured.
1168 struct timespec timeLeft;
1169 timeLeft.tv_sec = g_traceDurationSeconds;
1170 timeLeft.tv_nsec = 0;
1171 do {
1172 if (g_traceAborted) {
1173 break;
1174 }
1175 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1176 }
Martijn Coenend9535872015-11-26 10:00:55 +01001177
1178 if (traceStream) {
1179 streamTrace();
1180 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001181 }
1182
1183 // Stop the trace and restore the default settings.
1184 if (traceStop)
1185 stopTrace();
1186
1187 if (ok && traceDump) {
1188 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001189 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001190 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001191 int outFd = STDOUT_FILENO;
1192 if (g_outputFile) {
1193 outFd = open(g_outputFile, O_WRONLY | O_CREAT);
1194 }
1195 if (outFd == -1) {
1196 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1197 } else {
1198 dprintf(outFd, "TRACE:\n");
1199 dumpTrace(outFd);
1200 if (g_outputFile) {
1201 close(outFd);
1202 }
1203 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001204 } else {
1205 printf("\ntrace aborted.\n");
1206 fflush(stdout);
1207 }
1208 clearTrace();
1209 } else if (!ok) {
1210 fprintf(stderr, "unable to start tracing\n");
1211 }
1212
1213 // Reset the trace buffer size to 1.
1214 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001215 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001216
1217 return g_traceAborted ? 1 : 0;
1218}