blob: 5a347557e4acb06aa08c3927ad02b2ba21e3fcc8 [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, { } },
Felipe Leme0f97c1d2016-09-07 11:33:26 -0700111 { "network", "Network", ATRACE_TAG_NETWORK, { } },
sergeyvdb404152016-05-02 19:26:07 -0700112 { k_coreServiceCategory, "Core services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700113 { "sched", "CPU Scheduling", 0, {
114 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_switch/enable" },
115 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_wakeup/enable" },
Riley Andrews5672bb72015-11-19 13:31:17 -0800116 { OPT, "/sys/kernel/debug/tracing/events/sched/sched_blocked_reason/enable" },
Ruchi Kandoicfe500d2015-11-23 13:47:20 -0800117 { OPT, "/sys/kernel/debug/tracing/events/sched/sched_cpu_hotplug/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800118 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700119 { "irq", "IRQ Events", 0, {
120 { REQ, "/sys/kernel/debug/tracing/events/irq/enable" },
Riley Andrews412e4f62015-11-02 21:01:34 -0800121 { OPT, "/sys/kernel/debug/tracing/events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700122 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700123 { "freq", "CPU Frequency", 0, {
124 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_frequency/enable" },
125 { OPT, "/sys/kernel/debug/tracing/events/power/clock_set_rate/enable" },
Ruchi Kandoiffcc7112015-11-19 18:32:00 -0800126 { OPT, "/sys/kernel/debug/tracing/events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800127 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700128 { "membus", "Memory Bus Utilization", 0, {
129 { REQ, "/sys/kernel/debug/tracing/events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800130 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700131 { "idle", "CPU Idle", 0, {
132 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800133 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700134 { "disk", "Disk I/O", 0, {
Greg Hackmanne80d32c2014-11-20 12:59:44 -0800135 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_enter/enable" },
136 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_exit/enable" },
137 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_begin/enable" },
138 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_end/enable" },
139 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_begin/enable" },
140 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_end/enable" },
141 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable" },
142 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable" },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700143 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" },
144 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800145 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700146 { "mmc", "eMMC commands", 0, {
147 { REQ, "/sys/kernel/debug/tracing/events/mmc/enable" },
148 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700149 { "load", "CPU Load", 0, {
150 { REQ, "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800151 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700152 { "sync", "Synchronization", 0, {
153 { REQ, "/sys/kernel/debug/tracing/events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800154 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700155 { "workq", "Kernel Workqueues", 0, {
156 { REQ, "/sys/kernel/debug/tracing/events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800157 } },
Colin Cross580407f2014-08-18 15:22:13 -0700158 { "memreclaim", "Kernel Memory Reclaim", 0, {
159 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
160 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
161 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_wake/enable" },
162 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_sleep/enable" },
163 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800164 { "regulators", "Voltage and Current Regulators", 0, {
165 { REQ, "/sys/kernel/debug/tracing/events/regulator/enable" },
166 } },
Scott Bauerae473362015-06-08 16:32:36 -0700167 { "binder_driver", "Binder Kernel driver", 0, {
168 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction/enable" },
169 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction_received/enable" },
170 } },
171 { "binder_lock", "Binder global lock trace", 0, {
172 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_lock/enable" },
173 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_locked/enable" },
174 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_unlock/enable" },
175 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200176 { "pagecache", "Page cache", 0, {
177 { REQ, "/sys/kernel/debug/tracing/events/filemap/enable" },
178 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800179};
180
181/* Command line options */
182static int g_traceDurationSeconds = 5;
183static bool g_traceOverwrite = false;
184static int g_traceBufferSizeKB = 2048;
185static bool g_compress = false;
186static bool g_nohup = false;
187static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900188static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700189static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700190static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700191static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800192
193/* Global state */
194static bool g_traceAborted = false;
195static bool g_categoryEnables[NELEM(k_categories)] = {};
196
197/* Sys file paths */
198static const char* k_traceClockPath =
199 "/sys/kernel/debug/tracing/trace_clock";
200
201static const char* k_traceBufferSizePath =
202 "/sys/kernel/debug/tracing/buffer_size_kb";
203
204static const char* k_tracingOverwriteEnablePath =
205 "/sys/kernel/debug/tracing/options/overwrite";
206
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700207static const char* k_currentTracerPath =
208 "/sys/kernel/debug/tracing/current_tracer";
209
210static const char* k_printTgidPath =
211 "/sys/kernel/debug/tracing/options/print-tgid";
212
213static const char* k_funcgraphAbsTimePath =
214 "/sys/kernel/debug/tracing/options/funcgraph-abstime";
215
216static const char* k_funcgraphCpuPath =
217 "/sys/kernel/debug/tracing/options/funcgraph-cpu";
218
219static const char* k_funcgraphProcPath =
220 "/sys/kernel/debug/tracing/options/funcgraph-proc";
221
222static const char* k_funcgraphFlatPath =
223 "/sys/kernel/debug/tracing/options/funcgraph-flat";
224
225static const char* k_funcgraphDurationPath =
226 "/sys/kernel/debug/tracing/options/funcgraph-duration";
227
228static const char* k_ftraceFilterPath =
229 "/sys/kernel/debug/tracing/set_ftrace_filter";
230
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800231static const char* k_tracingOnPath =
232 "/sys/kernel/debug/tracing/tracing_on";
233
234static const char* k_tracePath =
235 "/sys/kernel/debug/tracing/trace";
236
Martijn Coenend9535872015-11-26 10:00:55 +0100237static const char* k_traceStreamPath =
238 "/sys/kernel/debug/tracing/trace_pipe";
239
John Reck469a1942015-03-26 15:31:35 -0700240static const char* k_traceMarkerPath =
241 "/sys/kernel/debug/tracing/trace_marker";
242
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800243// Check whether a file exists.
244static bool fileExists(const char* filename) {
245 return access(filename, F_OK) != -1;
246}
247
248// Check whether a file is writable.
249static bool fileIsWritable(const char* filename) {
250 return access(filename, W_OK) != -1;
251}
252
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700253// Truncate a file.
254static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800255{
Jamie Gennis43122e72013-03-21 14:06:31 -0700256 // This uses creat rather than truncate because some of the debug kernel
257 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
258 // calls to truncate, but they are cleared by calls to creat.
259 int traceFD = creat(path, 0);
260 if (traceFD == -1) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700261 fprintf(stderr, "error truncating %s: %s (%d)\n", path,
Jamie Gennis43122e72013-03-21 14:06:31 -0700262 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700263 return false;
264 }
265
Jamie Gennis43122e72013-03-21 14:06:31 -0700266 close(traceFD);
267
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700268 return true;
269}
270
271static bool _writeStr(const char* filename, const char* str, int flags)
272{
273 int fd = open(filename, flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800274 if (fd == -1) {
275 fprintf(stderr, "error opening %s: %s (%d)\n", filename,
276 strerror(errno), errno);
277 return false;
278 }
279
280 bool ok = true;
281 ssize_t len = strlen(str);
282 if (write(fd, str, len) != len) {
283 fprintf(stderr, "error writing to %s: %s (%d)\n", filename,
284 strerror(errno), errno);
285 ok = false;
286 }
287
288 close(fd);
289
290 return ok;
291}
292
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700293// Write a string to a file, returning true if the write was successful.
294static bool writeStr(const char* filename, const char* str)
295{
296 return _writeStr(filename, str, O_WRONLY);
297}
298
299// Append a string to a file, returning true if the write was successful.
300static bool appendStr(const char* filename, const char* str)
301{
302 return _writeStr(filename, str, O_APPEND|O_WRONLY);
303}
304
John Reck469a1942015-03-26 15:31:35 -0700305static void writeClockSyncMarker()
306{
307 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200308 int len = 0;
309 int fd = open(k_traceMarkerPath, O_WRONLY);
310 if (fd == -1) {
311 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
312 strerror(errno), errno);
313 return;
314 }
John Reck469a1942015-03-26 15:31:35 -0700315 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200316
317 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
318 if (write(fd, buffer, len) != len) {
319 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
320 }
321
322 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
323 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
324 if (write(fd, buffer, len) != len) {
325 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
326 }
327
328 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700329}
330
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800331// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
332// file.
333static bool setKernelOptionEnable(const char* filename, bool enable)
334{
335 return writeStr(filename, enable ? "1" : "0");
336}
337
338// Check whether the category is supported on the device with the current
339// rootness. A category is supported only if all its required /sys/ files are
340// writable and if enabling the category will enable one or more tracing tags
341// or /sys/ files.
342static bool isCategorySupported(const TracingCategory& category)
343{
sergeyvdb404152016-05-02 19:26:07 -0700344 if (strcmp(category.name, k_coreServiceCategory) == 0) {
345 char value[PROPERTY_VALUE_MAX];
346 property_get(k_coreServicesProp, value, "");
347 return strlen(value) != 0;
348 }
349
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800350 bool ok = category.tags != 0;
351 for (int i = 0; i < MAX_SYS_FILES; i++) {
352 const char* path = category.sysfiles[i].path;
353 bool req = category.sysfiles[i].required == REQ;
354 if (path != NULL) {
355 if (req) {
356 if (!fileIsWritable(path)) {
357 return false;
358 } else {
359 ok = true;
360 }
361 } else {
362 ok |= fileIsWritable(path);
363 }
364 }
365 }
366 return ok;
367}
368
369// Check whether the category would be supported on the device if the user
370// were root. This function assumes that root is able to write to any file
371// that exists. It performs the same logic as isCategorySupported, but it
372// uses file existance rather than writability in the /sys/ file checks.
373static bool isCategorySupportedForRoot(const TracingCategory& category)
374{
375 bool ok = category.tags != 0;
376 for (int i = 0; i < MAX_SYS_FILES; i++) {
377 const char* path = category.sysfiles[i].path;
378 bool req = category.sysfiles[i].required == REQ;
379 if (path != NULL) {
380 if (req) {
381 if (!fileExists(path)) {
382 return false;
383 } else {
384 ok = true;
385 }
386 } else {
387 ok |= fileExists(path);
388 }
389 }
390 }
391 return ok;
392}
393
394// Enable or disable overwriting of the kernel trace buffers. Disabling this
395// will cause tracing to stop once the trace buffers have filled up.
396static bool setTraceOverwriteEnable(bool enable)
397{
398 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
399}
400
401// Enable or disable kernel tracing.
402static bool setTracingEnabled(bool enable)
403{
404 return setKernelOptionEnable(k_tracingOnPath, enable);
405}
406
407// Clear the contents of the kernel trace.
408static bool clearTrace()
409{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700410 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800411}
412
413// Set the size of the kernel's trace buffer in kilobytes.
414static bool setTraceBufferSizeKB(int size)
415{
416 char str[32] = "1";
417 int len;
418 if (size < 1) {
419 size = 1;
420 }
421 snprintf(str, 32, "%d", size);
422 return writeStr(k_traceBufferSizePath, str);
423}
424
Colin Crossb1ce49b2014-08-20 14:28:47 -0700425// Read the trace_clock sysfs file and return true if it matches the requested
426// value. The trace_clock file format is:
427// local [global] counter uptime perf
428static bool isTraceClock(const char *mode)
429{
430 int fd = open(k_traceClockPath, O_RDONLY);
431 if (fd == -1) {
432 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceClockPath,
433 strerror(errno), errno);
434 return false;
435 }
436
437 char buf[4097];
438 ssize_t n = read(fd, buf, 4096);
439 close(fd);
440 if (n == -1) {
441 fprintf(stderr, "error reading %s: %s (%d)\n", k_traceClockPath,
442 strerror(errno), errno);
443 return false;
444 }
445 buf[n] = '\0';
446
447 char *start = strchr(buf, '[');
448 if (start == NULL) {
449 return false;
450 }
451 start++;
452
453 char *end = strchr(start, ']');
454 if (end == NULL) {
455 return false;
456 }
457 *end = '\0';
458
459 return strcmp(mode, start) == 0;
460}
461
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800462// Enable or disable the kernel's use of the global clock. Disabling the global
463// clock will result in the kernel using a per-CPU local clock.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700464// Any write to the trace_clock sysfs file will reset the buffer, so only
465// update it if the requested value is not the current value.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800466static bool setGlobalClockEnable(bool enable)
467{
Colin Crossb1ce49b2014-08-20 14:28:47 -0700468 const char *clock = enable ? "global" : "local";
469
470 if (isTraceClock(clock)) {
471 return true;
472 }
473
474 return writeStr(k_traceClockPath, clock);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800475}
476
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700477static bool setPrintTgidEnableIfPresent(bool enable)
478{
479 if (fileExists(k_printTgidPath)) {
480 return setKernelOptionEnable(k_printTgidPath, enable);
481 }
482 return true;
483}
484
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800485// Poke all the binder-enabled processes in the system to get them to re-read
486// their system properties.
487static bool pokeBinderServices()
488{
489 sp<IServiceManager> sm = defaultServiceManager();
490 Vector<String16> services = sm->listServices();
491 for (size_t i = 0; i < services.size(); i++) {
492 sp<IBinder> obj = sm->checkService(services[i]);
493 if (obj != NULL) {
494 Parcel data;
495 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
496 NULL, 0) != OK) {
497 if (false) {
498 // XXX: For some reason this fails on tablets trying to
499 // poke the "phone" service. It's not clear whether some
500 // are expected to fail.
501 String8 svc(services[i]);
502 fprintf(stderr, "error poking binder service %s\n",
503 svc.string());
504 return false;
505 }
506 }
507 }
508 }
509 return true;
510}
511
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100512// Poke all the HAL processes in the system to get them to re-read
513// their system properties.
514static void pokeHalServices()
515{
516 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100517 using ::android::hardware::hidl_string;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100518
519 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800520
521 if (sm == nullptr) {
522 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
523 return;
524 }
525
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800526 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100527 for (size_t i = 0; i < interfaces.size(); i++) {
528 string fqInstanceName = interfaces[i];
529 string::size_type n = fqInstanceName.find("/");
530 if (n == std::string::npos || interfaces[i].size() == n+1)
531 continue;
532 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
533 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800534 auto getRet = sm->get(fqInterfaceName, instanceName, [&](const auto &interface) {
Yifan Hong61954a42016-12-05 12:58:05 -0800535 auto notifyRet = interface->notifySyspropsChanged();
536 if (!notifyRet.isOk()) {
537 fprintf(stderr, "failed to notifySyspropsChanged on service %s: %s\n",
538 fqInstanceName.c_str(),
539 notifyRet.getStatus().toString8().string());
540 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100541 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800542 if (!getRet.isOk()) {
543 fprintf(stderr, "failed to get service %s: %s\n",
544 fqInstanceName.c_str(),
545 getRet.getStatus().toString8().string());
546 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100547 }
548 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800549 if (!listRet.isOk()) {
550 fprintf(stderr, "failed to list services: %s\n", listRet.getStatus().toString8().string());
551 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100552}
553
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800554// Set the trace tags that userland tracing uses, and poke the running
555// processes to pick up the new value.
556static bool setTagsProperty(uint64_t tags)
557{
sergeyv4144eff2016-04-28 11:40:04 -0700558 char buf[PROPERTY_VALUE_MAX];
559 snprintf(buf, sizeof(buf), "%#" PRIx64, tags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800560 if (property_set(k_traceTagsProperty, buf) < 0) {
561 fprintf(stderr, "error setting trace tags system property\n");
562 return false;
563 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700564 return true;
565}
566
sergeyv4144eff2016-04-28 11:40:04 -0700567static void clearAppProperties()
568{
569 char buf[PROPERTY_KEY_MAX];
570 for (int i = 0; i < MAX_PACKAGES; i++) {
571 snprintf(buf, sizeof(buf), k_traceAppsPropertyTemplate, i);
572 if (property_set(buf, "") < 0) {
573 fprintf(stderr, "failed to clear system property: %s\n", buf);
574 }
575 }
576 if (property_set(k_traceAppsNumberProperty, "") < 0) {
577 fprintf(stderr, "failed to clear system property: %s",
578 k_traceAppsNumberProperty);
579 }
580}
581
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700582// Set the system property that indicates which apps should perform
583// application-level tracing.
Dan Austin497951c2016-05-31 13:27:03 -0700584static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700585{
sergeyv4144eff2016-04-28 11:40:04 -0700586 char buf[PROPERTY_KEY_MAX];
587 int i = 0;
Dan Austin497951c2016-05-31 13:27:03 -0700588 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700589 while (start != NULL) {
590 if (i == MAX_PACKAGES) {
591 fprintf(stderr, "error: only 16 packages could be traced at once\n");
592 clearAppProperties();
593 return false;
594 }
595 char* end = strchr(start, ',');
596 if (end != NULL) {
597 *end = '\0';
598 end++;
599 }
600 snprintf(buf, sizeof(buf), k_traceAppsPropertyTemplate, i);
601 if (property_set(buf, start) < 0) {
602 fprintf(stderr, "error setting trace app %d property to %s\n", i, buf);
603 clearAppProperties();
604 return false;
605 }
606 start = end;
607 i++;
608 }
609
610 snprintf(buf, sizeof(buf), "%d", i);
611 if (property_set(k_traceAppsNumberProperty, buf) < 0) {
612 fprintf(stderr, "error setting trace app number property to %s\n", buf);
613 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700614 return false;
615 }
616 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800617}
618
619// Disable all /sys/ enable files.
620static bool disableKernelTraceEvents() {
621 bool ok = true;
622 for (int i = 0; i < NELEM(k_categories); i++) {
623 const TracingCategory &c = k_categories[i];
624 for (int j = 0; j < MAX_SYS_FILES; j++) {
625 const char* path = c.sysfiles[j].path;
626 if (path != NULL && fileIsWritable(path)) {
627 ok &= setKernelOptionEnable(path, false);
628 }
629 }
630 }
631 return ok;
632}
633
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700634// Verify that the comma separated list of functions are being traced by the
635// kernel.
636static bool verifyKernelTraceFuncs(const char* funcs)
637{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100638 std::string buf;
639 if (!android::base::ReadFileToString(k_ftraceFilterPath, &buf)) {
640 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700641 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100642 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700643 }
644
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100645 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700646
647 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100648 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700649 bool ok = true;
650 char* myFuncs = strdup(funcs);
651 char* func = strtok(myFuncs, ",");
652 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100653 if (!strchr(func, '*')) {
654 String8 fancyFunc = String8::format("\n%s\n", func);
655 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
656 if (!found || func[0] == '\0') {
657 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
658 "to trace.\n", func);
659 ok = false;
660 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700661 }
662 func = strtok(NULL, ",");
663 }
664 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700665 return ok;
666}
667
668// Set the comma separated list of functions that the kernel is to trace.
669static bool setKernelTraceFuncs(const char* funcs)
670{
671 bool ok = true;
672
673 if (funcs == NULL || funcs[0] == '\0') {
674 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700675 if (fileIsWritable(k_currentTracerPath)) {
676 ok &= writeStr(k_currentTracerPath, "nop");
677 }
678 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700679 ok &= truncateFile(k_ftraceFilterPath);
680 }
681 } else {
682 // Enable kernel function tracing.
683 ok &= writeStr(k_currentTracerPath, "function_graph");
684 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
685 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
686 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
687 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
688
689 // Set the requested filter functions.
690 ok &= truncateFile(k_ftraceFilterPath);
691 char* myFuncs = strdup(funcs);
692 char* func = strtok(myFuncs, ",");
693 while (func) {
694 ok &= appendStr(k_ftraceFilterPath, func);
695 func = strtok(NULL, ",");
696 }
697 free(myFuncs);
698
699 // Verify that the set functions are being traced.
700 if (ok) {
701 ok &= verifyKernelTraceFuncs(funcs);
702 }
703 }
704
705 return ok;
706}
707
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900708static bool setCategoryEnable(const char* name, bool enable)
709{
710 for (int i = 0; i < NELEM(k_categories); i++) {
711 const TracingCategory& c = k_categories[i];
712 if (strcmp(name, c.name) == 0) {
713 if (isCategorySupported(c)) {
714 g_categoryEnables[i] = enable;
715 return true;
716 } else {
717 if (isCategorySupportedForRoot(c)) {
718 fprintf(stderr, "error: category \"%s\" requires root "
719 "privileges.\n", name);
720 } else {
721 fprintf(stderr, "error: category \"%s\" is not supported "
722 "on this device.\n", name);
723 }
724 return false;
725 }
726 }
727 }
728 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
729 return false;
730}
731
732static bool setCategoriesEnableFromFile(const char* categories_file)
733{
734 if (!categories_file) {
735 return true;
736 }
737 Tokenizer* tokenizer = NULL;
738 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
739 return false;
740 }
741 bool ok = true;
742 while (!tokenizer->isEol()) {
743 String8 token = tokenizer->nextToken(" ");
744 if (token.isEmpty()) {
745 tokenizer->skipDelimiters(" ");
746 continue;
747 }
748 ok &= setCategoryEnable(token.string(), true);
749 }
750 delete tokenizer;
751 return ok;
752}
753
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700754// Set all the kernel tracing settings to the desired state for this trace
755// capture.
756static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800757{
758 bool ok = true;
759
760 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900761 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800762 ok &= setTraceOverwriteEnable(g_traceOverwrite);
763 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
764 ok &= setGlobalClockEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700765 ok &= setPrintTgidEnableIfPresent(true);
766 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800767
768 // Set up the tags property.
769 uint64_t tags = 0;
770 for (int i = 0; i < NELEM(k_categories); i++) {
771 if (g_categoryEnables[i]) {
772 const TracingCategory &c = k_categories[i];
773 tags |= c.tags;
774 }
775 }
776 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700777
778 bool coreServicesTagEnabled = false;
779 for (int i = 0; i < NELEM(k_categories); i++) {
780 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
781 coreServicesTagEnabled = g_categoryEnables[i];
782 }
783 }
784
785 std::string packageList(g_debugAppCmdLine);
786 if (coreServicesTagEnabled) {
787 char value[PROPERTY_VALUE_MAX];
788 property_get(k_coreServicesProp, value, "");
789 if (!packageList.empty()) {
790 packageList += ",";
791 }
792 packageList += value;
793 }
Dan Austin497951c2016-05-31 13:27:03 -0700794 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700795 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100796 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800797
798 // Disable all the sysfs enables. This is done as a separate loop from
799 // the enables to allow the same enable to exist in multiple categories.
800 ok &= disableKernelTraceEvents();
801
802 // Enable all the sysfs enables that are in an enabled category.
803 for (int i = 0; i < NELEM(k_categories); i++) {
804 if (g_categoryEnables[i]) {
805 const TracingCategory &c = k_categories[i];
806 for (int j = 0; j < MAX_SYS_FILES; j++) {
807 const char* path = c.sysfiles[j].path;
808 bool required = c.sysfiles[j].required == REQ;
809 if (path != NULL) {
810 if (fileIsWritable(path)) {
811 ok &= setKernelOptionEnable(path, true);
812 } else if (required) {
813 fprintf(stderr, "error writing file %s\n", path);
814 ok = false;
815 }
816 }
817 }
818 }
819 }
820
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800821 return ok;
822}
823
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700824// Reset all the kernel tracing settings to their default state.
825static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800826{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800827 // Disable all tracing that we're able to.
828 disableKernelTraceEvents();
829
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700830 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800831 setTagsProperty(0);
sergeyv4144eff2016-04-28 11:40:04 -0700832 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700833 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800834
835 // Set the options back to their defaults.
836 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700837 setTraceBufferSizeKB(1);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800838 setGlobalClockEnable(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700839 setPrintTgidEnableIfPresent(false);
840 setKernelTraceFuncs(NULL);
841}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800842
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700843
844// Enable tracing in the kernel.
845static bool startTrace()
846{
847 return setTracingEnabled(true);
848}
849
850// Disable tracing in the kernel.
851static void stopTrace()
852{
853 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800854}
855
Martijn Coenend9535872015-11-26 10:00:55 +0100856// Read data from the tracing pipe and forward to stdout
857static void streamTrace()
858{
859 char trace_data[4096];
860 int traceFD = open(k_traceStreamPath, O_RDWR);
861 if (traceFD == -1) {
862 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
863 strerror(errno), errno);
864 return;
865 }
866 while (!g_traceAborted) {
867 ssize_t bytes_read = read(traceFD, trace_data, 4096);
868 if (bytes_read > 0) {
869 write(STDOUT_FILENO, trace_data, bytes_read);
870 fflush(stdout);
871 } else {
872 if (!g_traceAborted) {
873 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
874 bytes_read, errno, strerror(errno));
875 }
876 break;
877 }
878 }
879}
880
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800881// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700882static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800883{
John Reck6c8ac922016-03-28 11:25:30 -0700884 ALOGI("Dumping trace");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800885 int traceFD = open(k_tracePath, O_RDWR);
886 if (traceFD == -1) {
887 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
888 strerror(errno), errno);
889 return;
890 }
891
892 if (g_compress) {
893 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800894 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700895
896 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800897 if (result != Z_OK) {
898 fprintf(stderr, "error initializing zlib: %d\n", result);
899 close(traceFD);
900 return;
901 }
902
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700903 constexpr size_t bufSize = 64*1024;
904 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
905 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
906 if (!in || !out) {
907 fprintf(stderr, "couldn't allocate buffers\n");
908 close(traceFD);
909 return;
910 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800911
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700912 int flush = Z_NO_FLUSH;
913
914 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800915 zs.avail_out = bufSize;
916
917 do {
918
919 if (zs.avail_in == 0) {
920 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700921 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800922 if (result < 0) {
923 fprintf(stderr, "error reading trace: %s (%d)\n",
924 strerror(errno), errno);
925 result = Z_STREAM_END;
926 break;
927 } else if (result == 0) {
928 flush = Z_FINISH;
929 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700930 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800931 zs.avail_in = result;
932 }
933 }
934
935 if (zs.avail_out == 0) {
936 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700937 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800938 if ((size_t)result < bufSize) {
939 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
940 strerror(errno), errno);
941 result = Z_STREAM_END; // skip deflate error message
942 zs.avail_out = bufSize; // skip the final write
943 break;
944 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700945 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800946 zs.avail_out = bufSize;
947 }
948
949 } while ((result = deflate(&zs, flush)) == Z_OK);
950
951 if (result != Z_STREAM_END) {
952 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
953 }
954
955 if (zs.avail_out < bufSize) {
956 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -0700957 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800958 if ((size_t)result < bytes) {
959 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
960 strerror(errno), errno);
961 }
962 }
963
964 result = deflateEnd(&zs);
965 if (result != Z_OK) {
966 fprintf(stderr, "error cleaning up zlib: %d\n", result);
967 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800968 } else {
969 ssize_t sent = 0;
John Reck40b26b42016-03-30 09:44:36 -0700970 while ((sent = sendfile(outFd, traceFD, NULL, 64*1024*1024)) > 0);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800971 if (sent == -1) {
972 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
973 errno);
974 }
975 }
976
977 close(traceFD);
978}
979
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700980static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800981{
982 if (!g_nohup) {
983 g_traceAborted = true;
984 }
985}
986
987static void registerSigHandler()
988{
989 struct sigaction sa;
990 sigemptyset(&sa.sa_mask);
991 sa.sa_flags = 0;
992 sa.sa_handler = handleSignal;
993 sigaction(SIGHUP, &sa, NULL);
994 sigaction(SIGINT, &sa, NULL);
995 sigaction(SIGQUIT, &sa, NULL);
996 sigaction(SIGTERM, &sa, NULL);
997}
998
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800999static void listSupportedCategories()
1000{
1001 for (int i = 0; i < NELEM(k_categories); i++) {
1002 const TracingCategory& c = k_categories[i];
1003 if (isCategorySupported(c)) {
1004 printf(" %10s - %s\n", c.name, c.longname);
1005 }
1006 }
1007}
1008
1009// Print the command usage help to stderr.
1010static void showHelp(const char *cmd)
1011{
1012 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1013 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001014 " -a appname enable app-level tracing for a comma "
1015 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001016 " -b N use a trace buffer size of N KB\n"
1017 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001018 " -f filename use the categories written in a file as space-separated\n"
1019 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001020 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001021 " -n ignore signals\n"
1022 " -s N sleep for N seconds before tracing [default 0]\n"
Elliott Hughesf884a062016-07-22 09:38:44 -07001023 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001024 " -z compress the trace dump\n"
1025 " --async_start start circular trace and return immediatly\n"
1026 " --async_dump dump the current contents of circular trace buffer\n"
1027 " --async_stop stop tracing and dump the current contents of circular\n"
1028 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001029 " --stream stream trace to stdout as it enters the trace buffer\n"
1030 " Note: this can take significant CPU time, and is best\n"
1031 " used for measuring things that are not affected by\n"
1032 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001033 " --list_categories\n"
1034 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001035 " -o filename write the trace to the specified file instead\n"
1036 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001037 );
1038}
1039
1040int main(int argc, char **argv)
1041{
1042 bool async = false;
1043 bool traceStart = true;
1044 bool traceStop = true;
1045 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001046 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001047
1048 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1049 showHelp(argv[0]);
1050 exit(0);
1051 }
1052
1053 for (;;) {
1054 int ret;
1055 int option_index = 0;
1056 static struct option long_options[] = {
1057 {"async_start", no_argument, 0, 0 },
1058 {"async_stop", no_argument, 0, 0 },
1059 {"async_dump", no_argument, 0, 0 },
1060 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +01001061 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001062 { 0, 0, 0, 0 }
1063 };
1064
John Reck40b26b42016-03-30 09:44:36 -07001065 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001066 long_options, &option_index);
1067
1068 if (ret < 0) {
1069 for (int i = optind; i < argc; i++) {
1070 if (!setCategoryEnable(argv[i], true)) {
1071 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1072 exit(1);
1073 }
1074 }
1075 break;
1076 }
1077
1078 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001079 case 'a':
1080 g_debugAppCmdLine = optarg;
1081 break;
1082
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001083 case 'b':
1084 g_traceBufferSizeKB = atoi(optarg);
1085 break;
1086
1087 case 'c':
1088 g_traceOverwrite = true;
1089 break;
1090
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001091 case 'f':
1092 g_categoriesFile = optarg;
1093 break;
1094
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001095 case 'k':
1096 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001097 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001098
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001099 case 'n':
1100 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001101 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001102
1103 case 's':
1104 g_initialSleepSecs = atoi(optarg);
1105 break;
1106
1107 case 't':
1108 g_traceDurationSeconds = atoi(optarg);
1109 break;
1110
1111 case 'z':
1112 g_compress = true;
1113 break;
1114
John Reck40b26b42016-03-30 09:44:36 -07001115 case 'o':
1116 g_outputFile = optarg;
1117 break;
1118
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001119 case 0:
1120 if (!strcmp(long_options[option_index].name, "async_start")) {
1121 async = true;
1122 traceStop = false;
1123 traceDump = false;
1124 g_traceOverwrite = true;
1125 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1126 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001127 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001128 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1129 async = true;
1130 traceStart = false;
1131 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001132 } else if (!strcmp(long_options[option_index].name, "stream")) {
1133 traceStream = true;
1134 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001135 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1136 listSupportedCategories();
1137 exit(0);
1138 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001139 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001140
1141 default:
1142 fprintf(stderr, "\n");
1143 showHelp(argv[0]);
1144 exit(-1);
1145 break;
1146 }
1147 }
1148
1149 registerSigHandler();
1150
1151 if (g_initialSleepSecs > 0) {
1152 sleep(g_initialSleepSecs);
1153 }
1154
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001155 bool ok = true;
1156 ok &= setUpTrace();
1157 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001158
1159 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001160 if (!traceStream) {
1161 printf("capturing trace...");
1162 fflush(stdout);
1163 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001164
1165 // We clear the trace after starting it because tracing gets enabled for
1166 // each CPU individually in the kernel. Having the beginning of the trace
1167 // contain entries from only one CPU can cause "begin" entries without a
1168 // matching "end" entry to show up if a task gets migrated from one CPU to
1169 // another.
1170 ok = clearTrace();
1171
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001172 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001173 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001174 // Sleep to allow the trace to be captured.
1175 struct timespec timeLeft;
1176 timeLeft.tv_sec = g_traceDurationSeconds;
1177 timeLeft.tv_nsec = 0;
1178 do {
1179 if (g_traceAborted) {
1180 break;
1181 }
1182 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1183 }
Martijn Coenend9535872015-11-26 10:00:55 +01001184
1185 if (traceStream) {
1186 streamTrace();
1187 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001188 }
1189
1190 // Stop the trace and restore the default settings.
1191 if (traceStop)
1192 stopTrace();
1193
1194 if (ok && traceDump) {
1195 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001196 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001197 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001198 int outFd = STDOUT_FILENO;
1199 if (g_outputFile) {
1200 outFd = open(g_outputFile, O_WRONLY | O_CREAT);
1201 }
1202 if (outFd == -1) {
1203 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1204 } else {
1205 dprintf(outFd, "TRACE:\n");
1206 dumpTrace(outFd);
1207 if (g_outputFile) {
1208 close(outFd);
1209 }
1210 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001211 } else {
1212 printf("\ntrace aborted.\n");
1213 fflush(stdout);
1214 }
1215 clearTrace();
1216 } else if (!ok) {
1217 fprintf(stderr, "unable to start tracing\n");
1218 }
1219
1220 // Reset the trace buffer size to 1.
1221 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001222 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001223
1224 return g_traceAborted ? 1 : 0;
1225}