blob: 320d11dfb1c071c71872e3a1248fefded09d6794 [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, { } },
Josh Gao468b4cb2016-11-29 10:55:21 -0800112 { "adb", "ADB", ATRACE_TAG_ADB, { } },
sergeyvdb404152016-05-02 19:26:07 -0700113 { k_coreServiceCategory, "Core services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700114 { "sched", "CPU Scheduling", 0, {
115 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_switch/enable" },
116 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_wakeup/enable" },
Riley Andrews5672bb72015-11-19 13:31:17 -0800117 { OPT, "/sys/kernel/debug/tracing/events/sched/sched_blocked_reason/enable" },
Ruchi Kandoicfe500d2015-11-23 13:47:20 -0800118 { OPT, "/sys/kernel/debug/tracing/events/sched/sched_cpu_hotplug/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800119 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700120 { "irq", "IRQ Events", 0, {
121 { REQ, "/sys/kernel/debug/tracing/events/irq/enable" },
Riley Andrews412e4f62015-11-02 21:01:34 -0800122 { OPT, "/sys/kernel/debug/tracing/events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700123 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700124 { "freq", "CPU Frequency", 0, {
125 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_frequency/enable" },
126 { OPT, "/sys/kernel/debug/tracing/events/power/clock_set_rate/enable" },
Ruchi Kandoiffcc7112015-11-19 18:32:00 -0800127 { OPT, "/sys/kernel/debug/tracing/events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800128 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700129 { "membus", "Memory Bus Utilization", 0, {
130 { REQ, "/sys/kernel/debug/tracing/events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800131 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700132 { "idle", "CPU Idle", 0, {
133 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800134 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700135 { "disk", "Disk I/O", 0, {
Greg Hackmanne80d32c2014-11-20 12:59:44 -0800136 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_enter/enable" },
137 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_exit/enable" },
138 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_begin/enable" },
139 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_end/enable" },
140 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_begin/enable" },
141 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_end/enable" },
142 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable" },
143 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable" },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700144 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" },
145 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800146 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700147 { "mmc", "eMMC commands", 0, {
148 { REQ, "/sys/kernel/debug/tracing/events/mmc/enable" },
149 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700150 { "load", "CPU Load", 0, {
151 { REQ, "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800152 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700153 { "sync", "Synchronization", 0, {
154 { REQ, "/sys/kernel/debug/tracing/events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800155 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700156 { "workq", "Kernel Workqueues", 0, {
157 { REQ, "/sys/kernel/debug/tracing/events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800158 } },
Colin Cross580407f2014-08-18 15:22:13 -0700159 { "memreclaim", "Kernel Memory Reclaim", 0, {
160 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
161 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
162 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_wake/enable" },
163 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_sleep/enable" },
164 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800165 { "regulators", "Voltage and Current Regulators", 0, {
166 { REQ, "/sys/kernel/debug/tracing/events/regulator/enable" },
167 } },
Scott Bauerae473362015-06-08 16:32:36 -0700168 { "binder_driver", "Binder Kernel driver", 0, {
169 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction/enable" },
170 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction_received/enable" },
171 } },
172 { "binder_lock", "Binder global lock trace", 0, {
173 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_lock/enable" },
174 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_locked/enable" },
175 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_unlock/enable" },
176 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200177 { "pagecache", "Page cache", 0, {
178 { REQ, "/sys/kernel/debug/tracing/events/filemap/enable" },
179 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800180};
181
182/* Command line options */
183static int g_traceDurationSeconds = 5;
184static bool g_traceOverwrite = false;
185static int g_traceBufferSizeKB = 2048;
186static bool g_compress = false;
187static bool g_nohup = false;
188static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900189static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700190static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700191static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700192static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800193
194/* Global state */
195static bool g_traceAborted = false;
196static bool g_categoryEnables[NELEM(k_categories)] = {};
197
198/* Sys file paths */
199static const char* k_traceClockPath =
200 "/sys/kernel/debug/tracing/trace_clock";
201
202static const char* k_traceBufferSizePath =
203 "/sys/kernel/debug/tracing/buffer_size_kb";
204
205static const char* k_tracingOverwriteEnablePath =
206 "/sys/kernel/debug/tracing/options/overwrite";
207
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700208static const char* k_currentTracerPath =
209 "/sys/kernel/debug/tracing/current_tracer";
210
211static const char* k_printTgidPath =
212 "/sys/kernel/debug/tracing/options/print-tgid";
213
214static const char* k_funcgraphAbsTimePath =
215 "/sys/kernel/debug/tracing/options/funcgraph-abstime";
216
217static const char* k_funcgraphCpuPath =
218 "/sys/kernel/debug/tracing/options/funcgraph-cpu";
219
220static const char* k_funcgraphProcPath =
221 "/sys/kernel/debug/tracing/options/funcgraph-proc";
222
223static const char* k_funcgraphFlatPath =
224 "/sys/kernel/debug/tracing/options/funcgraph-flat";
225
226static const char* k_funcgraphDurationPath =
227 "/sys/kernel/debug/tracing/options/funcgraph-duration";
228
229static const char* k_ftraceFilterPath =
230 "/sys/kernel/debug/tracing/set_ftrace_filter";
231
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800232static const char* k_tracingOnPath =
233 "/sys/kernel/debug/tracing/tracing_on";
234
235static const char* k_tracePath =
236 "/sys/kernel/debug/tracing/trace";
237
Martijn Coenend9535872015-11-26 10:00:55 +0100238static const char* k_traceStreamPath =
239 "/sys/kernel/debug/tracing/trace_pipe";
240
John Reck469a1942015-03-26 15:31:35 -0700241static const char* k_traceMarkerPath =
242 "/sys/kernel/debug/tracing/trace_marker";
243
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800244// Check whether a file exists.
245static bool fileExists(const char* filename) {
246 return access(filename, F_OK) != -1;
247}
248
249// Check whether a file is writable.
250static bool fileIsWritable(const char* filename) {
251 return access(filename, W_OK) != -1;
252}
253
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700254// Truncate a file.
255static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800256{
Jamie Gennis43122e72013-03-21 14:06:31 -0700257 // This uses creat rather than truncate because some of the debug kernel
258 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
259 // calls to truncate, but they are cleared by calls to creat.
260 int traceFD = creat(path, 0);
261 if (traceFD == -1) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700262 fprintf(stderr, "error truncating %s: %s (%d)\n", path,
Jamie Gennis43122e72013-03-21 14:06:31 -0700263 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700264 return false;
265 }
266
Jamie Gennis43122e72013-03-21 14:06:31 -0700267 close(traceFD);
268
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700269 return true;
270}
271
272static bool _writeStr(const char* filename, const char* str, int flags)
273{
274 int fd = open(filename, flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800275 if (fd == -1) {
276 fprintf(stderr, "error opening %s: %s (%d)\n", filename,
277 strerror(errno), errno);
278 return false;
279 }
280
281 bool ok = true;
282 ssize_t len = strlen(str);
283 if (write(fd, str, len) != len) {
284 fprintf(stderr, "error writing to %s: %s (%d)\n", filename,
285 strerror(errno), errno);
286 ok = false;
287 }
288
289 close(fd);
290
291 return ok;
292}
293
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700294// Write a string to a file, returning true if the write was successful.
295static bool writeStr(const char* filename, const char* str)
296{
297 return _writeStr(filename, str, O_WRONLY);
298}
299
300// Append a string to a file, returning true if the write was successful.
301static bool appendStr(const char* filename, const char* str)
302{
303 return _writeStr(filename, str, O_APPEND|O_WRONLY);
304}
305
John Reck469a1942015-03-26 15:31:35 -0700306static void writeClockSyncMarker()
307{
308 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200309 int len = 0;
310 int fd = open(k_traceMarkerPath, O_WRONLY);
311 if (fd == -1) {
312 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
313 strerror(errno), errno);
314 return;
315 }
John Reck469a1942015-03-26 15:31:35 -0700316 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200317
318 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
319 if (write(fd, buffer, len) != len) {
320 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
321 }
322
323 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
324 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
325 if (write(fd, buffer, len) != len) {
326 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
327 }
328
329 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700330}
331
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800332// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
333// file.
334static bool setKernelOptionEnable(const char* filename, bool enable)
335{
336 return writeStr(filename, enable ? "1" : "0");
337}
338
339// Check whether the category is supported on the device with the current
340// rootness. A category is supported only if all its required /sys/ files are
341// writable and if enabling the category will enable one or more tracing tags
342// or /sys/ files.
343static bool isCategorySupported(const TracingCategory& category)
344{
sergeyvdb404152016-05-02 19:26:07 -0700345 if (strcmp(category.name, k_coreServiceCategory) == 0) {
346 char value[PROPERTY_VALUE_MAX];
347 property_get(k_coreServicesProp, value, "");
348 return strlen(value) != 0;
349 }
350
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800351 bool ok = category.tags != 0;
352 for (int i = 0; i < MAX_SYS_FILES; i++) {
353 const char* path = category.sysfiles[i].path;
354 bool req = category.sysfiles[i].required == REQ;
355 if (path != NULL) {
356 if (req) {
357 if (!fileIsWritable(path)) {
358 return false;
359 } else {
360 ok = true;
361 }
362 } else {
363 ok |= fileIsWritable(path);
364 }
365 }
366 }
367 return ok;
368}
369
370// Check whether the category would be supported on the device if the user
371// were root. This function assumes that root is able to write to any file
372// that exists. It performs the same logic as isCategorySupported, but it
373// uses file existance rather than writability in the /sys/ file checks.
374static bool isCategorySupportedForRoot(const TracingCategory& category)
375{
376 bool ok = category.tags != 0;
377 for (int i = 0; i < MAX_SYS_FILES; i++) {
378 const char* path = category.sysfiles[i].path;
379 bool req = category.sysfiles[i].required == REQ;
380 if (path != NULL) {
381 if (req) {
382 if (!fileExists(path)) {
383 return false;
384 } else {
385 ok = true;
386 }
387 } else {
388 ok |= fileExists(path);
389 }
390 }
391 }
392 return ok;
393}
394
395// Enable or disable overwriting of the kernel trace buffers. Disabling this
396// will cause tracing to stop once the trace buffers have filled up.
397static bool setTraceOverwriteEnable(bool enable)
398{
399 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
400}
401
402// Enable or disable kernel tracing.
403static bool setTracingEnabled(bool enable)
404{
405 return setKernelOptionEnable(k_tracingOnPath, enable);
406}
407
408// Clear the contents of the kernel trace.
409static bool clearTrace()
410{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700411 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800412}
413
414// Set the size of the kernel's trace buffer in kilobytes.
415static bool setTraceBufferSizeKB(int size)
416{
417 char str[32] = "1";
418 int len;
419 if (size < 1) {
420 size = 1;
421 }
422 snprintf(str, 32, "%d", size);
423 return writeStr(k_traceBufferSizePath, str);
424}
425
Colin Crossb1ce49b2014-08-20 14:28:47 -0700426// Read the trace_clock sysfs file and return true if it matches the requested
427// value. The trace_clock file format is:
428// local [global] counter uptime perf
429static bool isTraceClock(const char *mode)
430{
431 int fd = open(k_traceClockPath, O_RDONLY);
432 if (fd == -1) {
433 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceClockPath,
434 strerror(errno), errno);
435 return false;
436 }
437
438 char buf[4097];
439 ssize_t n = read(fd, buf, 4096);
440 close(fd);
441 if (n == -1) {
442 fprintf(stderr, "error reading %s: %s (%d)\n", k_traceClockPath,
443 strerror(errno), errno);
444 return false;
445 }
446 buf[n] = '\0';
447
448 char *start = strchr(buf, '[');
449 if (start == NULL) {
450 return false;
451 }
452 start++;
453
454 char *end = strchr(start, ']');
455 if (end == NULL) {
456 return false;
457 }
458 *end = '\0';
459
460 return strcmp(mode, start) == 0;
461}
462
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800463// Enable or disable the kernel's use of the global clock. Disabling the global
464// clock will result in the kernel using a per-CPU local clock.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700465// Any write to the trace_clock sysfs file will reset the buffer, so only
466// update it if the requested value is not the current value.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800467static bool setGlobalClockEnable(bool enable)
468{
Colin Crossb1ce49b2014-08-20 14:28:47 -0700469 const char *clock = enable ? "global" : "local";
470
471 if (isTraceClock(clock)) {
472 return true;
473 }
474
475 return writeStr(k_traceClockPath, clock);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800476}
477
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700478static bool setPrintTgidEnableIfPresent(bool enable)
479{
480 if (fileExists(k_printTgidPath)) {
481 return setKernelOptionEnable(k_printTgidPath, enable);
482 }
483 return true;
484}
485
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800486// Poke all the binder-enabled processes in the system to get them to re-read
487// their system properties.
488static bool pokeBinderServices()
489{
490 sp<IServiceManager> sm = defaultServiceManager();
491 Vector<String16> services = sm->listServices();
492 for (size_t i = 0; i < services.size(); i++) {
493 sp<IBinder> obj = sm->checkService(services[i]);
494 if (obj != NULL) {
495 Parcel data;
496 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
497 NULL, 0) != OK) {
498 if (false) {
499 // XXX: For some reason this fails on tablets trying to
500 // poke the "phone" service. It's not clear whether some
501 // are expected to fail.
502 String8 svc(services[i]);
503 fprintf(stderr, "error poking binder service %s\n",
504 svc.string());
505 return false;
506 }
507 }
508 }
509 }
510 return true;
511}
512
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100513// Poke all the HAL processes in the system to get them to re-read
514// their system properties.
515static void pokeHalServices()
516{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100517 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100518 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100519 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100520 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100521
522 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800523
524 if (sm == nullptr) {
525 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
526 return;
527 }
528
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800529 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100530 for (size_t i = 0; i < interfaces.size(); i++) {
531 string fqInstanceName = interfaces[i];
532 string::size_type n = fqInstanceName.find("/");
533 if (n == std::string::npos || interfaces[i].size() == n+1)
534 continue;
535 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
536 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100537 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
538 if (!interfaceRet.isOk()) {
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800539 fprintf(stderr, "failed to get service %s: %s\n",
540 fqInstanceName.c_str(),
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100541 interfaceRet.description().c_str());
542 continue;
543 }
544 sp<IBase> interface = interfaceRet;
545 auto notifyRet = interface->notifySyspropsChanged();
546 if (!notifyRet.isOk()) {
547 fprintf(stderr, "failed to notifySyspropsChanged on service %s: %s\n",
548 fqInstanceName.c_str(),
549 notifyRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800550 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100551 }
552 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800553 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100554 // TODO(b/34242478) fix this when we determine the correct ACL
555 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800556 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100557}
558
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800559// Set the trace tags that userland tracing uses, and poke the running
560// processes to pick up the new value.
561static bool setTagsProperty(uint64_t tags)
562{
sergeyv4144eff2016-04-28 11:40:04 -0700563 char buf[PROPERTY_VALUE_MAX];
564 snprintf(buf, sizeof(buf), "%#" PRIx64, tags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800565 if (property_set(k_traceTagsProperty, buf) < 0) {
566 fprintf(stderr, "error setting trace tags system property\n");
567 return false;
568 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700569 return true;
570}
571
sergeyv4144eff2016-04-28 11:40:04 -0700572static void clearAppProperties()
573{
574 char buf[PROPERTY_KEY_MAX];
575 for (int i = 0; i < MAX_PACKAGES; i++) {
576 snprintf(buf, sizeof(buf), k_traceAppsPropertyTemplate, i);
577 if (property_set(buf, "") < 0) {
578 fprintf(stderr, "failed to clear system property: %s\n", buf);
579 }
580 }
581 if (property_set(k_traceAppsNumberProperty, "") < 0) {
582 fprintf(stderr, "failed to clear system property: %s",
583 k_traceAppsNumberProperty);
584 }
585}
586
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700587// Set the system property that indicates which apps should perform
588// application-level tracing.
Dan Austin497951c2016-05-31 13:27:03 -0700589static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700590{
sergeyv4144eff2016-04-28 11:40:04 -0700591 char buf[PROPERTY_KEY_MAX];
592 int i = 0;
Dan Austin497951c2016-05-31 13:27:03 -0700593 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700594 while (start != NULL) {
595 if (i == MAX_PACKAGES) {
596 fprintf(stderr, "error: only 16 packages could be traced at once\n");
597 clearAppProperties();
598 return false;
599 }
600 char* end = strchr(start, ',');
601 if (end != NULL) {
602 *end = '\0';
603 end++;
604 }
605 snprintf(buf, sizeof(buf), k_traceAppsPropertyTemplate, i);
606 if (property_set(buf, start) < 0) {
607 fprintf(stderr, "error setting trace app %d property to %s\n", i, buf);
608 clearAppProperties();
609 return false;
610 }
611 start = end;
612 i++;
613 }
614
615 snprintf(buf, sizeof(buf), "%d", i);
616 if (property_set(k_traceAppsNumberProperty, buf) < 0) {
617 fprintf(stderr, "error setting trace app number property to %s\n", buf);
618 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700619 return false;
620 }
621 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800622}
623
624// Disable all /sys/ enable files.
625static bool disableKernelTraceEvents() {
626 bool ok = true;
627 for (int i = 0; i < NELEM(k_categories); i++) {
628 const TracingCategory &c = k_categories[i];
629 for (int j = 0; j < MAX_SYS_FILES; j++) {
630 const char* path = c.sysfiles[j].path;
631 if (path != NULL && fileIsWritable(path)) {
632 ok &= setKernelOptionEnable(path, false);
633 }
634 }
635 }
636 return ok;
637}
638
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700639// Verify that the comma separated list of functions are being traced by the
640// kernel.
641static bool verifyKernelTraceFuncs(const char* funcs)
642{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100643 std::string buf;
644 if (!android::base::ReadFileToString(k_ftraceFilterPath, &buf)) {
645 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700646 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100647 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700648 }
649
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100650 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700651
652 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100653 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700654 bool ok = true;
655 char* myFuncs = strdup(funcs);
656 char* func = strtok(myFuncs, ",");
657 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100658 if (!strchr(func, '*')) {
659 String8 fancyFunc = String8::format("\n%s\n", func);
660 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
661 if (!found || func[0] == '\0') {
662 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
663 "to trace.\n", func);
664 ok = false;
665 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700666 }
667 func = strtok(NULL, ",");
668 }
669 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700670 return ok;
671}
672
673// Set the comma separated list of functions that the kernel is to trace.
674static bool setKernelTraceFuncs(const char* funcs)
675{
676 bool ok = true;
677
678 if (funcs == NULL || funcs[0] == '\0') {
679 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700680 if (fileIsWritable(k_currentTracerPath)) {
681 ok &= writeStr(k_currentTracerPath, "nop");
682 }
683 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700684 ok &= truncateFile(k_ftraceFilterPath);
685 }
686 } else {
687 // Enable kernel function tracing.
688 ok &= writeStr(k_currentTracerPath, "function_graph");
689 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
690 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
691 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
692 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
693
694 // Set the requested filter functions.
695 ok &= truncateFile(k_ftraceFilterPath);
696 char* myFuncs = strdup(funcs);
697 char* func = strtok(myFuncs, ",");
698 while (func) {
699 ok &= appendStr(k_ftraceFilterPath, func);
700 func = strtok(NULL, ",");
701 }
702 free(myFuncs);
703
704 // Verify that the set functions are being traced.
705 if (ok) {
706 ok &= verifyKernelTraceFuncs(funcs);
707 }
708 }
709
710 return ok;
711}
712
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900713static bool setCategoryEnable(const char* name, bool enable)
714{
715 for (int i = 0; i < NELEM(k_categories); i++) {
716 const TracingCategory& c = k_categories[i];
717 if (strcmp(name, c.name) == 0) {
718 if (isCategorySupported(c)) {
719 g_categoryEnables[i] = enable;
720 return true;
721 } else {
722 if (isCategorySupportedForRoot(c)) {
723 fprintf(stderr, "error: category \"%s\" requires root "
724 "privileges.\n", name);
725 } else {
726 fprintf(stderr, "error: category \"%s\" is not supported "
727 "on this device.\n", name);
728 }
729 return false;
730 }
731 }
732 }
733 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
734 return false;
735}
736
737static bool setCategoriesEnableFromFile(const char* categories_file)
738{
739 if (!categories_file) {
740 return true;
741 }
742 Tokenizer* tokenizer = NULL;
743 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
744 return false;
745 }
746 bool ok = true;
747 while (!tokenizer->isEol()) {
748 String8 token = tokenizer->nextToken(" ");
749 if (token.isEmpty()) {
750 tokenizer->skipDelimiters(" ");
751 continue;
752 }
753 ok &= setCategoryEnable(token.string(), true);
754 }
755 delete tokenizer;
756 return ok;
757}
758
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700759// Set all the kernel tracing settings to the desired state for this trace
760// capture.
761static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800762{
763 bool ok = true;
764
765 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900766 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800767 ok &= setTraceOverwriteEnable(g_traceOverwrite);
768 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
769 ok &= setGlobalClockEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700770 ok &= setPrintTgidEnableIfPresent(true);
771 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800772
773 // Set up the tags property.
774 uint64_t tags = 0;
775 for (int i = 0; i < NELEM(k_categories); i++) {
776 if (g_categoryEnables[i]) {
777 const TracingCategory &c = k_categories[i];
778 tags |= c.tags;
779 }
780 }
781 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700782
783 bool coreServicesTagEnabled = false;
784 for (int i = 0; i < NELEM(k_categories); i++) {
785 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
786 coreServicesTagEnabled = g_categoryEnables[i];
787 }
788 }
789
790 std::string packageList(g_debugAppCmdLine);
791 if (coreServicesTagEnabled) {
792 char value[PROPERTY_VALUE_MAX];
793 property_get(k_coreServicesProp, value, "");
794 if (!packageList.empty()) {
795 packageList += ",";
796 }
797 packageList += value;
798 }
Dan Austin497951c2016-05-31 13:27:03 -0700799 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700800 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100801 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800802
803 // Disable all the sysfs enables. This is done as a separate loop from
804 // the enables to allow the same enable to exist in multiple categories.
805 ok &= disableKernelTraceEvents();
806
807 // Enable all the sysfs enables that are in an enabled category.
808 for (int i = 0; i < NELEM(k_categories); i++) {
809 if (g_categoryEnables[i]) {
810 const TracingCategory &c = k_categories[i];
811 for (int j = 0; j < MAX_SYS_FILES; j++) {
812 const char* path = c.sysfiles[j].path;
813 bool required = c.sysfiles[j].required == REQ;
814 if (path != NULL) {
815 if (fileIsWritable(path)) {
816 ok &= setKernelOptionEnable(path, true);
817 } else if (required) {
818 fprintf(stderr, "error writing file %s\n", path);
819 ok = false;
820 }
821 }
822 }
823 }
824 }
825
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800826 return ok;
827}
828
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700829// Reset all the kernel tracing settings to their default state.
830static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800831{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800832 // Disable all tracing that we're able to.
833 disableKernelTraceEvents();
834
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700835 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800836 setTagsProperty(0);
sergeyv4144eff2016-04-28 11:40:04 -0700837 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700838 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800839
840 // Set the options back to their defaults.
841 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700842 setTraceBufferSizeKB(1);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800843 setGlobalClockEnable(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700844 setPrintTgidEnableIfPresent(false);
845 setKernelTraceFuncs(NULL);
846}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800847
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700848
849// Enable tracing in the kernel.
850static bool startTrace()
851{
852 return setTracingEnabled(true);
853}
854
855// Disable tracing in the kernel.
856static void stopTrace()
857{
858 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800859}
860
Martijn Coenend9535872015-11-26 10:00:55 +0100861// Read data from the tracing pipe and forward to stdout
862static void streamTrace()
863{
864 char trace_data[4096];
865 int traceFD = open(k_traceStreamPath, O_RDWR);
866 if (traceFD == -1) {
867 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
868 strerror(errno), errno);
869 return;
870 }
871 while (!g_traceAborted) {
872 ssize_t bytes_read = read(traceFD, trace_data, 4096);
873 if (bytes_read > 0) {
874 write(STDOUT_FILENO, trace_data, bytes_read);
875 fflush(stdout);
876 } else {
877 if (!g_traceAborted) {
878 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
879 bytes_read, errno, strerror(errno));
880 }
881 break;
882 }
883 }
884}
885
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800886// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700887static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800888{
John Reck6c8ac922016-03-28 11:25:30 -0700889 ALOGI("Dumping trace");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800890 int traceFD = open(k_tracePath, O_RDWR);
891 if (traceFD == -1) {
892 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
893 strerror(errno), errno);
894 return;
895 }
896
897 if (g_compress) {
898 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800899 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700900
901 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800902 if (result != Z_OK) {
903 fprintf(stderr, "error initializing zlib: %d\n", result);
904 close(traceFD);
905 return;
906 }
907
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700908 constexpr size_t bufSize = 64*1024;
909 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
910 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
911 if (!in || !out) {
912 fprintf(stderr, "couldn't allocate buffers\n");
913 close(traceFD);
914 return;
915 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800916
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700917 int flush = Z_NO_FLUSH;
918
919 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800920 zs.avail_out = bufSize;
921
922 do {
923
924 if (zs.avail_in == 0) {
925 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700926 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800927 if (result < 0) {
928 fprintf(stderr, "error reading trace: %s (%d)\n",
929 strerror(errno), errno);
930 result = Z_STREAM_END;
931 break;
932 } else if (result == 0) {
933 flush = Z_FINISH;
934 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700935 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800936 zs.avail_in = result;
937 }
938 }
939
940 if (zs.avail_out == 0) {
941 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700942 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800943 if ((size_t)result < bufSize) {
944 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
945 strerror(errno), errno);
946 result = Z_STREAM_END; // skip deflate error message
947 zs.avail_out = bufSize; // skip the final write
948 break;
949 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700950 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800951 zs.avail_out = bufSize;
952 }
953
954 } while ((result = deflate(&zs, flush)) == Z_OK);
955
956 if (result != Z_STREAM_END) {
957 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
958 }
959
960 if (zs.avail_out < bufSize) {
961 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -0700962 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800963 if ((size_t)result < bytes) {
964 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
965 strerror(errno), errno);
966 }
967 }
968
969 result = deflateEnd(&zs);
970 if (result != Z_OK) {
971 fprintf(stderr, "error cleaning up zlib: %d\n", result);
972 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800973 } else {
974 ssize_t sent = 0;
John Reck40b26b42016-03-30 09:44:36 -0700975 while ((sent = sendfile(outFd, traceFD, NULL, 64*1024*1024)) > 0);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800976 if (sent == -1) {
977 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
978 errno);
979 }
980 }
981
982 close(traceFD);
983}
984
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700985static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800986{
987 if (!g_nohup) {
988 g_traceAborted = true;
989 }
990}
991
992static void registerSigHandler()
993{
994 struct sigaction sa;
995 sigemptyset(&sa.sa_mask);
996 sa.sa_flags = 0;
997 sa.sa_handler = handleSignal;
998 sigaction(SIGHUP, &sa, NULL);
999 sigaction(SIGINT, &sa, NULL);
1000 sigaction(SIGQUIT, &sa, NULL);
1001 sigaction(SIGTERM, &sa, NULL);
1002}
1003
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001004static void listSupportedCategories()
1005{
1006 for (int i = 0; i < NELEM(k_categories); i++) {
1007 const TracingCategory& c = k_categories[i];
1008 if (isCategorySupported(c)) {
1009 printf(" %10s - %s\n", c.name, c.longname);
1010 }
1011 }
1012}
1013
1014// Print the command usage help to stderr.
1015static void showHelp(const char *cmd)
1016{
1017 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1018 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001019 " -a appname enable app-level tracing for a comma "
1020 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001021 " -b N use a trace buffer size of N KB\n"
1022 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001023 " -f filename use the categories written in a file as space-separated\n"
1024 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001025 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001026 " -n ignore signals\n"
1027 " -s N sleep for N seconds before tracing [default 0]\n"
Elliott Hughesf884a062016-07-22 09:38:44 -07001028 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001029 " -z compress the trace dump\n"
1030 " --async_start start circular trace and return immediatly\n"
1031 " --async_dump dump the current contents of circular trace buffer\n"
1032 " --async_stop stop tracing and dump the current contents of circular\n"
1033 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001034 " --stream stream trace to stdout as it enters the trace buffer\n"
1035 " Note: this can take significant CPU time, and is best\n"
1036 " used for measuring things that are not affected by\n"
1037 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001038 " --list_categories\n"
1039 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001040 " -o filename write the trace to the specified file instead\n"
1041 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001042 );
1043}
1044
1045int main(int argc, char **argv)
1046{
1047 bool async = false;
1048 bool traceStart = true;
1049 bool traceStop = true;
1050 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001051 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001052
1053 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1054 showHelp(argv[0]);
1055 exit(0);
1056 }
1057
1058 for (;;) {
1059 int ret;
1060 int option_index = 0;
1061 static struct option long_options[] = {
1062 {"async_start", no_argument, 0, 0 },
1063 {"async_stop", no_argument, 0, 0 },
1064 {"async_dump", no_argument, 0, 0 },
1065 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +01001066 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001067 { 0, 0, 0, 0 }
1068 };
1069
John Reck40b26b42016-03-30 09:44:36 -07001070 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001071 long_options, &option_index);
1072
1073 if (ret < 0) {
1074 for (int i = optind; i < argc; i++) {
1075 if (!setCategoryEnable(argv[i], true)) {
1076 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1077 exit(1);
1078 }
1079 }
1080 break;
1081 }
1082
1083 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001084 case 'a':
1085 g_debugAppCmdLine = optarg;
1086 break;
1087
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001088 case 'b':
1089 g_traceBufferSizeKB = atoi(optarg);
1090 break;
1091
1092 case 'c':
1093 g_traceOverwrite = true;
1094 break;
1095
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001096 case 'f':
1097 g_categoriesFile = optarg;
1098 break;
1099
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001100 case 'k':
1101 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001102 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001103
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001104 case 'n':
1105 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001106 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001107
1108 case 's':
1109 g_initialSleepSecs = atoi(optarg);
1110 break;
1111
1112 case 't':
1113 g_traceDurationSeconds = atoi(optarg);
1114 break;
1115
1116 case 'z':
1117 g_compress = true;
1118 break;
1119
John Reck40b26b42016-03-30 09:44:36 -07001120 case 'o':
1121 g_outputFile = optarg;
1122 break;
1123
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001124 case 0:
1125 if (!strcmp(long_options[option_index].name, "async_start")) {
1126 async = true;
1127 traceStop = false;
1128 traceDump = false;
1129 g_traceOverwrite = true;
1130 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1131 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001132 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001133 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1134 async = true;
1135 traceStart = false;
1136 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001137 } else if (!strcmp(long_options[option_index].name, "stream")) {
1138 traceStream = true;
1139 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001140 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1141 listSupportedCategories();
1142 exit(0);
1143 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001144 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001145
1146 default:
1147 fprintf(stderr, "\n");
1148 showHelp(argv[0]);
1149 exit(-1);
1150 break;
1151 }
1152 }
1153
1154 registerSigHandler();
1155
1156 if (g_initialSleepSecs > 0) {
1157 sleep(g_initialSleepSecs);
1158 }
1159
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001160 bool ok = true;
1161 ok &= setUpTrace();
1162 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001163
1164 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001165 if (!traceStream) {
1166 printf("capturing trace...");
1167 fflush(stdout);
1168 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001169
1170 // We clear the trace after starting it because tracing gets enabled for
1171 // each CPU individually in the kernel. Having the beginning of the trace
1172 // contain entries from only one CPU can cause "begin" entries without a
1173 // matching "end" entry to show up if a task gets migrated from one CPU to
1174 // another.
1175 ok = clearTrace();
1176
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001177 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001178 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001179 // Sleep to allow the trace to be captured.
1180 struct timespec timeLeft;
1181 timeLeft.tv_sec = g_traceDurationSeconds;
1182 timeLeft.tv_nsec = 0;
1183 do {
1184 if (g_traceAborted) {
1185 break;
1186 }
1187 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1188 }
Martijn Coenend9535872015-11-26 10:00:55 +01001189
1190 if (traceStream) {
1191 streamTrace();
1192 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001193 }
1194
1195 // Stop the trace and restore the default settings.
1196 if (traceStop)
1197 stopTrace();
1198
1199 if (ok && traceDump) {
1200 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001201 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001202 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001203 int outFd = STDOUT_FILENO;
1204 if (g_outputFile) {
1205 outFd = open(g_outputFile, O_WRONLY | O_CREAT);
1206 }
1207 if (outFd == -1) {
1208 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1209 } else {
1210 dprintf(outFd, "TRACE:\n");
1211 dumpTrace(outFd);
1212 if (g_outputFile) {
1213 close(outFd);
1214 }
1215 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001216 } else {
1217 printf("\ntrace aborted.\n");
1218 fflush(stdout);
1219 }
1220 clearTrace();
1221 } else if (!ok) {
1222 fprintf(stderr, "unable to start tracing\n");
1223 }
1224
1225 // Reset the trace buffer size to 1.
1226 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001227 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001228
1229 return g_traceAborted ? 1 : 0;
1230}