blob: 3fcf5aa9dfdcc4c40da5fb90e780ac175f8401ae [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 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100123 { "i2c", "I2C Events", 0, {
124 { REQ, "/sys/kernel/debug/tracing/events/i2c/enable" },
125 { REQ, "/sys/kernel/debug/tracing/events/i2c/i2c_read/enable" },
126 { REQ, "/sys/kernel/debug/tracing/events/i2c/i2c_write/enable" },
127 { REQ, "/sys/kernel/debug/tracing/events/i2c/i2c_result/enable" },
128 { REQ, "/sys/kernel/debug/tracing/events/i2c/i2c_reply/enable" },
129 { OPT, "/sys/kernel/debug/tracing/events/i2c/smbus_read/enable" },
130 { OPT, "/sys/kernel/debug/tracing/events/i2c/smbus_write/enable" },
131 { OPT, "/sys/kernel/debug/tracing/events/i2c/smbus_result/enable" },
132 { OPT, "/sys/kernel/debug/tracing/events/i2c/smbus_reply/enable" },
133 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700134 { "freq", "CPU Frequency", 0, {
135 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_frequency/enable" },
136 { OPT, "/sys/kernel/debug/tracing/events/power/clock_set_rate/enable" },
Ruchi Kandoiffcc7112015-11-19 18:32:00 -0800137 { OPT, "/sys/kernel/debug/tracing/events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800138 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700139 { "membus", "Memory Bus Utilization", 0, {
140 { REQ, "/sys/kernel/debug/tracing/events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800141 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700142 { "idle", "CPU Idle", 0, {
143 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800144 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700145 { "disk", "Disk I/O", 0, {
Greg Hackmanne80d32c2014-11-20 12:59:44 -0800146 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_enter/enable" },
147 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_exit/enable" },
148 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_begin/enable" },
149 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_end/enable" },
150 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_begin/enable" },
151 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_end/enable" },
152 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable" },
153 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable" },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700154 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" },
155 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800156 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700157 { "mmc", "eMMC commands", 0, {
158 { REQ, "/sys/kernel/debug/tracing/events/mmc/enable" },
159 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700160 { "load", "CPU Load", 0, {
161 { REQ, "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800162 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700163 { "sync", "Synchronization", 0, {
164 { REQ, "/sys/kernel/debug/tracing/events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800165 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700166 { "workq", "Kernel Workqueues", 0, {
167 { REQ, "/sys/kernel/debug/tracing/events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800168 } },
Colin Cross580407f2014-08-18 15:22:13 -0700169 { "memreclaim", "Kernel Memory Reclaim", 0, {
170 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
171 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
172 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_wake/enable" },
173 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_sleep/enable" },
174 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800175 { "regulators", "Voltage and Current Regulators", 0, {
176 { REQ, "/sys/kernel/debug/tracing/events/regulator/enable" },
177 } },
Scott Bauerae473362015-06-08 16:32:36 -0700178 { "binder_driver", "Binder Kernel driver", 0, {
179 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction/enable" },
180 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction_received/enable" },
181 } },
182 { "binder_lock", "Binder global lock trace", 0, {
183 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_lock/enable" },
184 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_locked/enable" },
185 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_unlock/enable" },
186 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200187 { "pagecache", "Page cache", 0, {
188 { REQ, "/sys/kernel/debug/tracing/events/filemap/enable" },
189 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800190};
191
192/* Command line options */
193static int g_traceDurationSeconds = 5;
194static bool g_traceOverwrite = false;
195static int g_traceBufferSizeKB = 2048;
196static bool g_compress = false;
197static bool g_nohup = false;
198static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900199static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700200static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700201static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700202static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800203
204/* Global state */
205static bool g_traceAborted = false;
206static bool g_categoryEnables[NELEM(k_categories)] = {};
207
208/* Sys file paths */
209static const char* k_traceClockPath =
210 "/sys/kernel/debug/tracing/trace_clock";
211
212static const char* k_traceBufferSizePath =
213 "/sys/kernel/debug/tracing/buffer_size_kb";
214
215static const char* k_tracingOverwriteEnablePath =
216 "/sys/kernel/debug/tracing/options/overwrite";
217
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700218static const char* k_currentTracerPath =
219 "/sys/kernel/debug/tracing/current_tracer";
220
221static const char* k_printTgidPath =
222 "/sys/kernel/debug/tracing/options/print-tgid";
223
224static const char* k_funcgraphAbsTimePath =
225 "/sys/kernel/debug/tracing/options/funcgraph-abstime";
226
227static const char* k_funcgraphCpuPath =
228 "/sys/kernel/debug/tracing/options/funcgraph-cpu";
229
230static const char* k_funcgraphProcPath =
231 "/sys/kernel/debug/tracing/options/funcgraph-proc";
232
233static const char* k_funcgraphFlatPath =
234 "/sys/kernel/debug/tracing/options/funcgraph-flat";
235
236static const char* k_funcgraphDurationPath =
237 "/sys/kernel/debug/tracing/options/funcgraph-duration";
238
239static const char* k_ftraceFilterPath =
240 "/sys/kernel/debug/tracing/set_ftrace_filter";
241
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800242static const char* k_tracingOnPath =
243 "/sys/kernel/debug/tracing/tracing_on";
244
245static const char* k_tracePath =
246 "/sys/kernel/debug/tracing/trace";
247
Martijn Coenend9535872015-11-26 10:00:55 +0100248static const char* k_traceStreamPath =
249 "/sys/kernel/debug/tracing/trace_pipe";
250
John Reck469a1942015-03-26 15:31:35 -0700251static const char* k_traceMarkerPath =
252 "/sys/kernel/debug/tracing/trace_marker";
253
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800254// Check whether a file exists.
255static bool fileExists(const char* filename) {
256 return access(filename, F_OK) != -1;
257}
258
259// Check whether a file is writable.
260static bool fileIsWritable(const char* filename) {
261 return access(filename, W_OK) != -1;
262}
263
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700264// Truncate a file.
265static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800266{
Jamie Gennis43122e72013-03-21 14:06:31 -0700267 // This uses creat rather than truncate because some of the debug kernel
268 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
269 // calls to truncate, but they are cleared by calls to creat.
270 int traceFD = creat(path, 0);
271 if (traceFD == -1) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700272 fprintf(stderr, "error truncating %s: %s (%d)\n", path,
Jamie Gennis43122e72013-03-21 14:06:31 -0700273 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700274 return false;
275 }
276
Jamie Gennis43122e72013-03-21 14:06:31 -0700277 close(traceFD);
278
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700279 return true;
280}
281
282static bool _writeStr(const char* filename, const char* str, int flags)
283{
284 int fd = open(filename, flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800285 if (fd == -1) {
286 fprintf(stderr, "error opening %s: %s (%d)\n", filename,
287 strerror(errno), errno);
288 return false;
289 }
290
291 bool ok = true;
292 ssize_t len = strlen(str);
293 if (write(fd, str, len) != len) {
294 fprintf(stderr, "error writing to %s: %s (%d)\n", filename,
295 strerror(errno), errno);
296 ok = false;
297 }
298
299 close(fd);
300
301 return ok;
302}
303
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700304// Write a string to a file, returning true if the write was successful.
305static bool writeStr(const char* filename, const char* str)
306{
307 return _writeStr(filename, str, O_WRONLY);
308}
309
310// Append a string to a file, returning true if the write was successful.
311static bool appendStr(const char* filename, const char* str)
312{
313 return _writeStr(filename, str, O_APPEND|O_WRONLY);
314}
315
John Reck469a1942015-03-26 15:31:35 -0700316static void writeClockSyncMarker()
317{
318 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200319 int len = 0;
320 int fd = open(k_traceMarkerPath, O_WRONLY);
321 if (fd == -1) {
322 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
323 strerror(errno), errno);
324 return;
325 }
John Reck469a1942015-03-26 15:31:35 -0700326 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200327
328 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
329 if (write(fd, buffer, len) != len) {
330 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
331 }
332
333 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
334 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
335 if (write(fd, buffer, len) != len) {
336 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
337 }
338
339 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700340}
341
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800342// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
343// file.
344static bool setKernelOptionEnable(const char* filename, bool enable)
345{
346 return writeStr(filename, enable ? "1" : "0");
347}
348
349// Check whether the category is supported on the device with the current
350// rootness. A category is supported only if all its required /sys/ files are
351// writable and if enabling the category will enable one or more tracing tags
352// or /sys/ files.
353static bool isCategorySupported(const TracingCategory& category)
354{
sergeyvdb404152016-05-02 19:26:07 -0700355 if (strcmp(category.name, k_coreServiceCategory) == 0) {
356 char value[PROPERTY_VALUE_MAX];
357 property_get(k_coreServicesProp, value, "");
358 return strlen(value) != 0;
359 }
360
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800361 bool ok = category.tags != 0;
362 for (int i = 0; i < MAX_SYS_FILES; i++) {
363 const char* path = category.sysfiles[i].path;
364 bool req = category.sysfiles[i].required == REQ;
365 if (path != NULL) {
366 if (req) {
367 if (!fileIsWritable(path)) {
368 return false;
369 } else {
370 ok = true;
371 }
372 } else {
373 ok |= fileIsWritable(path);
374 }
375 }
376 }
377 return ok;
378}
379
380// Check whether the category would be supported on the device if the user
381// were root. This function assumes that root is able to write to any file
382// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700383// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800384static bool isCategorySupportedForRoot(const TracingCategory& category)
385{
386 bool ok = category.tags != 0;
387 for (int i = 0; i < MAX_SYS_FILES; i++) {
388 const char* path = category.sysfiles[i].path;
389 bool req = category.sysfiles[i].required == REQ;
390 if (path != NULL) {
391 if (req) {
392 if (!fileExists(path)) {
393 return false;
394 } else {
395 ok = true;
396 }
397 } else {
398 ok |= fileExists(path);
399 }
400 }
401 }
402 return ok;
403}
404
405// Enable or disable overwriting of the kernel trace buffers. Disabling this
406// will cause tracing to stop once the trace buffers have filled up.
407static bool setTraceOverwriteEnable(bool enable)
408{
409 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
410}
411
412// Enable or disable kernel tracing.
413static bool setTracingEnabled(bool enable)
414{
415 return setKernelOptionEnable(k_tracingOnPath, enable);
416}
417
418// Clear the contents of the kernel trace.
419static bool clearTrace()
420{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700421 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800422}
423
424// Set the size of the kernel's trace buffer in kilobytes.
425static bool setTraceBufferSizeKB(int size)
426{
427 char str[32] = "1";
428 int len;
429 if (size < 1) {
430 size = 1;
431 }
432 snprintf(str, 32, "%d", size);
433 return writeStr(k_traceBufferSizePath, str);
434}
435
Colin Crossb1ce49b2014-08-20 14:28:47 -0700436// Read the trace_clock sysfs file and return true if it matches the requested
437// value. The trace_clock file format is:
438// local [global] counter uptime perf
439static bool isTraceClock(const char *mode)
440{
441 int fd = open(k_traceClockPath, O_RDONLY);
442 if (fd == -1) {
443 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceClockPath,
444 strerror(errno), errno);
445 return false;
446 }
447
448 char buf[4097];
449 ssize_t n = read(fd, buf, 4096);
450 close(fd);
451 if (n == -1) {
452 fprintf(stderr, "error reading %s: %s (%d)\n", k_traceClockPath,
453 strerror(errno), errno);
454 return false;
455 }
456 buf[n] = '\0';
457
458 char *start = strchr(buf, '[');
459 if (start == NULL) {
460 return false;
461 }
462 start++;
463
464 char *end = strchr(start, ']');
465 if (end == NULL) {
466 return false;
467 }
468 *end = '\0';
469
470 return strcmp(mode, start) == 0;
471}
472
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800473// Enable or disable the kernel's use of the global clock. Disabling the global
474// clock will result in the kernel using a per-CPU local clock.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700475// Any write to the trace_clock sysfs file will reset the buffer, so only
476// update it if the requested value is not the current value.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800477static bool setGlobalClockEnable(bool enable)
478{
Colin Crossb1ce49b2014-08-20 14:28:47 -0700479 const char *clock = enable ? "global" : "local";
480
481 if (isTraceClock(clock)) {
482 return true;
483 }
484
485 return writeStr(k_traceClockPath, clock);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800486}
487
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700488static bool setPrintTgidEnableIfPresent(bool enable)
489{
490 if (fileExists(k_printTgidPath)) {
491 return setKernelOptionEnable(k_printTgidPath, enable);
492 }
493 return true;
494}
495
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800496// Poke all the binder-enabled processes in the system to get them to re-read
497// their system properties.
498static bool pokeBinderServices()
499{
500 sp<IServiceManager> sm = defaultServiceManager();
501 Vector<String16> services = sm->listServices();
502 for (size_t i = 0; i < services.size(); i++) {
503 sp<IBinder> obj = sm->checkService(services[i]);
504 if (obj != NULL) {
505 Parcel data;
506 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
507 NULL, 0) != OK) {
508 if (false) {
509 // XXX: For some reason this fails on tablets trying to
510 // poke the "phone" service. It's not clear whether some
511 // are expected to fail.
512 String8 svc(services[i]);
513 fprintf(stderr, "error poking binder service %s\n",
514 svc.string());
515 return false;
516 }
517 }
518 }
519 }
520 return true;
521}
522
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100523// Poke all the HAL processes in the system to get them to re-read
524// their system properties.
525static void pokeHalServices()
526{
527 using ::android::hidl::manager::V1_0::IServiceManager;
528 using ::android::hardware::IBinder;
529 using ::android::hardware::hidl_string;
530 using ::android::hardware::Parcel;
531
532 Parcel data;
533
534 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800535 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100536 for (size_t i = 0; i < interfaces.size(); i++) {
537 string fqInstanceName = interfaces[i];
538 string::size_type n = fqInstanceName.find("/");
539 if (n == std::string::npos || interfaces[i].size() == n+1)
540 continue;
541 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
542 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800543 auto getRet = sm->get(fqInterfaceName, instanceName, [&](const auto &interface) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100544 // TODO(b/32756130)
545 // Once IServiceManager returns IBase, use interface->notifySyspropsChanged() here
546 interface->transact(IBinder::SYSPROPS_TRANSACTION, data, nullptr, 0, nullptr);
547 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800548 if (!getRet.isOk()) {
549 fprintf(stderr, "failed to get service %s: %s\n",
550 fqInstanceName.c_str(),
551 getRet.getStatus().toString8().string());
552 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100553 }
554 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800555 if (!listRet.isOk()) {
556 fprintf(stderr, "failed to list services: %s\n", listRet.getStatus().toString8().string());
557 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100558}
559
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800560// Set the trace tags that userland tracing uses, and poke the running
561// processes to pick up the new value.
562static bool setTagsProperty(uint64_t tags)
563{
sergeyv4144eff2016-04-28 11:40:04 -0700564 char buf[PROPERTY_VALUE_MAX];
565 snprintf(buf, sizeof(buf), "%#" PRIx64, tags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800566 if (property_set(k_traceTagsProperty, buf) < 0) {
567 fprintf(stderr, "error setting trace tags system property\n");
568 return false;
569 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700570 return true;
571}
572
sergeyv4144eff2016-04-28 11:40:04 -0700573static void clearAppProperties()
574{
575 char buf[PROPERTY_KEY_MAX];
576 for (int i = 0; i < MAX_PACKAGES; i++) {
577 snprintf(buf, sizeof(buf), k_traceAppsPropertyTemplate, i);
578 if (property_set(buf, "") < 0) {
579 fprintf(stderr, "failed to clear system property: %s\n", buf);
580 }
581 }
582 if (property_set(k_traceAppsNumberProperty, "") < 0) {
583 fprintf(stderr, "failed to clear system property: %s",
584 k_traceAppsNumberProperty);
585 }
586}
587
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700588// Set the system property that indicates which apps should perform
589// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700590static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700591{
sergeyv4144eff2016-04-28 11:40:04 -0700592 char buf[PROPERTY_KEY_MAX];
593 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700594 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700595 while (start != NULL) {
596 if (i == MAX_PACKAGES) {
597 fprintf(stderr, "error: only 16 packages could be traced at once\n");
598 clearAppProperties();
599 return false;
600 }
601 char* end = strchr(start, ',');
602 if (end != NULL) {
603 *end = '\0';
604 end++;
605 }
606 snprintf(buf, sizeof(buf), k_traceAppsPropertyTemplate, i);
607 if (property_set(buf, start) < 0) {
608 fprintf(stderr, "error setting trace app %d property to %s\n", i, buf);
609 clearAppProperties();
610 return false;
611 }
612 start = end;
613 i++;
614 }
615
616 snprintf(buf, sizeof(buf), "%d", i);
617 if (property_set(k_traceAppsNumberProperty, buf) < 0) {
618 fprintf(stderr, "error setting trace app number property to %s\n", buf);
619 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700620 return false;
621 }
622 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800623}
624
625// Disable all /sys/ enable files.
626static bool disableKernelTraceEvents() {
627 bool ok = true;
628 for (int i = 0; i < NELEM(k_categories); i++) {
629 const TracingCategory &c = k_categories[i];
630 for (int j = 0; j < MAX_SYS_FILES; j++) {
631 const char* path = c.sysfiles[j].path;
632 if (path != NULL && fileIsWritable(path)) {
633 ok &= setKernelOptionEnable(path, false);
634 }
635 }
636 }
637 return ok;
638}
639
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700640// Verify that the comma separated list of functions are being traced by the
641// kernel.
642static bool verifyKernelTraceFuncs(const char* funcs)
643{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100644 std::string buf;
645 if (!android::base::ReadFileToString(k_ftraceFilterPath, &buf)) {
646 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700647 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100648 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700649 }
650
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100651 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700652
653 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100654 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700655 bool ok = true;
656 char* myFuncs = strdup(funcs);
657 char* func = strtok(myFuncs, ",");
658 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100659 if (!strchr(func, '*')) {
660 String8 fancyFunc = String8::format("\n%s\n", func);
661 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
662 if (!found || func[0] == '\0') {
663 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
664 "to trace.\n", func);
665 ok = false;
666 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700667 }
668 func = strtok(NULL, ",");
669 }
670 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700671 return ok;
672}
673
674// Set the comma separated list of functions that the kernel is to trace.
675static bool setKernelTraceFuncs(const char* funcs)
676{
677 bool ok = true;
678
679 if (funcs == NULL || funcs[0] == '\0') {
680 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700681 if (fileIsWritable(k_currentTracerPath)) {
682 ok &= writeStr(k_currentTracerPath, "nop");
683 }
684 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700685 ok &= truncateFile(k_ftraceFilterPath);
686 }
687 } else {
688 // Enable kernel function tracing.
689 ok &= writeStr(k_currentTracerPath, "function_graph");
690 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
691 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
692 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
693 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
694
695 // Set the requested filter functions.
696 ok &= truncateFile(k_ftraceFilterPath);
697 char* myFuncs = strdup(funcs);
698 char* func = strtok(myFuncs, ",");
699 while (func) {
700 ok &= appendStr(k_ftraceFilterPath, func);
701 func = strtok(NULL, ",");
702 }
703 free(myFuncs);
704
705 // Verify that the set functions are being traced.
706 if (ok) {
707 ok &= verifyKernelTraceFuncs(funcs);
708 }
709 }
710
711 return ok;
712}
713
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900714static bool setCategoryEnable(const char* name, bool enable)
715{
716 for (int i = 0; i < NELEM(k_categories); i++) {
717 const TracingCategory& c = k_categories[i];
718 if (strcmp(name, c.name) == 0) {
719 if (isCategorySupported(c)) {
720 g_categoryEnables[i] = enable;
721 return true;
722 } else {
723 if (isCategorySupportedForRoot(c)) {
724 fprintf(stderr, "error: category \"%s\" requires root "
725 "privileges.\n", name);
726 } else {
727 fprintf(stderr, "error: category \"%s\" is not supported "
728 "on this device.\n", name);
729 }
730 return false;
731 }
732 }
733 }
734 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
735 return false;
736}
737
738static bool setCategoriesEnableFromFile(const char* categories_file)
739{
740 if (!categories_file) {
741 return true;
742 }
743 Tokenizer* tokenizer = NULL;
744 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
745 return false;
746 }
747 bool ok = true;
748 while (!tokenizer->isEol()) {
749 String8 token = tokenizer->nextToken(" ");
750 if (token.isEmpty()) {
751 tokenizer->skipDelimiters(" ");
752 continue;
753 }
754 ok &= setCategoryEnable(token.string(), true);
755 }
756 delete tokenizer;
757 return ok;
758}
759
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700760// Set all the kernel tracing settings to the desired state for this trace
761// capture.
762static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800763{
764 bool ok = true;
765
766 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900767 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800768 ok &= setTraceOverwriteEnable(g_traceOverwrite);
769 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
770 ok &= setGlobalClockEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700771 ok &= setPrintTgidEnableIfPresent(true);
772 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800773
774 // Set up the tags property.
775 uint64_t tags = 0;
776 for (int i = 0; i < NELEM(k_categories); i++) {
777 if (g_categoryEnables[i]) {
778 const TracingCategory &c = k_categories[i];
779 tags |= c.tags;
780 }
781 }
782 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700783
784 bool coreServicesTagEnabled = false;
785 for (int i = 0; i < NELEM(k_categories); i++) {
786 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
787 coreServicesTagEnabled = g_categoryEnables[i];
788 }
789 }
790
791 std::string packageList(g_debugAppCmdLine);
792 if (coreServicesTagEnabled) {
793 char value[PROPERTY_VALUE_MAX];
794 property_get(k_coreServicesProp, value, "");
795 if (!packageList.empty()) {
796 packageList += ",";
797 }
798 packageList += value;
799 }
Dan Austin09a79872016-05-31 13:27:03 -0700800 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700801 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100802 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800803
804 // Disable all the sysfs enables. This is done as a separate loop from
805 // the enables to allow the same enable to exist in multiple categories.
806 ok &= disableKernelTraceEvents();
807
808 // Enable all the sysfs enables that are in an enabled category.
809 for (int i = 0; i < NELEM(k_categories); i++) {
810 if (g_categoryEnables[i]) {
811 const TracingCategory &c = k_categories[i];
812 for (int j = 0; j < MAX_SYS_FILES; j++) {
813 const char* path = c.sysfiles[j].path;
814 bool required = c.sysfiles[j].required == REQ;
815 if (path != NULL) {
816 if (fileIsWritable(path)) {
817 ok &= setKernelOptionEnable(path, true);
818 } else if (required) {
819 fprintf(stderr, "error writing file %s\n", path);
820 ok = false;
821 }
822 }
823 }
824 }
825 }
826
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800827 return ok;
828}
829
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700830// Reset all the kernel tracing settings to their default state.
831static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800832{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800833 // Disable all tracing that we're able to.
834 disableKernelTraceEvents();
835
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700836 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800837 setTagsProperty(0);
sergeyv4144eff2016-04-28 11:40:04 -0700838 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700839 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800840
841 // Set the options back to their defaults.
842 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700843 setTraceBufferSizeKB(1);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800844 setGlobalClockEnable(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700845 setPrintTgidEnableIfPresent(false);
846 setKernelTraceFuncs(NULL);
847}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800848
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700849
850// Enable tracing in the kernel.
851static bool startTrace()
852{
853 return setTracingEnabled(true);
854}
855
856// Disable tracing in the kernel.
857static void stopTrace()
858{
859 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800860}
861
Martijn Coenend9535872015-11-26 10:00:55 +0100862// Read data from the tracing pipe and forward to stdout
863static void streamTrace()
864{
865 char trace_data[4096];
866 int traceFD = open(k_traceStreamPath, O_RDWR);
867 if (traceFD == -1) {
868 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
869 strerror(errno), errno);
870 return;
871 }
872 while (!g_traceAborted) {
873 ssize_t bytes_read = read(traceFD, trace_data, 4096);
874 if (bytes_read > 0) {
875 write(STDOUT_FILENO, trace_data, bytes_read);
876 fflush(stdout);
877 } else {
878 if (!g_traceAborted) {
879 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
880 bytes_read, errno, strerror(errno));
881 }
882 break;
883 }
884 }
885}
886
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800887// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700888static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800889{
John Reck6c8ac922016-03-28 11:25:30 -0700890 ALOGI("Dumping trace");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800891 int traceFD = open(k_tracePath, O_RDWR);
892 if (traceFD == -1) {
893 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
894 strerror(errno), errno);
895 return;
896 }
897
898 if (g_compress) {
899 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800900 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700901
902 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800903 if (result != Z_OK) {
904 fprintf(stderr, "error initializing zlib: %d\n", result);
905 close(traceFD);
906 return;
907 }
908
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700909 constexpr size_t bufSize = 64*1024;
910 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
911 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
912 if (!in || !out) {
913 fprintf(stderr, "couldn't allocate buffers\n");
914 close(traceFD);
915 return;
916 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800917
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700918 int flush = Z_NO_FLUSH;
919
920 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800921 zs.avail_out = bufSize;
922
923 do {
924
925 if (zs.avail_in == 0) {
926 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700927 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800928 if (result < 0) {
929 fprintf(stderr, "error reading trace: %s (%d)\n",
930 strerror(errno), errno);
931 result = Z_STREAM_END;
932 break;
933 } else if (result == 0) {
934 flush = Z_FINISH;
935 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700936 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800937 zs.avail_in = result;
938 }
939 }
940
941 if (zs.avail_out == 0) {
942 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700943 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800944 if ((size_t)result < bufSize) {
945 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
946 strerror(errno), errno);
947 result = Z_STREAM_END; // skip deflate error message
948 zs.avail_out = bufSize; // skip the final write
949 break;
950 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700951 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800952 zs.avail_out = bufSize;
953 }
954
955 } while ((result = deflate(&zs, flush)) == Z_OK);
956
957 if (result != Z_STREAM_END) {
958 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
959 }
960
961 if (zs.avail_out < bufSize) {
962 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -0700963 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800964 if ((size_t)result < bytes) {
965 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
966 strerror(errno), errno);
967 }
968 }
969
970 result = deflateEnd(&zs);
971 if (result != Z_OK) {
972 fprintf(stderr, "error cleaning up zlib: %d\n", result);
973 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800974 } else {
975 ssize_t sent = 0;
John Reck40b26b42016-03-30 09:44:36 -0700976 while ((sent = sendfile(outFd, traceFD, NULL, 64*1024*1024)) > 0);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800977 if (sent == -1) {
978 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
979 errno);
980 }
981 }
982
983 close(traceFD);
984}
985
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700986static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800987{
988 if (!g_nohup) {
989 g_traceAborted = true;
990 }
991}
992
993static void registerSigHandler()
994{
995 struct sigaction sa;
996 sigemptyset(&sa.sa_mask);
997 sa.sa_flags = 0;
998 sa.sa_handler = handleSignal;
999 sigaction(SIGHUP, &sa, NULL);
1000 sigaction(SIGINT, &sa, NULL);
1001 sigaction(SIGQUIT, &sa, NULL);
1002 sigaction(SIGTERM, &sa, NULL);
1003}
1004
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001005static void listSupportedCategories()
1006{
1007 for (int i = 0; i < NELEM(k_categories); i++) {
1008 const TracingCategory& c = k_categories[i];
1009 if (isCategorySupported(c)) {
1010 printf(" %10s - %s\n", c.name, c.longname);
1011 }
1012 }
1013}
1014
1015// Print the command usage help to stderr.
1016static void showHelp(const char *cmd)
1017{
1018 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1019 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001020 " -a appname enable app-level tracing for a comma "
1021 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001022 " -b N use a trace buffer size of N KB\n"
1023 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001024 " -f filename use the categories written in a file as space-separated\n"
1025 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001026 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001027 " -n ignore signals\n"
1028 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001029 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001030 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001031 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001032 " --async_dump dump the current contents of circular trace buffer\n"
1033 " --async_stop stop tracing and dump the current contents of circular\n"
1034 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001035 " --stream stream trace to stdout as it enters the trace buffer\n"
1036 " Note: this can take significant CPU time, and is best\n"
1037 " used for measuring things that are not affected by\n"
1038 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001039 " --list_categories\n"
1040 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001041 " -o filename write the trace to the specified file instead\n"
1042 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001043 );
1044}
1045
1046int main(int argc, char **argv)
1047{
1048 bool async = false;
1049 bool traceStart = true;
1050 bool traceStop = true;
1051 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001052 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001053
1054 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1055 showHelp(argv[0]);
1056 exit(0);
1057 }
1058
1059 for (;;) {
1060 int ret;
1061 int option_index = 0;
1062 static struct option long_options[] = {
1063 {"async_start", no_argument, 0, 0 },
1064 {"async_stop", no_argument, 0, 0 },
1065 {"async_dump", no_argument, 0, 0 },
1066 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +01001067 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001068 { 0, 0, 0, 0 }
1069 };
1070
John Reck40b26b42016-03-30 09:44:36 -07001071 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001072 long_options, &option_index);
1073
1074 if (ret < 0) {
1075 for (int i = optind; i < argc; i++) {
1076 if (!setCategoryEnable(argv[i], true)) {
1077 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1078 exit(1);
1079 }
1080 }
1081 break;
1082 }
1083
1084 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001085 case 'a':
1086 g_debugAppCmdLine = optarg;
1087 break;
1088
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001089 case 'b':
1090 g_traceBufferSizeKB = atoi(optarg);
1091 break;
1092
1093 case 'c':
1094 g_traceOverwrite = true;
1095 break;
1096
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001097 case 'f':
1098 g_categoriesFile = optarg;
1099 break;
1100
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001101 case 'k':
1102 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001103 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001104
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001105 case 'n':
1106 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001107 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001108
1109 case 's':
1110 g_initialSleepSecs = atoi(optarg);
1111 break;
1112
1113 case 't':
1114 g_traceDurationSeconds = atoi(optarg);
1115 break;
1116
1117 case 'z':
1118 g_compress = true;
1119 break;
1120
John Reck40b26b42016-03-30 09:44:36 -07001121 case 'o':
1122 g_outputFile = optarg;
1123 break;
1124
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001125 case 0:
1126 if (!strcmp(long_options[option_index].name, "async_start")) {
1127 async = true;
1128 traceStop = false;
1129 traceDump = false;
1130 g_traceOverwrite = true;
1131 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1132 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001133 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001134 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1135 async = true;
1136 traceStart = false;
1137 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001138 } else if (!strcmp(long_options[option_index].name, "stream")) {
1139 traceStream = true;
1140 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001141 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1142 listSupportedCategories();
1143 exit(0);
1144 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001145 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001146
1147 default:
1148 fprintf(stderr, "\n");
1149 showHelp(argv[0]);
1150 exit(-1);
1151 break;
1152 }
1153 }
1154
1155 registerSigHandler();
1156
1157 if (g_initialSleepSecs > 0) {
1158 sleep(g_initialSleepSecs);
1159 }
1160
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001161 bool ok = true;
1162 ok &= setUpTrace();
1163 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001164
1165 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001166 if (!traceStream) {
1167 printf("capturing trace...");
1168 fflush(stdout);
1169 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001170
1171 // We clear the trace after starting it because tracing gets enabled for
1172 // each CPU individually in the kernel. Having the beginning of the trace
1173 // contain entries from only one CPU can cause "begin" entries without a
1174 // matching "end" entry to show up if a task gets migrated from one CPU to
1175 // another.
1176 ok = clearTrace();
1177
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001178 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001179 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001180 // Sleep to allow the trace to be captured.
1181 struct timespec timeLeft;
1182 timeLeft.tv_sec = g_traceDurationSeconds;
1183 timeLeft.tv_nsec = 0;
1184 do {
1185 if (g_traceAborted) {
1186 break;
1187 }
1188 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1189 }
Martijn Coenend9535872015-11-26 10:00:55 +01001190
1191 if (traceStream) {
1192 streamTrace();
1193 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001194 }
1195
1196 // Stop the trace and restore the default settings.
1197 if (traceStop)
1198 stopTrace();
1199
1200 if (ok && traceDump) {
1201 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001202 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001203 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001204 int outFd = STDOUT_FILENO;
1205 if (g_outputFile) {
George Burgess IV48443342016-05-04 19:42:00 -07001206 outFd = open(g_outputFile, O_WRONLY | O_CREAT, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001207 }
1208 if (outFd == -1) {
1209 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1210 } else {
1211 dprintf(outFd, "TRACE:\n");
1212 dumpTrace(outFd);
1213 if (g_outputFile) {
1214 close(outFd);
1215 }
1216 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001217 } else {
1218 printf("\ntrace aborted.\n");
1219 fflush(stdout);
1220 }
1221 clearTrace();
1222 } else if (!ok) {
1223 fprintf(stderr, "unable to start tracing\n");
1224 }
1225
1226 // Reset the trace buffer size to 1.
1227 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001228 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001229
1230 return g_traceAborted ? 1 : 0;
1231}