blob: d39c5cef479bf1351e856e93500ca646ab2d2324 [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 } },
Michael Wrightab54f682016-08-18 19:56:43 +0100124 { "i2c", "I2C Events", 0, {
125 { REQ, "/sys/kernel/debug/tracing/events/i2c/enable" },
126 { REQ, "/sys/kernel/debug/tracing/events/i2c/i2c_read/enable" },
127 { REQ, "/sys/kernel/debug/tracing/events/i2c/i2c_write/enable" },
128 { REQ, "/sys/kernel/debug/tracing/events/i2c/i2c_result/enable" },
129 { REQ, "/sys/kernel/debug/tracing/events/i2c/i2c_reply/enable" },
130 { OPT, "/sys/kernel/debug/tracing/events/i2c/smbus_read/enable" },
131 { OPT, "/sys/kernel/debug/tracing/events/i2c/smbus_write/enable" },
132 { OPT, "/sys/kernel/debug/tracing/events/i2c/smbus_result/enable" },
133 { OPT, "/sys/kernel/debug/tracing/events/i2c/smbus_reply/enable" },
134 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700135 { "freq", "CPU Frequency", 0, {
136 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_frequency/enable" },
137 { OPT, "/sys/kernel/debug/tracing/events/power/clock_set_rate/enable" },
Ruchi Kandoiffcc7112015-11-19 18:32:00 -0800138 { OPT, "/sys/kernel/debug/tracing/events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800139 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700140 { "membus", "Memory Bus Utilization", 0, {
141 { REQ, "/sys/kernel/debug/tracing/events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800142 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700143 { "idle", "CPU Idle", 0, {
144 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800145 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700146 { "disk", "Disk I/O", 0, {
Greg Hackmanne80d32c2014-11-20 12:59:44 -0800147 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_enter/enable" },
148 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_exit/enable" },
149 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_begin/enable" },
150 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_end/enable" },
151 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_begin/enable" },
152 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_end/enable" },
153 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable" },
154 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable" },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700155 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" },
156 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800157 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700158 { "mmc", "eMMC commands", 0, {
159 { REQ, "/sys/kernel/debug/tracing/events/mmc/enable" },
160 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700161 { "load", "CPU Load", 0, {
162 { REQ, "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800163 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700164 { "sync", "Synchronization", 0, {
165 { REQ, "/sys/kernel/debug/tracing/events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800166 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700167 { "workq", "Kernel Workqueues", 0, {
168 { REQ, "/sys/kernel/debug/tracing/events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800169 } },
Colin Cross580407f2014-08-18 15:22:13 -0700170 { "memreclaim", "Kernel Memory Reclaim", 0, {
171 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
172 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
173 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_wake/enable" },
174 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_sleep/enable" },
175 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800176 { "regulators", "Voltage and Current Regulators", 0, {
177 { REQ, "/sys/kernel/debug/tracing/events/regulator/enable" },
178 } },
Scott Bauerae473362015-06-08 16:32:36 -0700179 { "binder_driver", "Binder Kernel driver", 0, {
180 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction/enable" },
181 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_transaction_received/enable" },
182 } },
183 { "binder_lock", "Binder global lock trace", 0, {
184 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_lock/enable" },
185 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_locked/enable" },
186 { REQ, "/sys/kernel/debug/tracing/events/binder/binder_unlock/enable" },
187 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200188 { "pagecache", "Page cache", 0, {
189 { REQ, "/sys/kernel/debug/tracing/events/filemap/enable" },
190 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800191};
192
193/* Command line options */
194static int g_traceDurationSeconds = 5;
195static bool g_traceOverwrite = false;
196static int g_traceBufferSizeKB = 2048;
197static bool g_compress = false;
198static bool g_nohup = false;
199static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900200static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700201static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700202static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700203static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800204
205/* Global state */
206static bool g_traceAborted = false;
207static bool g_categoryEnables[NELEM(k_categories)] = {};
208
209/* Sys file paths */
210static const char* k_traceClockPath =
211 "/sys/kernel/debug/tracing/trace_clock";
212
213static const char* k_traceBufferSizePath =
214 "/sys/kernel/debug/tracing/buffer_size_kb";
215
216static const char* k_tracingOverwriteEnablePath =
217 "/sys/kernel/debug/tracing/options/overwrite";
218
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700219static const char* k_currentTracerPath =
220 "/sys/kernel/debug/tracing/current_tracer";
221
222static const char* k_printTgidPath =
223 "/sys/kernel/debug/tracing/options/print-tgid";
224
225static const char* k_funcgraphAbsTimePath =
226 "/sys/kernel/debug/tracing/options/funcgraph-abstime";
227
228static const char* k_funcgraphCpuPath =
229 "/sys/kernel/debug/tracing/options/funcgraph-cpu";
230
231static const char* k_funcgraphProcPath =
232 "/sys/kernel/debug/tracing/options/funcgraph-proc";
233
234static const char* k_funcgraphFlatPath =
235 "/sys/kernel/debug/tracing/options/funcgraph-flat";
236
237static const char* k_funcgraphDurationPath =
238 "/sys/kernel/debug/tracing/options/funcgraph-duration";
239
240static const char* k_ftraceFilterPath =
241 "/sys/kernel/debug/tracing/set_ftrace_filter";
242
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800243static const char* k_tracingOnPath =
244 "/sys/kernel/debug/tracing/tracing_on";
245
246static const char* k_tracePath =
247 "/sys/kernel/debug/tracing/trace";
248
Martijn Coenend9535872015-11-26 10:00:55 +0100249static const char* k_traceStreamPath =
250 "/sys/kernel/debug/tracing/trace_pipe";
251
John Reck469a1942015-03-26 15:31:35 -0700252static const char* k_traceMarkerPath =
253 "/sys/kernel/debug/tracing/trace_marker";
254
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800255// Check whether a file exists.
256static bool fileExists(const char* filename) {
257 return access(filename, F_OK) != -1;
258}
259
260// Check whether a file is writable.
261static bool fileIsWritable(const char* filename) {
262 return access(filename, W_OK) != -1;
263}
264
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700265// Truncate a file.
266static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800267{
Jamie Gennis43122e72013-03-21 14:06:31 -0700268 // This uses creat rather than truncate because some of the debug kernel
269 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
270 // calls to truncate, but they are cleared by calls to creat.
271 int traceFD = creat(path, 0);
272 if (traceFD == -1) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700273 fprintf(stderr, "error truncating %s: %s (%d)\n", path,
Jamie Gennis43122e72013-03-21 14:06:31 -0700274 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700275 return false;
276 }
277
Jamie Gennis43122e72013-03-21 14:06:31 -0700278 close(traceFD);
279
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700280 return true;
281}
282
283static bool _writeStr(const char* filename, const char* str, int flags)
284{
285 int fd = open(filename, flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800286 if (fd == -1) {
287 fprintf(stderr, "error opening %s: %s (%d)\n", filename,
288 strerror(errno), errno);
289 return false;
290 }
291
292 bool ok = true;
293 ssize_t len = strlen(str);
294 if (write(fd, str, len) != len) {
295 fprintf(stderr, "error writing to %s: %s (%d)\n", filename,
296 strerror(errno), errno);
297 ok = false;
298 }
299
300 close(fd);
301
302 return ok;
303}
304
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700305// Write a string to a file, returning true if the write was successful.
306static bool writeStr(const char* filename, const char* str)
307{
308 return _writeStr(filename, str, O_WRONLY);
309}
310
311// Append a string to a file, returning true if the write was successful.
312static bool appendStr(const char* filename, const char* str)
313{
314 return _writeStr(filename, str, O_APPEND|O_WRONLY);
315}
316
John Reck469a1942015-03-26 15:31:35 -0700317static void writeClockSyncMarker()
318{
319 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200320 int len = 0;
321 int fd = open(k_traceMarkerPath, O_WRONLY);
322 if (fd == -1) {
323 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
324 strerror(errno), errno);
325 return;
326 }
John Reck469a1942015-03-26 15:31:35 -0700327 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200328
329 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
330 if (write(fd, buffer, len) != len) {
331 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
332 }
333
334 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
335 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
336 if (write(fd, buffer, len) != len) {
337 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
338 }
339
340 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700341}
342
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800343// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
344// file.
345static bool setKernelOptionEnable(const char* filename, bool enable)
346{
347 return writeStr(filename, enable ? "1" : "0");
348}
349
350// Check whether the category is supported on the device with the current
351// rootness. A category is supported only if all its required /sys/ files are
352// writable and if enabling the category will enable one or more tracing tags
353// or /sys/ files.
354static bool isCategorySupported(const TracingCategory& category)
355{
sergeyvdb404152016-05-02 19:26:07 -0700356 if (strcmp(category.name, k_coreServiceCategory) == 0) {
357 char value[PROPERTY_VALUE_MAX];
358 property_get(k_coreServicesProp, value, "");
359 return strlen(value) != 0;
360 }
361
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800362 bool ok = category.tags != 0;
363 for (int i = 0; i < MAX_SYS_FILES; i++) {
364 const char* path = category.sysfiles[i].path;
365 bool req = category.sysfiles[i].required == REQ;
366 if (path != NULL) {
367 if (req) {
368 if (!fileIsWritable(path)) {
369 return false;
370 } else {
371 ok = true;
372 }
373 } else {
374 ok |= fileIsWritable(path);
375 }
376 }
377 }
378 return ok;
379}
380
381// Check whether the category would be supported on the device if the user
382// were root. This function assumes that root is able to write to any file
383// that exists. It performs the same logic as isCategorySupported, but it
384// uses file existance rather than writability in the /sys/ file checks.
385static bool isCategorySupportedForRoot(const TracingCategory& category)
386{
387 bool ok = category.tags != 0;
388 for (int i = 0; i < MAX_SYS_FILES; i++) {
389 const char* path = category.sysfiles[i].path;
390 bool req = category.sysfiles[i].required == REQ;
391 if (path != NULL) {
392 if (req) {
393 if (!fileExists(path)) {
394 return false;
395 } else {
396 ok = true;
397 }
398 } else {
399 ok |= fileExists(path);
400 }
401 }
402 }
403 return ok;
404}
405
406// Enable or disable overwriting of the kernel trace buffers. Disabling this
407// will cause tracing to stop once the trace buffers have filled up.
408static bool setTraceOverwriteEnable(bool enable)
409{
410 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
411}
412
413// Enable or disable kernel tracing.
414static bool setTracingEnabled(bool enable)
415{
416 return setKernelOptionEnable(k_tracingOnPath, enable);
417}
418
419// Clear the contents of the kernel trace.
420static bool clearTrace()
421{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700422 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800423}
424
425// Set the size of the kernel's trace buffer in kilobytes.
426static bool setTraceBufferSizeKB(int size)
427{
428 char str[32] = "1";
429 int len;
430 if (size < 1) {
431 size = 1;
432 }
433 snprintf(str, 32, "%d", size);
434 return writeStr(k_traceBufferSizePath, str);
435}
436
Colin Crossb1ce49b2014-08-20 14:28:47 -0700437// Read the trace_clock sysfs file and return true if it matches the requested
438// value. The trace_clock file format is:
439// local [global] counter uptime perf
440static bool isTraceClock(const char *mode)
441{
442 int fd = open(k_traceClockPath, O_RDONLY);
443 if (fd == -1) {
444 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceClockPath,
445 strerror(errno), errno);
446 return false;
447 }
448
449 char buf[4097];
450 ssize_t n = read(fd, buf, 4096);
451 close(fd);
452 if (n == -1) {
453 fprintf(stderr, "error reading %s: %s (%d)\n", k_traceClockPath,
454 strerror(errno), errno);
455 return false;
456 }
457 buf[n] = '\0';
458
459 char *start = strchr(buf, '[');
460 if (start == NULL) {
461 return false;
462 }
463 start++;
464
465 char *end = strchr(start, ']');
466 if (end == NULL) {
467 return false;
468 }
469 *end = '\0';
470
471 return strcmp(mode, start) == 0;
472}
473
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800474// Enable or disable the kernel's use of the global clock. Disabling the global
475// clock will result in the kernel using a per-CPU local clock.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700476// Any write to the trace_clock sysfs file will reset the buffer, so only
477// update it if the requested value is not the current value.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800478static bool setGlobalClockEnable(bool enable)
479{
Colin Crossb1ce49b2014-08-20 14:28:47 -0700480 const char *clock = enable ? "global" : "local";
481
482 if (isTraceClock(clock)) {
483 return true;
484 }
485
486 return writeStr(k_traceClockPath, clock);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800487}
488
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700489static bool setPrintTgidEnableIfPresent(bool enable)
490{
491 if (fileExists(k_printTgidPath)) {
492 return setKernelOptionEnable(k_printTgidPath, enable);
493 }
494 return true;
495}
496
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800497// Poke all the binder-enabled processes in the system to get them to re-read
498// their system properties.
499static bool pokeBinderServices()
500{
501 sp<IServiceManager> sm = defaultServiceManager();
502 Vector<String16> services = sm->listServices();
503 for (size_t i = 0; i < services.size(); i++) {
504 sp<IBinder> obj = sm->checkService(services[i]);
505 if (obj != NULL) {
506 Parcel data;
507 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
508 NULL, 0) != OK) {
509 if (false) {
510 // XXX: For some reason this fails on tablets trying to
511 // poke the "phone" service. It's not clear whether some
512 // are expected to fail.
513 String8 svc(services[i]);
514 fprintf(stderr, "error poking binder service %s\n",
515 svc.string());
516 return false;
517 }
518 }
519 }
520 }
521 return true;
522}
523
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100524// Poke all the HAL processes in the system to get them to re-read
525// their system properties.
526static void pokeHalServices()
527{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100528 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100529 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100530 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100531 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100532
533 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800534
535 if (sm == nullptr) {
536 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
537 return;
538 }
539
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800540 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100541 for (size_t i = 0; i < interfaces.size(); i++) {
542 string fqInstanceName = interfaces[i];
543 string::size_type n = fqInstanceName.find("/");
544 if (n == std::string::npos || interfaces[i].size() == n+1)
545 continue;
546 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
547 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100548 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
549 if (!interfaceRet.isOk()) {
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800550 fprintf(stderr, "failed to get service %s: %s\n",
551 fqInstanceName.c_str(),
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100552 interfaceRet.description().c_str());
553 continue;
554 }
555 sp<IBase> interface = interfaceRet;
556 auto notifyRet = interface->notifySyspropsChanged();
557 if (!notifyRet.isOk()) {
558 fprintf(stderr, "failed to notifySyspropsChanged on service %s: %s\n",
559 fqInstanceName.c_str(),
560 notifyRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800561 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100562 }
563 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800564 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100565 // TODO(b/34242478) fix this when we determine the correct ACL
566 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800567 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100568}
569
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800570// Set the trace tags that userland tracing uses, and poke the running
571// processes to pick up the new value.
572static bool setTagsProperty(uint64_t tags)
573{
sergeyv4144eff2016-04-28 11:40:04 -0700574 char buf[PROPERTY_VALUE_MAX];
575 snprintf(buf, sizeof(buf), "%#" PRIx64, tags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800576 if (property_set(k_traceTagsProperty, buf) < 0) {
577 fprintf(stderr, "error setting trace tags system property\n");
578 return false;
579 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700580 return true;
581}
582
sergeyv4144eff2016-04-28 11:40:04 -0700583static void clearAppProperties()
584{
585 char buf[PROPERTY_KEY_MAX];
586 for (int i = 0; i < MAX_PACKAGES; i++) {
587 snprintf(buf, sizeof(buf), k_traceAppsPropertyTemplate, i);
588 if (property_set(buf, "") < 0) {
589 fprintf(stderr, "failed to clear system property: %s\n", buf);
590 }
591 }
592 if (property_set(k_traceAppsNumberProperty, "") < 0) {
593 fprintf(stderr, "failed to clear system property: %s",
594 k_traceAppsNumberProperty);
595 }
596}
597
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700598// Set the system property that indicates which apps should perform
599// application-level tracing.
Dan Austin497951c2016-05-31 13:27:03 -0700600static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700601{
sergeyv4144eff2016-04-28 11:40:04 -0700602 char buf[PROPERTY_KEY_MAX];
603 int i = 0;
Dan Austin497951c2016-05-31 13:27:03 -0700604 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700605 while (start != NULL) {
606 if (i == MAX_PACKAGES) {
607 fprintf(stderr, "error: only 16 packages could be traced at once\n");
608 clearAppProperties();
609 return false;
610 }
611 char* end = strchr(start, ',');
612 if (end != NULL) {
613 *end = '\0';
614 end++;
615 }
616 snprintf(buf, sizeof(buf), k_traceAppsPropertyTemplate, i);
617 if (property_set(buf, start) < 0) {
618 fprintf(stderr, "error setting trace app %d property to %s\n", i, buf);
619 clearAppProperties();
620 return false;
621 }
622 start = end;
623 i++;
624 }
625
626 snprintf(buf, sizeof(buf), "%d", i);
627 if (property_set(k_traceAppsNumberProperty, buf) < 0) {
628 fprintf(stderr, "error setting trace app number property to %s\n", buf);
629 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700630 return false;
631 }
632 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800633}
634
635// Disable all /sys/ enable files.
636static bool disableKernelTraceEvents() {
637 bool ok = true;
638 for (int i = 0; i < NELEM(k_categories); i++) {
639 const TracingCategory &c = k_categories[i];
640 for (int j = 0; j < MAX_SYS_FILES; j++) {
641 const char* path = c.sysfiles[j].path;
642 if (path != NULL && fileIsWritable(path)) {
643 ok &= setKernelOptionEnable(path, false);
644 }
645 }
646 }
647 return ok;
648}
649
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700650// Verify that the comma separated list of functions are being traced by the
651// kernel.
652static bool verifyKernelTraceFuncs(const char* funcs)
653{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100654 std::string buf;
655 if (!android::base::ReadFileToString(k_ftraceFilterPath, &buf)) {
656 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700657 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100658 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700659 }
660
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100661 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700662
663 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100664 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700665 bool ok = true;
666 char* myFuncs = strdup(funcs);
667 char* func = strtok(myFuncs, ",");
668 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100669 if (!strchr(func, '*')) {
670 String8 fancyFunc = String8::format("\n%s\n", func);
671 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
672 if (!found || func[0] == '\0') {
673 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
674 "to trace.\n", func);
675 ok = false;
676 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700677 }
678 func = strtok(NULL, ",");
679 }
680 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700681 return ok;
682}
683
684// Set the comma separated list of functions that the kernel is to trace.
685static bool setKernelTraceFuncs(const char* funcs)
686{
687 bool ok = true;
688
689 if (funcs == NULL || funcs[0] == '\0') {
690 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700691 if (fileIsWritable(k_currentTracerPath)) {
692 ok &= writeStr(k_currentTracerPath, "nop");
693 }
694 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700695 ok &= truncateFile(k_ftraceFilterPath);
696 }
697 } else {
698 // Enable kernel function tracing.
699 ok &= writeStr(k_currentTracerPath, "function_graph");
700 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
701 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
702 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
703 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
704
705 // Set the requested filter functions.
706 ok &= truncateFile(k_ftraceFilterPath);
707 char* myFuncs = strdup(funcs);
708 char* func = strtok(myFuncs, ",");
709 while (func) {
710 ok &= appendStr(k_ftraceFilterPath, func);
711 func = strtok(NULL, ",");
712 }
713 free(myFuncs);
714
715 // Verify that the set functions are being traced.
716 if (ok) {
717 ok &= verifyKernelTraceFuncs(funcs);
718 }
719 }
720
721 return ok;
722}
723
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900724static bool setCategoryEnable(const char* name, bool enable)
725{
726 for (int i = 0; i < NELEM(k_categories); i++) {
727 const TracingCategory& c = k_categories[i];
728 if (strcmp(name, c.name) == 0) {
729 if (isCategorySupported(c)) {
730 g_categoryEnables[i] = enable;
731 return true;
732 } else {
733 if (isCategorySupportedForRoot(c)) {
734 fprintf(stderr, "error: category \"%s\" requires root "
735 "privileges.\n", name);
736 } else {
737 fprintf(stderr, "error: category \"%s\" is not supported "
738 "on this device.\n", name);
739 }
740 return false;
741 }
742 }
743 }
744 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
745 return false;
746}
747
748static bool setCategoriesEnableFromFile(const char* categories_file)
749{
750 if (!categories_file) {
751 return true;
752 }
753 Tokenizer* tokenizer = NULL;
754 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
755 return false;
756 }
757 bool ok = true;
758 while (!tokenizer->isEol()) {
759 String8 token = tokenizer->nextToken(" ");
760 if (token.isEmpty()) {
761 tokenizer->skipDelimiters(" ");
762 continue;
763 }
764 ok &= setCategoryEnable(token.string(), true);
765 }
766 delete tokenizer;
767 return ok;
768}
769
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700770// Set all the kernel tracing settings to the desired state for this trace
771// capture.
772static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800773{
774 bool ok = true;
775
776 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900777 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800778 ok &= setTraceOverwriteEnable(g_traceOverwrite);
779 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
780 ok &= setGlobalClockEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700781 ok &= setPrintTgidEnableIfPresent(true);
782 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800783
784 // Set up the tags property.
785 uint64_t tags = 0;
786 for (int i = 0; i < NELEM(k_categories); i++) {
787 if (g_categoryEnables[i]) {
788 const TracingCategory &c = k_categories[i];
789 tags |= c.tags;
790 }
791 }
792 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700793
794 bool coreServicesTagEnabled = false;
795 for (int i = 0; i < NELEM(k_categories); i++) {
796 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
797 coreServicesTagEnabled = g_categoryEnables[i];
798 }
799 }
800
801 std::string packageList(g_debugAppCmdLine);
802 if (coreServicesTagEnabled) {
803 char value[PROPERTY_VALUE_MAX];
804 property_get(k_coreServicesProp, value, "");
805 if (!packageList.empty()) {
806 packageList += ",";
807 }
808 packageList += value;
809 }
Dan Austin497951c2016-05-31 13:27:03 -0700810 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700811 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100812 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800813
814 // Disable all the sysfs enables. This is done as a separate loop from
815 // the enables to allow the same enable to exist in multiple categories.
816 ok &= disableKernelTraceEvents();
817
818 // Enable all the sysfs enables that are in an enabled category.
819 for (int i = 0; i < NELEM(k_categories); i++) {
820 if (g_categoryEnables[i]) {
821 const TracingCategory &c = k_categories[i];
822 for (int j = 0; j < MAX_SYS_FILES; j++) {
823 const char* path = c.sysfiles[j].path;
824 bool required = c.sysfiles[j].required == REQ;
825 if (path != NULL) {
826 if (fileIsWritable(path)) {
827 ok &= setKernelOptionEnable(path, true);
828 } else if (required) {
829 fprintf(stderr, "error writing file %s\n", path);
830 ok = false;
831 }
832 }
833 }
834 }
835 }
836
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800837 return ok;
838}
839
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700840// Reset all the kernel tracing settings to their default state.
841static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800842{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800843 // Disable all tracing that we're able to.
844 disableKernelTraceEvents();
845
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700846 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800847 setTagsProperty(0);
sergeyv4144eff2016-04-28 11:40:04 -0700848 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700849 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800850
851 // Set the options back to their defaults.
852 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700853 setTraceBufferSizeKB(1);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800854 setGlobalClockEnable(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700855 setPrintTgidEnableIfPresent(false);
856 setKernelTraceFuncs(NULL);
857}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800858
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700859
860// Enable tracing in the kernel.
861static bool startTrace()
862{
863 return setTracingEnabled(true);
864}
865
866// Disable tracing in the kernel.
867static void stopTrace()
868{
869 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800870}
871
Martijn Coenend9535872015-11-26 10:00:55 +0100872// Read data from the tracing pipe and forward to stdout
873static void streamTrace()
874{
875 char trace_data[4096];
876 int traceFD = open(k_traceStreamPath, O_RDWR);
877 if (traceFD == -1) {
878 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
879 strerror(errno), errno);
880 return;
881 }
882 while (!g_traceAborted) {
883 ssize_t bytes_read = read(traceFD, trace_data, 4096);
884 if (bytes_read > 0) {
885 write(STDOUT_FILENO, trace_data, bytes_read);
886 fflush(stdout);
887 } else {
888 if (!g_traceAborted) {
889 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
890 bytes_read, errno, strerror(errno));
891 }
892 break;
893 }
894 }
895}
896
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800897// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700898static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800899{
John Reck6c8ac922016-03-28 11:25:30 -0700900 ALOGI("Dumping trace");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800901 int traceFD = open(k_tracePath, O_RDWR);
902 if (traceFD == -1) {
903 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
904 strerror(errno), errno);
905 return;
906 }
907
908 if (g_compress) {
909 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800910 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700911
912 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800913 if (result != Z_OK) {
914 fprintf(stderr, "error initializing zlib: %d\n", result);
915 close(traceFD);
916 return;
917 }
918
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700919 constexpr size_t bufSize = 64*1024;
920 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
921 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
922 if (!in || !out) {
923 fprintf(stderr, "couldn't allocate buffers\n");
924 close(traceFD);
925 return;
926 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800927
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700928 int flush = Z_NO_FLUSH;
929
930 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800931 zs.avail_out = bufSize;
932
933 do {
934
935 if (zs.avail_in == 0) {
936 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700937 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800938 if (result < 0) {
939 fprintf(stderr, "error reading trace: %s (%d)\n",
940 strerror(errno), errno);
941 result = Z_STREAM_END;
942 break;
943 } else if (result == 0) {
944 flush = Z_FINISH;
945 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700946 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800947 zs.avail_in = result;
948 }
949 }
950
951 if (zs.avail_out == 0) {
952 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700953 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800954 if ((size_t)result < bufSize) {
955 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
956 strerror(errno), errno);
957 result = Z_STREAM_END; // skip deflate error message
958 zs.avail_out = bufSize; // skip the final write
959 break;
960 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700961 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800962 zs.avail_out = bufSize;
963 }
964
965 } while ((result = deflate(&zs, flush)) == Z_OK);
966
967 if (result != Z_STREAM_END) {
968 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
969 }
970
971 if (zs.avail_out < bufSize) {
972 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -0700973 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800974 if ((size_t)result < bytes) {
975 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
976 strerror(errno), errno);
977 }
978 }
979
980 result = deflateEnd(&zs);
981 if (result != Z_OK) {
982 fprintf(stderr, "error cleaning up zlib: %d\n", result);
983 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800984 } else {
985 ssize_t sent = 0;
John Reck40b26b42016-03-30 09:44:36 -0700986 while ((sent = sendfile(outFd, traceFD, NULL, 64*1024*1024)) > 0);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800987 if (sent == -1) {
988 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
989 errno);
990 }
991 }
992
993 close(traceFD);
994}
995
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700996static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800997{
998 if (!g_nohup) {
999 g_traceAborted = true;
1000 }
1001}
1002
1003static void registerSigHandler()
1004{
1005 struct sigaction sa;
1006 sigemptyset(&sa.sa_mask);
1007 sa.sa_flags = 0;
1008 sa.sa_handler = handleSignal;
1009 sigaction(SIGHUP, &sa, NULL);
1010 sigaction(SIGINT, &sa, NULL);
1011 sigaction(SIGQUIT, &sa, NULL);
1012 sigaction(SIGTERM, &sa, NULL);
1013}
1014
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001015static void listSupportedCategories()
1016{
1017 for (int i = 0; i < NELEM(k_categories); i++) {
1018 const TracingCategory& c = k_categories[i];
1019 if (isCategorySupported(c)) {
1020 printf(" %10s - %s\n", c.name, c.longname);
1021 }
1022 }
1023}
1024
1025// Print the command usage help to stderr.
1026static void showHelp(const char *cmd)
1027{
1028 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1029 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001030 " -a appname enable app-level tracing for a comma "
1031 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001032 " -b N use a trace buffer size of N KB\n"
1033 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001034 " -f filename use the categories written in a file as space-separated\n"
1035 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001036 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001037 " -n ignore signals\n"
1038 " -s N sleep for N seconds before tracing [default 0]\n"
Elliott Hughesf884a062016-07-22 09:38:44 -07001039 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001040 " -z compress the trace dump\n"
1041 " --async_start start circular trace and return immediatly\n"
1042 " --async_dump dump the current contents of circular trace buffer\n"
1043 " --async_stop stop tracing and dump the current contents of circular\n"
1044 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001045 " --stream stream trace to stdout as it enters the trace buffer\n"
1046 " Note: this can take significant CPU time, and is best\n"
1047 " used for measuring things that are not affected by\n"
1048 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001049 " --list_categories\n"
1050 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001051 " -o filename write the trace to the specified file instead\n"
1052 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001053 );
1054}
1055
1056int main(int argc, char **argv)
1057{
1058 bool async = false;
1059 bool traceStart = true;
1060 bool traceStop = true;
1061 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001062 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001063
1064 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1065 showHelp(argv[0]);
1066 exit(0);
1067 }
1068
1069 for (;;) {
1070 int ret;
1071 int option_index = 0;
1072 static struct option long_options[] = {
1073 {"async_start", no_argument, 0, 0 },
1074 {"async_stop", no_argument, 0, 0 },
1075 {"async_dump", no_argument, 0, 0 },
1076 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +01001077 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001078 { 0, 0, 0, 0 }
1079 };
1080
John Reck40b26b42016-03-30 09:44:36 -07001081 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001082 long_options, &option_index);
1083
1084 if (ret < 0) {
1085 for (int i = optind; i < argc; i++) {
1086 if (!setCategoryEnable(argv[i], true)) {
1087 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1088 exit(1);
1089 }
1090 }
1091 break;
1092 }
1093
1094 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001095 case 'a':
1096 g_debugAppCmdLine = optarg;
1097 break;
1098
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001099 case 'b':
1100 g_traceBufferSizeKB = atoi(optarg);
1101 break;
1102
1103 case 'c':
1104 g_traceOverwrite = true;
1105 break;
1106
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001107 case 'f':
1108 g_categoriesFile = optarg;
1109 break;
1110
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001111 case 'k':
1112 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001113 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001114
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001115 case 'n':
1116 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001117 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001118
1119 case 's':
1120 g_initialSleepSecs = atoi(optarg);
1121 break;
1122
1123 case 't':
1124 g_traceDurationSeconds = atoi(optarg);
1125 break;
1126
1127 case 'z':
1128 g_compress = true;
1129 break;
1130
John Reck40b26b42016-03-30 09:44:36 -07001131 case 'o':
1132 g_outputFile = optarg;
1133 break;
1134
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001135 case 0:
1136 if (!strcmp(long_options[option_index].name, "async_start")) {
1137 async = true;
1138 traceStop = false;
1139 traceDump = false;
1140 g_traceOverwrite = true;
1141 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1142 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001143 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001144 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1145 async = true;
1146 traceStart = false;
1147 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001148 } else if (!strcmp(long_options[option_index].name, "stream")) {
1149 traceStream = true;
1150 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001151 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1152 listSupportedCategories();
1153 exit(0);
1154 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001155 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001156
1157 default:
1158 fprintf(stderr, "\n");
1159 showHelp(argv[0]);
1160 exit(-1);
1161 break;
1162 }
1163 }
1164
1165 registerSigHandler();
1166
1167 if (g_initialSleepSecs > 0) {
1168 sleep(g_initialSleepSecs);
1169 }
1170
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001171 bool ok = true;
1172 ok &= setUpTrace();
1173 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001174
1175 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001176 if (!traceStream) {
1177 printf("capturing trace...");
1178 fflush(stdout);
1179 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001180
1181 // We clear the trace after starting it because tracing gets enabled for
1182 // each CPU individually in the kernel. Having the beginning of the trace
1183 // contain entries from only one CPU can cause "begin" entries without a
1184 // matching "end" entry to show up if a task gets migrated from one CPU to
1185 // another.
1186 ok = clearTrace();
1187
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001188 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001189 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001190 // Sleep to allow the trace to be captured.
1191 struct timespec timeLeft;
1192 timeLeft.tv_sec = g_traceDurationSeconds;
1193 timeLeft.tv_nsec = 0;
1194 do {
1195 if (g_traceAborted) {
1196 break;
1197 }
1198 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1199 }
Martijn Coenend9535872015-11-26 10:00:55 +01001200
1201 if (traceStream) {
1202 streamTrace();
1203 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001204 }
1205
1206 // Stop the trace and restore the default settings.
1207 if (traceStop)
1208 stopTrace();
1209
1210 if (ok && traceDump) {
1211 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001212 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001213 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001214 int outFd = STDOUT_FILENO;
1215 if (g_outputFile) {
1216 outFd = open(g_outputFile, O_WRONLY | O_CREAT);
1217 }
1218 if (outFd == -1) {
1219 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1220 } else {
1221 dprintf(outFd, "TRACE:\n");
1222 dumpTrace(outFd);
1223 if (g_outputFile) {
1224 close(outFd);
1225 }
1226 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001227 } else {
1228 printf("\ntrace aborted.\n");
1229 fflush(stdout);
1230 }
1231 clearTrace();
1232 } else if (!ok) {
1233 fprintf(stderr, "unable to start tracing\n");
1234 }
1235
1236 // Reset the trace buffer size to 1.
1237 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001238 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001239
1240 return g_traceAborted ? 1 : 0;
1241}