blob: 4954869865f966c07dc32439257eedd6f696ab79 [file] [log] [blame]
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
John Reck40b26b42016-03-30 09:44:36 -070017 #define LOG_TAG "atrace"
18
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080019#include <errno.h>
20#include <fcntl.h>
21#include <getopt.h>
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070022#include <inttypes.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080023#include <signal.h>
24#include <stdarg.h>
25#include <stdbool.h>
26#include <stdio.h>
27#include <stdlib.h>
Elliott Hughes3da5d232015-01-25 08:35:20 -080028#include <string.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080029#include <sys/sendfile.h>
30#include <time.h>
Martijn Coenend9535872015-11-26 10:00:55 +010031#include <unistd.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080032#include <zlib.h>
33
Elliott Hughesa252f4d2016-07-21 17:12:15 -070034#include <memory>
35
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080036#include <binder/IBinder.h>
37#include <binder/IServiceManager.h>
38#include <binder/Parcel.h>
39
Martijn Coenenee9b97e2016-11-16 16:00:26 +010040#include <android/hidl/manager/1.0/IServiceManager.h>
41#include <hidl/ServiceManagement.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080042#include <cutils/properties.h>
43
44#include <utils/String8.h>
John Reck469a1942015-03-26 15:31:35 -070045#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +090046#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080047#include <utils/Trace.h>
Stephane Gasparinid8419c22016-03-02 13:45:15 +010048#include <android-base/file.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080049
50using namespace android;
51
Martijn Coenenee9b97e2016-11-16 16:00:26 +010052using std::string;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080053#define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0])))
54
sergeyv4144eff2016-04-28 11:40:04 -070055#define MAX_SYS_FILES 10
56#define MAX_PACKAGES 16
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080057
58const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
sergeyv4144eff2016-04-28 11:40:04 -070059
60const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
61const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070062const char* k_coreServiceCategory = "core_services";
63const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080064
65typedef enum { OPT, REQ } requiredness ;
66
67struct TracingCategory {
68 // The name identifying the category.
69 const char* name;
70
71 // A longer description of the category.
72 const char* longname;
73
74 // The userland tracing tags that the category enables.
75 uint64_t tags;
76
77 // The fname==NULL terminated list of /sys/ files that the category
78 // enables.
79 struct {
80 // Whether the file must be writable in order to enable the tracing
81 // category.
82 requiredness required;
83
84 // The path to the enable file.
85 const char* path;
86 } sysfiles[MAX_SYS_FILES];
87};
88
89/* Tracing categories */
90static const TracingCategory k_categories[] = {
Jamie Gennisb2a89e32013-03-11 19:37:53 -070091 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, { } },
92 { "input", "Input", ATRACE_TAG_INPUT, { } },
93 { "view", "View System", ATRACE_TAG_VIEW, { } },
94 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
95 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
96 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -050097 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070098 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
99 { "video", "Video", ATRACE_TAG_VIDEO, { } },
100 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
101 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700102 { "app", "Application", ATRACE_TAG_APP, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -0700103 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -0700104 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -0700105 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -0700106 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700107 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 14:36:20 -0700108 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-07-01 01:46:25 +0900109 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Greg Hackmannbbd7d992014-12-01 14:43:34 -0800110 { "database", "Database", ATRACE_TAG_DATABASE, { } },
sergeyvdb404152016-05-02 19:26:07 -0700111 { k_coreServiceCategory, "Core services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700112 { "sched", "CPU Scheduling", 0, {
113 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_switch/enable" },
114 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_wakeup/enable" },
Riley Andrews5672bb72015-11-19 13:31:17 -0800115 { OPT, "/sys/kernel/debug/tracing/events/sched/sched_blocked_reason/enable" },
Ruchi Kandoicfe500d2015-11-23 13:47:20 -0800116 { OPT, "/sys/kernel/debug/tracing/events/sched/sched_cpu_hotplug/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800117 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700118 { "irq", "IRQ Events", 0, {
119 { REQ, "/sys/kernel/debug/tracing/events/irq/enable" },
Riley Andrews412e4f62015-11-02 21:01:34 -0800120 { OPT, "/sys/kernel/debug/tracing/events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700121 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700122 { "freq", "CPU Frequency", 0, {
123 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_frequency/enable" },
124 { OPT, "/sys/kernel/debug/tracing/events/power/clock_set_rate/enable" },
Ruchi Kandoiffcc7112015-11-19 18:32:00 -0800125 { OPT, "/sys/kernel/debug/tracing/events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800126 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700127 { "membus", "Memory Bus Utilization", 0, {
128 { REQ, "/sys/kernel/debug/tracing/events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800129 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700130 { "idle", "CPU Idle", 0, {
131 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800132 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700133 { "disk", "Disk I/O", 0, {
Greg Hackmanne80d32c2014-11-20 12:59:44 -0800134 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_enter/enable" },
135 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_exit/enable" },
136 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_begin/enable" },
137 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_end/enable" },
138 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_begin/enable" },
139 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_end/enable" },
140 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable" },
141 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable" },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700142 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" },
143 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800144 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700145 { "mmc", "eMMC commands", 0, {
146 { REQ, "/sys/kernel/debug/tracing/events/mmc/enable" },
147 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700148 { "load", "CPU Load", 0, {
149 { REQ, "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800150 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700151 { "sync", "Synchronization", 0, {
152 { REQ, "/sys/kernel/debug/tracing/events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800153 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700154 { "workq", "Kernel Workqueues", 0, {
155 { REQ, "/sys/kernel/debug/tracing/events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800156 } },
Colin Cross580407f2014-08-18 15:22:13 -0700157 { "memreclaim", "Kernel Memory Reclaim", 0, {
158 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
159 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
160 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_wake/enable" },
161 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_sleep/enable" },
162 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800163 { "regulators", "Voltage and Current Regulators", 0, {
164 { REQ, "/sys/kernel/debug/tracing/events/regulator/enable" },
165 } },
Scott Bauerae473362015-06-08 16:32:36 -0700166 { "binder_driver", "Binder Kernel driver", 0, {
167 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction/enable" },
168 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction_received/enable" },
169 } },
170 { "binder_lock", "Binder global lock trace", 0, {
171 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_lock/enable" },
172 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_locked/enable" },
173 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_unlock/enable" },
174 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200175 { "pagecache", "Page cache", 0, {
176 { REQ, "/sys/kernel/debug/tracing/events/filemap/enable" },
177 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800178};
179
180/* Command line options */
181static int g_traceDurationSeconds = 5;
182static bool g_traceOverwrite = false;
183static int g_traceBufferSizeKB = 2048;
184static bool g_compress = false;
185static bool g_nohup = false;
186static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900187static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700188static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700189static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700190static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800191
192/* Global state */
193static bool g_traceAborted = false;
194static bool g_categoryEnables[NELEM(k_categories)] = {};
195
196/* Sys file paths */
197static const char* k_traceClockPath =
198 "/sys/kernel/debug/tracing/trace_clock";
199
200static const char* k_traceBufferSizePath =
201 "/sys/kernel/debug/tracing/buffer_size_kb";
202
203static const char* k_tracingOverwriteEnablePath =
204 "/sys/kernel/debug/tracing/options/overwrite";
205
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700206static const char* k_currentTracerPath =
207 "/sys/kernel/debug/tracing/current_tracer";
208
209static const char* k_printTgidPath =
210 "/sys/kernel/debug/tracing/options/print-tgid";
211
212static const char* k_funcgraphAbsTimePath =
213 "/sys/kernel/debug/tracing/options/funcgraph-abstime";
214
215static const char* k_funcgraphCpuPath =
216 "/sys/kernel/debug/tracing/options/funcgraph-cpu";
217
218static const char* k_funcgraphProcPath =
219 "/sys/kernel/debug/tracing/options/funcgraph-proc";
220
221static const char* k_funcgraphFlatPath =
222 "/sys/kernel/debug/tracing/options/funcgraph-flat";
223
224static const char* k_funcgraphDurationPath =
225 "/sys/kernel/debug/tracing/options/funcgraph-duration";
226
227static const char* k_ftraceFilterPath =
228 "/sys/kernel/debug/tracing/set_ftrace_filter";
229
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800230static const char* k_tracingOnPath =
231 "/sys/kernel/debug/tracing/tracing_on";
232
233static const char* k_tracePath =
234 "/sys/kernel/debug/tracing/trace";
235
Martijn Coenend9535872015-11-26 10:00:55 +0100236static const char* k_traceStreamPath =
237 "/sys/kernel/debug/tracing/trace_pipe";
238
John Reck469a1942015-03-26 15:31:35 -0700239static const char* k_traceMarkerPath =
240 "/sys/kernel/debug/tracing/trace_marker";
241
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800242// Check whether a file exists.
243static bool fileExists(const char* filename) {
244 return access(filename, F_OK) != -1;
245}
246
247// Check whether a file is writable.
248static bool fileIsWritable(const char* filename) {
249 return access(filename, W_OK) != -1;
250}
251
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700252// Truncate a file.
253static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800254{
Jamie Gennis43122e72013-03-21 14:06:31 -0700255 // This uses creat rather than truncate because some of the debug kernel
256 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
257 // calls to truncate, but they are cleared by calls to creat.
258 int traceFD = creat(path, 0);
259 if (traceFD == -1) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700260 fprintf(stderr, "error truncating %s: %s (%d)\n", path,
Jamie Gennis43122e72013-03-21 14:06:31 -0700261 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700262 return false;
263 }
264
Jamie Gennis43122e72013-03-21 14:06:31 -0700265 close(traceFD);
266
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700267 return true;
268}
269
270static bool _writeStr(const char* filename, const char* str, int flags)
271{
272 int fd = open(filename, flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800273 if (fd == -1) {
274 fprintf(stderr, "error opening %s: %s (%d)\n", filename,
275 strerror(errno), errno);
276 return false;
277 }
278
279 bool ok = true;
280 ssize_t len = strlen(str);
281 if (write(fd, str, len) != len) {
282 fprintf(stderr, "error writing to %s: %s (%d)\n", filename,
283 strerror(errno), errno);
284 ok = false;
285 }
286
287 close(fd);
288
289 return ok;
290}
291
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700292// Write a string to a file, returning true if the write was successful.
293static bool writeStr(const char* filename, const char* str)
294{
295 return _writeStr(filename, str, O_WRONLY);
296}
297
298// Append a string to a file, returning true if the write was successful.
299static bool appendStr(const char* filename, const char* str)
300{
301 return _writeStr(filename, str, O_APPEND|O_WRONLY);
302}
303
John Reck469a1942015-03-26 15:31:35 -0700304static void writeClockSyncMarker()
305{
306 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200307 int len = 0;
308 int fd = open(k_traceMarkerPath, O_WRONLY);
309 if (fd == -1) {
310 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
311 strerror(errno), errno);
312 return;
313 }
John Reck469a1942015-03-26 15:31:35 -0700314 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200315
316 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
317 if (write(fd, buffer, len) != len) {
318 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
319 }
320
321 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
322 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
323 if (write(fd, buffer, len) != len) {
324 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
325 }
326
327 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700328}
329
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800330// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
331// file.
332static bool setKernelOptionEnable(const char* filename, bool enable)
333{
334 return writeStr(filename, enable ? "1" : "0");
335}
336
337// Check whether the category is supported on the device with the current
338// rootness. A category is supported only if all its required /sys/ files are
339// writable and if enabling the category will enable one or more tracing tags
340// or /sys/ files.
341static bool isCategorySupported(const TracingCategory& category)
342{
sergeyvdb404152016-05-02 19:26:07 -0700343 if (strcmp(category.name, k_coreServiceCategory) == 0) {
344 char value[PROPERTY_VALUE_MAX];
345 property_get(k_coreServicesProp, value, "");
346 return strlen(value) != 0;
347 }
348
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800349 bool ok = category.tags != 0;
350 for (int i = 0; i < MAX_SYS_FILES; i++) {
351 const char* path = category.sysfiles[i].path;
352 bool req = category.sysfiles[i].required == REQ;
353 if (path != NULL) {
354 if (req) {
355 if (!fileIsWritable(path)) {
356 return false;
357 } else {
358 ok = true;
359 }
360 } else {
361 ok |= fileIsWritable(path);
362 }
363 }
364 }
365 return ok;
366}
367
368// Check whether the category would be supported on the device if the user
369// were root. This function assumes that root is able to write to any file
370// that exists. It performs the same logic as isCategorySupported, but it
371// uses file existance rather than writability in the /sys/ file checks.
372static bool isCategorySupportedForRoot(const TracingCategory& category)
373{
374 bool ok = category.tags != 0;
375 for (int i = 0; i < MAX_SYS_FILES; i++) {
376 const char* path = category.sysfiles[i].path;
377 bool req = category.sysfiles[i].required == REQ;
378 if (path != NULL) {
379 if (req) {
380 if (!fileExists(path)) {
381 return false;
382 } else {
383 ok = true;
384 }
385 } else {
386 ok |= fileExists(path);
387 }
388 }
389 }
390 return ok;
391}
392
393// Enable or disable overwriting of the kernel trace buffers. Disabling this
394// will cause tracing to stop once the trace buffers have filled up.
395static bool setTraceOverwriteEnable(bool enable)
396{
397 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
398}
399
400// Enable or disable kernel tracing.
401static bool setTracingEnabled(bool enable)
402{
403 return setKernelOptionEnable(k_tracingOnPath, enable);
404}
405
406// Clear the contents of the kernel trace.
407static bool clearTrace()
408{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700409 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800410}
411
412// Set the size of the kernel's trace buffer in kilobytes.
413static bool setTraceBufferSizeKB(int size)
414{
415 char str[32] = "1";
416 int len;
417 if (size < 1) {
418 size = 1;
419 }
420 snprintf(str, 32, "%d", size);
421 return writeStr(k_traceBufferSizePath, str);
422}
423
Colin Crossb1ce49b2014-08-20 14:28:47 -0700424// Read the trace_clock sysfs file and return true if it matches the requested
425// value. The trace_clock file format is:
426// local [global] counter uptime perf
427static bool isTraceClock(const char *mode)
428{
429 int fd = open(k_traceClockPath, O_RDONLY);
430 if (fd == -1) {
431 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceClockPath,
432 strerror(errno), errno);
433 return false;
434 }
435
436 char buf[4097];
437 ssize_t n = read(fd, buf, 4096);
438 close(fd);
439 if (n == -1) {
440 fprintf(stderr, "error reading %s: %s (%d)\n", k_traceClockPath,
441 strerror(errno), errno);
442 return false;
443 }
444 buf[n] = '\0';
445
446 char *start = strchr(buf, '[');
447 if (start == NULL) {
448 return false;
449 }
450 start++;
451
452 char *end = strchr(start, ']');
453 if (end == NULL) {
454 return false;
455 }
456 *end = '\0';
457
458 return strcmp(mode, start) == 0;
459}
460
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800461// Enable or disable the kernel's use of the global clock. Disabling the global
462// clock will result in the kernel using a per-CPU local clock.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700463// Any write to the trace_clock sysfs file will reset the buffer, so only
464// update it if the requested value is not the current value.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800465static bool setGlobalClockEnable(bool enable)
466{
Colin Crossb1ce49b2014-08-20 14:28:47 -0700467 const char *clock = enable ? "global" : "local";
468
469 if (isTraceClock(clock)) {
470 return true;
471 }
472
473 return writeStr(k_traceClockPath, clock);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800474}
475
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700476static bool setPrintTgidEnableIfPresent(bool enable)
477{
478 if (fileExists(k_printTgidPath)) {
479 return setKernelOptionEnable(k_printTgidPath, enable);
480 }
481 return true;
482}
483
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800484// Poke all the binder-enabled processes in the system to get them to re-read
485// their system properties.
486static bool pokeBinderServices()
487{
488 sp<IServiceManager> sm = defaultServiceManager();
489 Vector<String16> services = sm->listServices();
490 for (size_t i = 0; i < services.size(); i++) {
491 sp<IBinder> obj = sm->checkService(services[i]);
492 if (obj != NULL) {
493 Parcel data;
494 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
495 NULL, 0) != OK) {
496 if (false) {
497 // XXX: For some reason this fails on tablets trying to
498 // poke the "phone" service. It's not clear whether some
499 // are expected to fail.
500 String8 svc(services[i]);
501 fprintf(stderr, "error poking binder service %s\n",
502 svc.string());
503 return false;
504 }
505 }
506 }
507 }
508 return true;
509}
510
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100511// Poke all the HAL processes in the system to get them to re-read
512// their system properties.
513static void pokeHalServices()
514{
515 using ::android::hidl::manager::V1_0::IServiceManager;
516 using ::android::hardware::IBinder;
517 using ::android::hardware::hidl_string;
518 using ::android::hardware::Parcel;
519
520 Parcel data;
521
522 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800523 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100524 for (size_t i = 0; i < interfaces.size(); i++) {
525 string fqInstanceName = interfaces[i];
526 string::size_type n = fqInstanceName.find("/");
527 if (n == std::string::npos || interfaces[i].size() == n+1)
528 continue;
529 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
530 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800531 auto getRet = sm->get(fqInterfaceName, instanceName, [&](const auto &interface) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100532 // TODO(b/32756130)
533 // Once IServiceManager returns IBase, use interface->notifySyspropsChanged() here
534 interface->transact(IBinder::SYSPROPS_TRANSACTION, data, nullptr, 0, nullptr);
535 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800536 if (!getRet.isOk()) {
537 fprintf(stderr, "failed to get service %s: %s\n",
538 fqInstanceName.c_str(),
539 getRet.getStatus().toString8().string());
540 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100541 }
542 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800543 if (!listRet.isOk()) {
544 fprintf(stderr, "failed to list services: %s\n", listRet.getStatus().toString8().string());
545 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100546}
547
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800548// Set the trace tags that userland tracing uses, and poke the running
549// processes to pick up the new value.
550static bool setTagsProperty(uint64_t tags)
551{
sergeyv4144eff2016-04-28 11:40:04 -0700552 char buf[PROPERTY_VALUE_MAX];
553 snprintf(buf, sizeof(buf), "%#" PRIx64, tags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800554 if (property_set(k_traceTagsProperty, buf) < 0) {
555 fprintf(stderr, "error setting trace tags system property\n");
556 return false;
557 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700558 return true;
559}
560
sergeyv4144eff2016-04-28 11:40:04 -0700561static void clearAppProperties()
562{
563 char buf[PROPERTY_KEY_MAX];
564 for (int i = 0; i < MAX_PACKAGES; i++) {
565 snprintf(buf, sizeof(buf), k_traceAppsPropertyTemplate, i);
566 if (property_set(buf, "") < 0) {
567 fprintf(stderr, "failed to clear system property: %s\n", buf);
568 }
569 }
570 if (property_set(k_traceAppsNumberProperty, "") < 0) {
571 fprintf(stderr, "failed to clear system property: %s",
572 k_traceAppsNumberProperty);
573 }
574}
575
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700576// Set the system property that indicates which apps should perform
577// application-level tracing.
Dan Austin497951c2016-05-31 13:27:03 -0700578static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700579{
sergeyv4144eff2016-04-28 11:40:04 -0700580 char buf[PROPERTY_KEY_MAX];
581 int i = 0;
Dan Austin497951c2016-05-31 13:27:03 -0700582 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700583 while (start != NULL) {
584 if (i == MAX_PACKAGES) {
585 fprintf(stderr, "error: only 16 packages could be traced at once\n");
586 clearAppProperties();
587 return false;
588 }
589 char* end = strchr(start, ',');
590 if (end != NULL) {
591 *end = '\0';
592 end++;
593 }
594 snprintf(buf, sizeof(buf), k_traceAppsPropertyTemplate, i);
595 if (property_set(buf, start) < 0) {
596 fprintf(stderr, "error setting trace app %d property to %s\n", i, buf);
597 clearAppProperties();
598 return false;
599 }
600 start = end;
601 i++;
602 }
603
604 snprintf(buf, sizeof(buf), "%d", i);
605 if (property_set(k_traceAppsNumberProperty, buf) < 0) {
606 fprintf(stderr, "error setting trace app number property to %s\n", buf);
607 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700608 return false;
609 }
610 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800611}
612
613// Disable all /sys/ enable files.
614static bool disableKernelTraceEvents() {
615 bool ok = true;
616 for (int i = 0; i < NELEM(k_categories); i++) {
617 const TracingCategory &c = k_categories[i];
618 for (int j = 0; j < MAX_SYS_FILES; j++) {
619 const char* path = c.sysfiles[j].path;
620 if (path != NULL && fileIsWritable(path)) {
621 ok &= setKernelOptionEnable(path, false);
622 }
623 }
624 }
625 return ok;
626}
627
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700628// Verify that the comma separated list of functions are being traced by the
629// kernel.
630static bool verifyKernelTraceFuncs(const char* funcs)
631{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100632 std::string buf;
633 if (!android::base::ReadFileToString(k_ftraceFilterPath, &buf)) {
634 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700635 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100636 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700637 }
638
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100639 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700640
641 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100642 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700643 bool ok = true;
644 char* myFuncs = strdup(funcs);
645 char* func = strtok(myFuncs, ",");
646 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100647 if (!strchr(func, '*')) {
648 String8 fancyFunc = String8::format("\n%s\n", func);
649 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
650 if (!found || func[0] == '\0') {
651 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
652 "to trace.\n", func);
653 ok = false;
654 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700655 }
656 func = strtok(NULL, ",");
657 }
658 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700659 return ok;
660}
661
662// Set the comma separated list of functions that the kernel is to trace.
663static bool setKernelTraceFuncs(const char* funcs)
664{
665 bool ok = true;
666
667 if (funcs == NULL || funcs[0] == '\0') {
668 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700669 if (fileIsWritable(k_currentTracerPath)) {
670 ok &= writeStr(k_currentTracerPath, "nop");
671 }
672 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700673 ok &= truncateFile(k_ftraceFilterPath);
674 }
675 } else {
676 // Enable kernel function tracing.
677 ok &= writeStr(k_currentTracerPath, "function_graph");
678 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
679 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
680 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
681 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
682
683 // Set the requested filter functions.
684 ok &= truncateFile(k_ftraceFilterPath);
685 char* myFuncs = strdup(funcs);
686 char* func = strtok(myFuncs, ",");
687 while (func) {
688 ok &= appendStr(k_ftraceFilterPath, func);
689 func = strtok(NULL, ",");
690 }
691 free(myFuncs);
692
693 // Verify that the set functions are being traced.
694 if (ok) {
695 ok &= verifyKernelTraceFuncs(funcs);
696 }
697 }
698
699 return ok;
700}
701
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900702static bool setCategoryEnable(const char* name, bool enable)
703{
704 for (int i = 0; i < NELEM(k_categories); i++) {
705 const TracingCategory& c = k_categories[i];
706 if (strcmp(name, c.name) == 0) {
707 if (isCategorySupported(c)) {
708 g_categoryEnables[i] = enable;
709 return true;
710 } else {
711 if (isCategorySupportedForRoot(c)) {
712 fprintf(stderr, "error: category \"%s\" requires root "
713 "privileges.\n", name);
714 } else {
715 fprintf(stderr, "error: category \"%s\" is not supported "
716 "on this device.\n", name);
717 }
718 return false;
719 }
720 }
721 }
722 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
723 return false;
724}
725
726static bool setCategoriesEnableFromFile(const char* categories_file)
727{
728 if (!categories_file) {
729 return true;
730 }
731 Tokenizer* tokenizer = NULL;
732 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
733 return false;
734 }
735 bool ok = true;
736 while (!tokenizer->isEol()) {
737 String8 token = tokenizer->nextToken(" ");
738 if (token.isEmpty()) {
739 tokenizer->skipDelimiters(" ");
740 continue;
741 }
742 ok &= setCategoryEnable(token.string(), true);
743 }
744 delete tokenizer;
745 return ok;
746}
747
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700748// Set all the kernel tracing settings to the desired state for this trace
749// capture.
750static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800751{
752 bool ok = true;
753
754 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900755 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800756 ok &= setTraceOverwriteEnable(g_traceOverwrite);
757 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
758 ok &= setGlobalClockEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700759 ok &= setPrintTgidEnableIfPresent(true);
760 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800761
762 // Set up the tags property.
763 uint64_t tags = 0;
764 for (int i = 0; i < NELEM(k_categories); i++) {
765 if (g_categoryEnables[i]) {
766 const TracingCategory &c = k_categories[i];
767 tags |= c.tags;
768 }
769 }
770 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700771
772 bool coreServicesTagEnabled = false;
773 for (int i = 0; i < NELEM(k_categories); i++) {
774 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
775 coreServicesTagEnabled = g_categoryEnables[i];
776 }
777 }
778
779 std::string packageList(g_debugAppCmdLine);
780 if (coreServicesTagEnabled) {
781 char value[PROPERTY_VALUE_MAX];
782 property_get(k_coreServicesProp, value, "");
783 if (!packageList.empty()) {
784 packageList += ",";
785 }
786 packageList += value;
787 }
Dan Austin497951c2016-05-31 13:27:03 -0700788 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700789 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100790 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800791
792 // Disable all the sysfs enables. This is done as a separate loop from
793 // the enables to allow the same enable to exist in multiple categories.
794 ok &= disableKernelTraceEvents();
795
796 // Enable all the sysfs enables that are in an enabled category.
797 for (int i = 0; i < NELEM(k_categories); i++) {
798 if (g_categoryEnables[i]) {
799 const TracingCategory &c = k_categories[i];
800 for (int j = 0; j < MAX_SYS_FILES; j++) {
801 const char* path = c.sysfiles[j].path;
802 bool required = c.sysfiles[j].required == REQ;
803 if (path != NULL) {
804 if (fileIsWritable(path)) {
805 ok &= setKernelOptionEnable(path, true);
806 } else if (required) {
807 fprintf(stderr, "error writing file %s\n", path);
808 ok = false;
809 }
810 }
811 }
812 }
813 }
814
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800815 return ok;
816}
817
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700818// Reset all the kernel tracing settings to their default state.
819static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800820{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800821 // Disable all tracing that we're able to.
822 disableKernelTraceEvents();
823
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700824 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800825 setTagsProperty(0);
sergeyv4144eff2016-04-28 11:40:04 -0700826 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700827 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800828
829 // Set the options back to their defaults.
830 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700831 setTraceBufferSizeKB(1);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800832 setGlobalClockEnable(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700833 setPrintTgidEnableIfPresent(false);
834 setKernelTraceFuncs(NULL);
835}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800836
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700837
838// Enable tracing in the kernel.
839static bool startTrace()
840{
841 return setTracingEnabled(true);
842}
843
844// Disable tracing in the kernel.
845static void stopTrace()
846{
847 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800848}
849
Martijn Coenend9535872015-11-26 10:00:55 +0100850// Read data from the tracing pipe and forward to stdout
851static void streamTrace()
852{
853 char trace_data[4096];
854 int traceFD = open(k_traceStreamPath, O_RDWR);
855 if (traceFD == -1) {
856 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
857 strerror(errno), errno);
858 return;
859 }
860 while (!g_traceAborted) {
861 ssize_t bytes_read = read(traceFD, trace_data, 4096);
862 if (bytes_read > 0) {
863 write(STDOUT_FILENO, trace_data, bytes_read);
864 fflush(stdout);
865 } else {
866 if (!g_traceAborted) {
867 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
868 bytes_read, errno, strerror(errno));
869 }
870 break;
871 }
872 }
873}
874
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800875// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700876static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800877{
John Reck6c8ac922016-03-28 11:25:30 -0700878 ALOGI("Dumping trace");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800879 int traceFD = open(k_tracePath, O_RDWR);
880 if (traceFD == -1) {
881 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
882 strerror(errno), errno);
883 return;
884 }
885
886 if (g_compress) {
887 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800888 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700889
890 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800891 if (result != Z_OK) {
892 fprintf(stderr, "error initializing zlib: %d\n", result);
893 close(traceFD);
894 return;
895 }
896
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700897 constexpr size_t bufSize = 64*1024;
898 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
899 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
900 if (!in || !out) {
901 fprintf(stderr, "couldn't allocate buffers\n");
902 close(traceFD);
903 return;
904 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800905
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700906 int flush = Z_NO_FLUSH;
907
908 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800909 zs.avail_out = bufSize;
910
911 do {
912
913 if (zs.avail_in == 0) {
914 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700915 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800916 if (result < 0) {
917 fprintf(stderr, "error reading trace: %s (%d)\n",
918 strerror(errno), errno);
919 result = Z_STREAM_END;
920 break;
921 } else if (result == 0) {
922 flush = Z_FINISH;
923 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700924 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800925 zs.avail_in = result;
926 }
927 }
928
929 if (zs.avail_out == 0) {
930 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700931 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800932 if ((size_t)result < bufSize) {
933 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
934 strerror(errno), errno);
935 result = Z_STREAM_END; // skip deflate error message
936 zs.avail_out = bufSize; // skip the final write
937 break;
938 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700939 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800940 zs.avail_out = bufSize;
941 }
942
943 } while ((result = deflate(&zs, flush)) == Z_OK);
944
945 if (result != Z_STREAM_END) {
946 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
947 }
948
949 if (zs.avail_out < bufSize) {
950 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -0700951 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800952 if ((size_t)result < bytes) {
953 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
954 strerror(errno), errno);
955 }
956 }
957
958 result = deflateEnd(&zs);
959 if (result != Z_OK) {
960 fprintf(stderr, "error cleaning up zlib: %d\n", result);
961 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800962 } else {
963 ssize_t sent = 0;
John Reck40b26b42016-03-30 09:44:36 -0700964 while ((sent = sendfile(outFd, traceFD, NULL, 64*1024*1024)) > 0);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800965 if (sent == -1) {
966 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
967 errno);
968 }
969 }
970
971 close(traceFD);
972}
973
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700974static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800975{
976 if (!g_nohup) {
977 g_traceAborted = true;
978 }
979}
980
981static void registerSigHandler()
982{
983 struct sigaction sa;
984 sigemptyset(&sa.sa_mask);
985 sa.sa_flags = 0;
986 sa.sa_handler = handleSignal;
987 sigaction(SIGHUP, &sa, NULL);
988 sigaction(SIGINT, &sa, NULL);
989 sigaction(SIGQUIT, &sa, NULL);
990 sigaction(SIGTERM, &sa, NULL);
991}
992
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800993static void listSupportedCategories()
994{
995 for (int i = 0; i < NELEM(k_categories); i++) {
996 const TracingCategory& c = k_categories[i];
997 if (isCategorySupported(c)) {
998 printf(" %10s - %s\n", c.name, c.longname);
999 }
1000 }
1001}
1002
1003// Print the command usage help to stderr.
1004static void showHelp(const char *cmd)
1005{
1006 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1007 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001008 " -a appname enable app-level tracing for a comma "
1009 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001010 " -b N use a trace buffer size of N KB\n"
1011 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001012 " -f filename use the categories written in a file as space-separated\n"
1013 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001014 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001015 " -n ignore signals\n"
1016 " -s N sleep for N seconds before tracing [default 0]\n"
Elliott Hughesf884a062016-07-22 09:38:44 -07001017 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001018 " -z compress the trace dump\n"
1019 " --async_start start circular trace and return immediatly\n"
1020 " --async_dump dump the current contents of circular trace buffer\n"
1021 " --async_stop stop tracing and dump the current contents of circular\n"
1022 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001023 " --stream stream trace to stdout as it enters the trace buffer\n"
1024 " Note: this can take significant CPU time, and is best\n"
1025 " used for measuring things that are not affected by\n"
1026 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001027 " --list_categories\n"
1028 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001029 " -o filename write the trace to the specified file instead\n"
1030 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001031 );
1032}
1033
1034int main(int argc, char **argv)
1035{
1036 bool async = false;
1037 bool traceStart = true;
1038 bool traceStop = true;
1039 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001040 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001041
1042 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1043 showHelp(argv[0]);
1044 exit(0);
1045 }
1046
1047 for (;;) {
1048 int ret;
1049 int option_index = 0;
1050 static struct option long_options[] = {
1051 {"async_start", no_argument, 0, 0 },
1052 {"async_stop", no_argument, 0, 0 },
1053 {"async_dump", no_argument, 0, 0 },
1054 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +01001055 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001056 { 0, 0, 0, 0 }
1057 };
1058
John Reck40b26b42016-03-30 09:44:36 -07001059 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001060 long_options, &option_index);
1061
1062 if (ret < 0) {
1063 for (int i = optind; i < argc; i++) {
1064 if (!setCategoryEnable(argv[i], true)) {
1065 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1066 exit(1);
1067 }
1068 }
1069 break;
1070 }
1071
1072 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001073 case 'a':
1074 g_debugAppCmdLine = optarg;
1075 break;
1076
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001077 case 'b':
1078 g_traceBufferSizeKB = atoi(optarg);
1079 break;
1080
1081 case 'c':
1082 g_traceOverwrite = true;
1083 break;
1084
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001085 case 'f':
1086 g_categoriesFile = optarg;
1087 break;
1088
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001089 case 'k':
1090 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001091 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001092
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001093 case 'n':
1094 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001095 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001096
1097 case 's':
1098 g_initialSleepSecs = atoi(optarg);
1099 break;
1100
1101 case 't':
1102 g_traceDurationSeconds = atoi(optarg);
1103 break;
1104
1105 case 'z':
1106 g_compress = true;
1107 break;
1108
John Reck40b26b42016-03-30 09:44:36 -07001109 case 'o':
1110 g_outputFile = optarg;
1111 break;
1112
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001113 case 0:
1114 if (!strcmp(long_options[option_index].name, "async_start")) {
1115 async = true;
1116 traceStop = false;
1117 traceDump = false;
1118 g_traceOverwrite = true;
1119 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1120 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001121 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001122 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1123 async = true;
1124 traceStart = false;
1125 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001126 } else if (!strcmp(long_options[option_index].name, "stream")) {
1127 traceStream = true;
1128 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001129 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1130 listSupportedCategories();
1131 exit(0);
1132 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001133 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001134
1135 default:
1136 fprintf(stderr, "\n");
1137 showHelp(argv[0]);
1138 exit(-1);
1139 break;
1140 }
1141 }
1142
1143 registerSigHandler();
1144
1145 if (g_initialSleepSecs > 0) {
1146 sleep(g_initialSleepSecs);
1147 }
1148
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001149 bool ok = true;
1150 ok &= setUpTrace();
1151 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001152
1153 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001154 if (!traceStream) {
1155 printf("capturing trace...");
1156 fflush(stdout);
1157 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001158
1159 // We clear the trace after starting it because tracing gets enabled for
1160 // each CPU individually in the kernel. Having the beginning of the trace
1161 // contain entries from only one CPU can cause "begin" entries without a
1162 // matching "end" entry to show up if a task gets migrated from one CPU to
1163 // another.
1164 ok = clearTrace();
1165
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001166 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001167 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001168 // Sleep to allow the trace to be captured.
1169 struct timespec timeLeft;
1170 timeLeft.tv_sec = g_traceDurationSeconds;
1171 timeLeft.tv_nsec = 0;
1172 do {
1173 if (g_traceAborted) {
1174 break;
1175 }
1176 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1177 }
Martijn Coenend9535872015-11-26 10:00:55 +01001178
1179 if (traceStream) {
1180 streamTrace();
1181 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001182 }
1183
1184 // Stop the trace and restore the default settings.
1185 if (traceStop)
1186 stopTrace();
1187
1188 if (ok && traceDump) {
1189 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001190 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001191 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001192 int outFd = STDOUT_FILENO;
1193 if (g_outputFile) {
1194 outFd = open(g_outputFile, O_WRONLY | O_CREAT);
1195 }
1196 if (outFd == -1) {
1197 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1198 } else {
1199 dprintf(outFd, "TRACE:\n");
1200 dumpTrace(outFd);
1201 if (g_outputFile) {
1202 close(outFd);
1203 }
1204 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001205 } else {
1206 printf("\ntrace aborted.\n");
1207 fflush(stdout);
1208 }
1209 clearTrace();
1210 } else if (!ok) {
1211 fprintf(stderr, "unable to start tracing\n");
1212 }
1213
1214 // Reset the trace buffer size to 1.
1215 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001216 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001217
1218 return g_traceAborted ? 1 : 0;
1219}