blob: 457d203571178238d71093214d804c77e888b2d5 [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
Paul Lawrence2cd93cc2017-01-17 09:50:18 -080017#define LOG_TAG "atrace"
John Reck40b26b42016-03-30 09:44:36 -070018
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 <time.h>
Martijn Coenend9535872015-11-26 10:00:55 +010030#include <unistd.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080031#include <zlib.h>
32
Carmen Jacksonea826792017-05-05 11:42:32 -070033#include <fstream>
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
43#include <utils/String8.h>
John Reck469a1942015-03-26 15:31:35 -070044#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +090045#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080046#include <utils/Trace.h>
Stephane Gasparinid8419c22016-03-02 13:45:15 +010047#include <android-base/file.h>
Elliott Hughes5fd6ff62017-03-28 14:55:31 -070048#include <android-base/macros.h>
49#include <android-base/properties.h>
50#include <android-base/stringprintf.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080051
52using namespace android;
53
Martijn Coenenee9b97e2016-11-16 16:00:26 +010054using std::string;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080055
sergeyv4144eff2016-04-28 11:40:04 -070056#define MAX_SYS_FILES 10
57#define MAX_PACKAGES 16
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080058
59const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
sergeyv4144eff2016-04-28 11:40:04 -070060
61const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
62const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070063const char* k_coreServiceCategory = "core_services";
64const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080065
66typedef enum { OPT, REQ } requiredness ;
67
68struct TracingCategory {
69 // The name identifying the category.
70 const char* name;
71
72 // A longer description of the category.
73 const char* longname;
74
75 // The userland tracing tags that the category enables.
76 uint64_t tags;
77
78 // The fname==NULL terminated list of /sys/ files that the category
79 // enables.
80 struct {
81 // Whether the file must be writable in order to enable the tracing
82 // category.
83 requiredness required;
84
85 // The path to the enable file.
86 const char* path;
87 } sysfiles[MAX_SYS_FILES];
88};
89
90/* Tracing categories */
91static const TracingCategory k_categories[] = {
Jamie Gennisb2a89e32013-03-11 19:37:53 -070092 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, { } },
93 { "input", "Input", ATRACE_TAG_INPUT, { } },
94 { "view", "View System", ATRACE_TAG_VIEW, { } },
95 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
96 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
97 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -050098 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070099 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
100 { "video", "Video", ATRACE_TAG_VIDEO, { } },
101 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
102 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700103 { "app", "Application", ATRACE_TAG_APP, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -0700104 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -0700105 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -0700106 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -0700107 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700108 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 14:36:20 -0700109 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-07-01 01:46:25 +0900110 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Greg Hackmannbbd7d992014-12-01 14:43:34 -0800111 { "database", "Database", ATRACE_TAG_DATABASE, { } },
Felipe Leme0f97c1d2016-09-07 11:33:26 -0700112 { "network", "Network", ATRACE_TAG_NETWORK, { } },
Josh Gao468b4cb2016-11-29 10:55:21 -0800113 { "adb", "ADB", ATRACE_TAG_ADB, { } },
sergeyvdb404152016-05-02 19:26:07 -0700114 { k_coreServiceCategory, "Core services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700115 { "sched", "CPU Scheduling", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800116 { REQ, "events/sched/sched_switch/enable" },
117 { REQ, "events/sched/sched_wakeup/enable" },
118 { OPT, "events/sched/sched_blocked_reason/enable" },
119 { OPT, "events/sched/sched_cpu_hotplug/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800120 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700121 { "irq", "IRQ Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800122 { REQ, "events/irq/enable" },
123 { OPT, "events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700124 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100125 { "i2c", "I2C Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800126 { REQ, "events/i2c/enable" },
127 { REQ, "events/i2c/i2c_read/enable" },
128 { REQ, "events/i2c/i2c_write/enable" },
129 { REQ, "events/i2c/i2c_result/enable" },
130 { REQ, "events/i2c/i2c_reply/enable" },
131 { OPT, "events/i2c/smbus_read/enable" },
132 { OPT, "events/i2c/smbus_write/enable" },
133 { OPT, "events/i2c/smbus_result/enable" },
134 { OPT, "events/i2c/smbus_reply/enable" },
Michael Wright43fb6782016-08-18 19:56:43 +0100135 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700136 { "freq", "CPU Frequency", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800137 { REQ, "events/power/cpu_frequency/enable" },
138 { OPT, "events/power/clock_set_rate/enable" },
139 { OPT, "events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800140 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700141 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800142 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800143 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700144 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800145 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800146 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700147 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800148 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
149 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
150 { OPT, "events/f2fs/f2fs_write_begin/enable" },
151 { OPT, "events/f2fs/f2fs_write_end/enable" },
152 { OPT, "events/ext4/ext4_da_write_begin/enable" },
153 { OPT, "events/ext4/ext4_da_write_end/enable" },
154 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
155 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
156 { REQ, "events/block/block_rq_issue/enable" },
157 { REQ, "events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800158 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700159 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800160 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700161 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700162 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800163 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800164 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700165 { "sync", "Synchronization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800166 { REQ, "events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800167 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700168 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800169 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800170 } },
Colin Cross580407f2014-08-18 15:22:13 -0700171 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800172 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
173 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
174 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
175 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Marc Hittingerf1f62e32017-05-17 15:57:43 -0700176 { REQ, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700177 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800178 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800179 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800180 } },
Scott Bauerae473362015-06-08 16:32:36 -0700181 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800182 { REQ, "events/binder/binder_transaction/enable" },
183 { REQ, "events/binder/binder_transaction_received/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700184 } },
185 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800186 { OPT, "events/binder/binder_lock/enable" },
187 { OPT, "events/binder/binder_locked/enable" },
188 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700189 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200190 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800191 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200192 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800193};
194
195/* Command line options */
196static int g_traceDurationSeconds = 5;
197static bool g_traceOverwrite = false;
198static int g_traceBufferSizeKB = 2048;
199static bool g_compress = false;
200static bool g_nohup = false;
201static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900202static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700203static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700204static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700205static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800206
207/* Global state */
208static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700209static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800210static std::string g_traceFolder;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800211
212/* Sys file paths */
213static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800214 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800215
216static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800217 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800218
219static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800220 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800221
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700222static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800223 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700224
225static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800226 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700227
228static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800229 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700230
231static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800232 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700233
234static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800235 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700236
237static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800238 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700239
240static const char* k_funcgraphDurationPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800241 "options/funcgraph-duration";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700242
243static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800244 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700245
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800246static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800247 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800248
249static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800250 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800251
Martijn Coenend9535872015-11-26 10:00:55 +0100252static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800253 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100254
John Reck469a1942015-03-26 15:31:35 -0700255static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800256 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700257
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800258// Check whether a file exists.
259static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800260 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800261}
262
263// Check whether a file is writable.
264static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800265 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800266}
267
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700268// Truncate a file.
269static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800270{
Jamie Gennis43122e72013-03-21 14:06:31 -0700271 // This uses creat rather than truncate because some of the debug kernel
272 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
273 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800274 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700275 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800276 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700277 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700278 return false;
279 }
280
Jamie Gennis43122e72013-03-21 14:06:31 -0700281 close(traceFD);
282
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700283 return true;
284}
285
286static bool _writeStr(const char* filename, const char* str, int flags)
287{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800288 std::string fullFilename = g_traceFolder + filename;
289 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800290 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800291 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800292 strerror(errno), errno);
293 return false;
294 }
295
296 bool ok = true;
297 ssize_t len = strlen(str);
298 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800299 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800300 strerror(errno), errno);
301 ok = false;
302 }
303
304 close(fd);
305
306 return ok;
307}
308
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700309// Write a string to a file, returning true if the write was successful.
310static bool writeStr(const char* filename, const char* str)
311{
312 return _writeStr(filename, str, O_WRONLY);
313}
314
315// Append a string to a file, returning true if the write was successful.
316static bool appendStr(const char* filename, const char* str)
317{
318 return _writeStr(filename, str, O_APPEND|O_WRONLY);
319}
320
John Reck469a1942015-03-26 15:31:35 -0700321static void writeClockSyncMarker()
322{
323 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200324 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800325 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200326 if (fd == -1) {
327 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
328 strerror(errno), errno);
329 return;
330 }
John Reck469a1942015-03-26 15:31:35 -0700331 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200332
333 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
334 if (write(fd, buffer, len) != len) {
335 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
336 }
337
338 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
339 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
340 if (write(fd, buffer, len) != len) {
341 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
342 }
343
344 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700345}
346
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800347// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
348// file.
349static bool setKernelOptionEnable(const char* filename, bool enable)
350{
351 return writeStr(filename, enable ? "1" : "0");
352}
353
354// Check whether the category is supported on the device with the current
355// rootness. A category is supported only if all its required /sys/ files are
356// writable and if enabling the category will enable one or more tracing tags
357// or /sys/ files.
358static bool isCategorySupported(const TracingCategory& category)
359{
sergeyvdb404152016-05-02 19:26:07 -0700360 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700361 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700362 }
363
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800364 bool ok = category.tags != 0;
365 for (int i = 0; i < MAX_SYS_FILES; i++) {
366 const char* path = category.sysfiles[i].path;
367 bool req = category.sysfiles[i].required == REQ;
368 if (path != NULL) {
369 if (req) {
370 if (!fileIsWritable(path)) {
371 return false;
372 } else {
373 ok = true;
374 }
375 } else {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800376 ok = true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800377 }
378 }
379 }
380 return ok;
381}
382
383// Check whether the category would be supported on the device if the user
384// were root. This function assumes that root is able to write to any file
385// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700386// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800387static bool isCategorySupportedForRoot(const TracingCategory& category)
388{
389 bool ok = category.tags != 0;
390 for (int i = 0; i < MAX_SYS_FILES; i++) {
391 const char* path = category.sysfiles[i].path;
392 bool req = category.sysfiles[i].required == REQ;
393 if (path != NULL) {
394 if (req) {
395 if (!fileExists(path)) {
396 return false;
397 } else {
398 ok = true;
399 }
400 } else {
401 ok |= fileExists(path);
402 }
403 }
404 }
405 return ok;
406}
407
408// Enable or disable overwriting of the kernel trace buffers. Disabling this
409// will cause tracing to stop once the trace buffers have filled up.
410static bool setTraceOverwriteEnable(bool enable)
411{
412 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
413}
414
415// Enable or disable kernel tracing.
416static bool setTracingEnabled(bool enable)
417{
418 return setKernelOptionEnable(k_tracingOnPath, enable);
419}
420
421// Clear the contents of the kernel trace.
422static bool clearTrace()
423{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700424 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800425}
426
427// Set the size of the kernel's trace buffer in kilobytes.
428static bool setTraceBufferSizeKB(int size)
429{
430 char str[32] = "1";
431 int len;
432 if (size < 1) {
433 size = 1;
434 }
435 snprintf(str, 32, "%d", size);
436 return writeStr(k_traceBufferSizePath, str);
437}
438
Carmen Jacksonea826792017-05-05 11:42:32 -0700439// Set the clock to the best available option while tracing. Use 'boot' if it's
440// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700441// Any write to the trace_clock sysfs file will reset the buffer, so only
442// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700443static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800444{
Carmen Jacksonea826792017-05-05 11:42:32 -0700445 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
446 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
447 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700448
Carmen Jacksonea826792017-05-05 11:42:32 -0700449 std::string newClock;
450 if (clockStr.find("boot") != std::string::npos) {
451 newClock = "boot";
452 } else if (clockStr.find("mono") != std::string::npos) {
453 newClock = "mono";
454 } else {
455 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700456 }
457
Carmen Jacksonea826792017-05-05 11:42:32 -0700458 size_t begin = clockStr.find("[") + 1;
459 size_t end = clockStr.find("]");
460 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
461 return true;
462 }
463 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800464}
465
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700466static bool setPrintTgidEnableIfPresent(bool enable)
467{
468 if (fileExists(k_printTgidPath)) {
469 return setKernelOptionEnable(k_printTgidPath, enable);
470 }
471 return true;
472}
473
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800474// Poke all the binder-enabled processes in the system to get them to re-read
475// their system properties.
476static bool pokeBinderServices()
477{
478 sp<IServiceManager> sm = defaultServiceManager();
479 Vector<String16> services = sm->listServices();
480 for (size_t i = 0; i < services.size(); i++) {
481 sp<IBinder> obj = sm->checkService(services[i]);
482 if (obj != NULL) {
483 Parcel data;
484 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
485 NULL, 0) != OK) {
486 if (false) {
487 // XXX: For some reason this fails on tablets trying to
488 // poke the "phone" service. It's not clear whether some
489 // are expected to fail.
490 String8 svc(services[i]);
491 fprintf(stderr, "error poking binder service %s\n",
492 svc.string());
493 return false;
494 }
495 }
496 }
497 }
498 return true;
499}
500
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100501// Poke all the HAL processes in the system to get them to re-read
502// their system properties.
503static void pokeHalServices()
504{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100505 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100506 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100507 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100508 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100509
510 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800511
512 if (sm == nullptr) {
513 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
514 return;
515 }
516
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800517 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100518 for (size_t i = 0; i < interfaces.size(); i++) {
519 string fqInstanceName = interfaces[i];
520 string::size_type n = fqInstanceName.find("/");
521 if (n == std::string::npos || interfaces[i].size() == n+1)
522 continue;
523 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
524 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100525 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
526 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100527 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100528 continue;
529 }
Carmen Jackson73206122017-04-18 15:37:57 -0700530
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100531 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700532 if (interface == nullptr) {
533 // ignore
534 continue;
535 }
536
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100537 auto notifyRet = interface->notifySyspropsChanged();
538 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100539 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800540 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100541 }
542 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800543 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100544 // TODO(b/34242478) fix this when we determine the correct ACL
545 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800546 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100547}
548
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800549// Set the trace tags that userland tracing uses, and poke the running
550// processes to pick up the new value.
551static bool setTagsProperty(uint64_t tags)
552{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700553 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
554 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800555 fprintf(stderr, "error setting trace tags system property\n");
556 return false;
557 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700558 return true;
559}
560
sergeyv4144eff2016-04-28 11:40:04 -0700561static void clearAppProperties()
562{
sergeyv4144eff2016-04-28 11:40:04 -0700563 for (int i = 0; i < MAX_PACKAGES; i++) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700564 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
565 if (!android::base::SetProperty(key, "")) {
566 fprintf(stderr, "failed to clear system property: %s\n", key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700567 }
568 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700569 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700570 fprintf(stderr, "failed to clear system property: %s",
571 k_traceAppsNumberProperty);
572 }
573}
574
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700575// Set the system property that indicates which apps should perform
576// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700577static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700578{
sergeyv4144eff2016-04-28 11:40:04 -0700579 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700580 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700581 while (start != NULL) {
582 if (i == MAX_PACKAGES) {
583 fprintf(stderr, "error: only 16 packages could be traced at once\n");
584 clearAppProperties();
585 return false;
586 }
587 char* end = strchr(start, ',');
588 if (end != NULL) {
589 *end = '\0';
590 end++;
591 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700592 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
593 if (!android::base::SetProperty(key, start)) {
594 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700595 clearAppProperties();
596 return false;
597 }
598 start = end;
599 i++;
600 }
601
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700602 std::string value = android::base::StringPrintf("%d", i);
603 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
604 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700605 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700606 return false;
607 }
608 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800609}
610
611// Disable all /sys/ enable files.
612static bool disableKernelTraceEvents() {
613 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700614 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800615 const TracingCategory &c = k_categories[i];
616 for (int j = 0; j < MAX_SYS_FILES; j++) {
617 const char* path = c.sysfiles[j].path;
618 if (path != NULL && fileIsWritable(path)) {
619 ok &= setKernelOptionEnable(path, false);
620 }
621 }
622 }
623 return ok;
624}
625
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700626// Verify that the comma separated list of functions are being traced by the
627// kernel.
628static bool verifyKernelTraceFuncs(const char* funcs)
629{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100630 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800631 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100632 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700633 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100634 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700635 }
636
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100637 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700638
639 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100640 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700641 bool ok = true;
642 char* myFuncs = strdup(funcs);
643 char* func = strtok(myFuncs, ",");
644 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100645 if (!strchr(func, '*')) {
646 String8 fancyFunc = String8::format("\n%s\n", func);
647 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
648 if (!found || func[0] == '\0') {
649 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
650 "to trace.\n", func);
651 ok = false;
652 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700653 }
654 func = strtok(NULL, ",");
655 }
656 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700657 return ok;
658}
659
660// Set the comma separated list of functions that the kernel is to trace.
661static bool setKernelTraceFuncs(const char* funcs)
662{
663 bool ok = true;
664
665 if (funcs == NULL || funcs[0] == '\0') {
666 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700667 if (fileIsWritable(k_currentTracerPath)) {
668 ok &= writeStr(k_currentTracerPath, "nop");
669 }
670 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700671 ok &= truncateFile(k_ftraceFilterPath);
672 }
673 } else {
674 // Enable kernel function tracing.
675 ok &= writeStr(k_currentTracerPath, "function_graph");
676 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
677 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
678 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
679 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
680
681 // Set the requested filter functions.
682 ok &= truncateFile(k_ftraceFilterPath);
683 char* myFuncs = strdup(funcs);
684 char* func = strtok(myFuncs, ",");
685 while (func) {
686 ok &= appendStr(k_ftraceFilterPath, func);
687 func = strtok(NULL, ",");
688 }
689 free(myFuncs);
690
691 // Verify that the set functions are being traced.
692 if (ok) {
693 ok &= verifyKernelTraceFuncs(funcs);
694 }
695 }
696
697 return ok;
698}
699
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900700static bool setCategoryEnable(const char* name, bool enable)
701{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700702 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900703 const TracingCategory& c = k_categories[i];
704 if (strcmp(name, c.name) == 0) {
705 if (isCategorySupported(c)) {
706 g_categoryEnables[i] = enable;
707 return true;
708 } else {
709 if (isCategorySupportedForRoot(c)) {
710 fprintf(stderr, "error: category \"%s\" requires root "
711 "privileges.\n", name);
712 } else {
713 fprintf(stderr, "error: category \"%s\" is not supported "
714 "on this device.\n", name);
715 }
716 return false;
717 }
718 }
719 }
720 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
721 return false;
722}
723
724static bool setCategoriesEnableFromFile(const char* categories_file)
725{
726 if (!categories_file) {
727 return true;
728 }
729 Tokenizer* tokenizer = NULL;
730 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
731 return false;
732 }
733 bool ok = true;
734 while (!tokenizer->isEol()) {
735 String8 token = tokenizer->nextToken(" ");
736 if (token.isEmpty()) {
737 tokenizer->skipDelimiters(" ");
738 continue;
739 }
740 ok &= setCategoryEnable(token.string(), true);
741 }
742 delete tokenizer;
743 return ok;
744}
745
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700746// Set all the kernel tracing settings to the desired state for this trace
747// capture.
748static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800749{
750 bool ok = true;
751
752 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900753 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800754 ok &= setTraceOverwriteEnable(g_traceOverwrite);
755 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
Carmen Jacksonea826792017-05-05 11:42:32 -0700756 ok &= setClock();
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700757 ok &= setPrintTgidEnableIfPresent(true);
758 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800759
760 // Set up the tags property.
761 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700762 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800763 if (g_categoryEnables[i]) {
764 const TracingCategory &c = k_categories[i];
765 tags |= c.tags;
766 }
767 }
768 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700769
770 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700771 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700772 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
773 coreServicesTagEnabled = g_categoryEnables[i];
774 }
775 }
776
777 std::string packageList(g_debugAppCmdLine);
778 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700779 if (!packageList.empty()) {
780 packageList += ",";
781 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700782 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700783 }
Dan Austin09a79872016-05-31 13:27:03 -0700784 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700785 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100786 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800787
788 // Disable all the sysfs enables. This is done as a separate loop from
789 // the enables to allow the same enable to exist in multiple categories.
790 ok &= disableKernelTraceEvents();
791
792 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700793 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800794 if (g_categoryEnables[i]) {
795 const TracingCategory &c = k_categories[i];
796 for (int j = 0; j < MAX_SYS_FILES; j++) {
797 const char* path = c.sysfiles[j].path;
798 bool required = c.sysfiles[j].required == REQ;
799 if (path != NULL) {
800 if (fileIsWritable(path)) {
801 ok &= setKernelOptionEnable(path, true);
802 } else if (required) {
803 fprintf(stderr, "error writing file %s\n", path);
804 ok = false;
805 }
806 }
807 }
808 }
809 }
810
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800811 return ok;
812}
813
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700814// Reset all the kernel tracing settings to their default state.
815static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800816{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800817 // Disable all tracing that we're able to.
818 disableKernelTraceEvents();
819
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700820 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800821 setTagsProperty(0);
sergeyv4144eff2016-04-28 11:40:04 -0700822 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700823 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800824
825 // Set the options back to their defaults.
826 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700827 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700828 setPrintTgidEnableIfPresent(false);
829 setKernelTraceFuncs(NULL);
830}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800831
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700832
833// Enable tracing in the kernel.
834static bool startTrace()
835{
836 return setTracingEnabled(true);
837}
838
839// Disable tracing in the kernel.
840static void stopTrace()
841{
842 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800843}
844
Martijn Coenend9535872015-11-26 10:00:55 +0100845// Read data from the tracing pipe and forward to stdout
846static void streamTrace()
847{
848 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800849 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100850 if (traceFD == -1) {
851 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
852 strerror(errno), errno);
853 return;
854 }
855 while (!g_traceAborted) {
856 ssize_t bytes_read = read(traceFD, trace_data, 4096);
857 if (bytes_read > 0) {
858 write(STDOUT_FILENO, trace_data, bytes_read);
859 fflush(stdout);
860 } else {
861 if (!g_traceAborted) {
862 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
863 bytes_read, errno, strerror(errno));
864 }
865 break;
866 }
867 }
868}
869
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800870// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700871static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800872{
John Reck6c8ac922016-03-28 11:25:30 -0700873 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800874 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800875 if (traceFD == -1) {
876 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
877 strerror(errno), errno);
878 return;
879 }
880
881 if (g_compress) {
882 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800883 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700884
885 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800886 if (result != Z_OK) {
887 fprintf(stderr, "error initializing zlib: %d\n", result);
888 close(traceFD);
889 return;
890 }
891
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700892 constexpr size_t bufSize = 64*1024;
893 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
894 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
895 if (!in || !out) {
896 fprintf(stderr, "couldn't allocate buffers\n");
897 close(traceFD);
898 return;
899 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800900
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700901 int flush = Z_NO_FLUSH;
902
903 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800904 zs.avail_out = bufSize;
905
906 do {
907
908 if (zs.avail_in == 0) {
909 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700910 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800911 if (result < 0) {
912 fprintf(stderr, "error reading trace: %s (%d)\n",
913 strerror(errno), errno);
914 result = Z_STREAM_END;
915 break;
916 } else if (result == 0) {
917 flush = Z_FINISH;
918 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700919 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800920 zs.avail_in = result;
921 }
922 }
923
924 if (zs.avail_out == 0) {
925 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700926 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800927 if ((size_t)result < bufSize) {
928 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
929 strerror(errno), errno);
930 result = Z_STREAM_END; // skip deflate error message
931 zs.avail_out = bufSize; // skip the final write
932 break;
933 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700934 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800935 zs.avail_out = bufSize;
936 }
937
938 } while ((result = deflate(&zs, flush)) == Z_OK);
939
940 if (result != Z_STREAM_END) {
941 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
942 }
943
944 if (zs.avail_out < bufSize) {
945 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -0700946 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800947 if ((size_t)result < bytes) {
948 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
949 strerror(errno), errno);
950 }
951 }
952
953 result = deflateEnd(&zs);
954 if (result != Z_OK) {
955 fprintf(stderr, "error cleaning up zlib: %d\n", result);
956 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800957 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -0700958 char buf[4096];
959 ssize_t rc;
960 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
961 if (!android::base::WriteFully(outFd, buf, rc)) {
962 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
963 break;
964 }
965 }
966 if (rc == -1) {
967 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800968 }
969 }
970
971 close(traceFD);
972}
973
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700974static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800975{
976 if (!g_nohup) {
977 g_traceAborted = true;
978 }
979}
980
981static void registerSigHandler()
982{
983 struct sigaction sa;
984 sigemptyset(&sa.sa_mask);
985 sa.sa_flags = 0;
986 sa.sa_handler = handleSignal;
987 sigaction(SIGHUP, &sa, NULL);
988 sigaction(SIGINT, &sa, NULL);
989 sigaction(SIGQUIT, &sa, NULL);
990 sigaction(SIGTERM, &sa, NULL);
991}
992
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800993static void listSupportedCategories()
994{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700995 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800996 const TracingCategory& c = k_categories[i];
997 if (isCategorySupported(c)) {
998 printf(" %10s - %s\n", c.name, c.longname);
999 }
1000 }
1001}
1002
1003// Print the command usage help to stderr.
1004static void showHelp(const char *cmd)
1005{
1006 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1007 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001008 " -a appname enable app-level tracing for a comma "
1009 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001010 " -b N use a trace buffer size of N KB\n"
1011 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001012 " -f filename use the categories written in a file as space-separated\n"
1013 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001014 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001015 " -n ignore signals\n"
1016 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001017 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001018 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001019 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001020 " --async_dump dump the current contents of circular trace buffer\n"
1021 " --async_stop stop tracing and dump the current contents of circular\n"
1022 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001023 " --stream stream trace to stdout as it enters the trace buffer\n"
1024 " Note: this can take significant CPU time, and is best\n"
1025 " used for measuring things that are not affected by\n"
1026 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001027 " --list_categories\n"
1028 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001029 " -o filename write the trace to the specified file instead\n"
1030 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001031 );
1032}
1033
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001034bool findTraceFiles()
1035{
1036 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1037 static const std::string tracefs_path = "/sys/kernel/tracing/";
1038 static const std::string trace_file = "trace_marker";
1039
1040 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1041 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1042
1043 if (!tracefs && !debugfs) {
1044 fprintf(stderr, "Error: Did not find trace folder\n");
1045 return false;
1046 }
1047
1048 if (tracefs) {
1049 g_traceFolder = tracefs_path;
1050 } else {
1051 g_traceFolder = debugfs_path;
1052 }
1053
1054 return true;
1055}
1056
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001057int main(int argc, char **argv)
1058{
1059 bool async = false;
1060 bool traceStart = true;
1061 bool traceStop = true;
1062 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001063 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001064
1065 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1066 showHelp(argv[0]);
1067 exit(0);
1068 }
1069
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001070 if (!findTraceFiles()) {
1071 fprintf(stderr, "No trace folder found\n");
1072 exit(-1);
1073 }
1074
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001075 for (;;) {
1076 int ret;
1077 int option_index = 0;
1078 static struct option long_options[] = {
1079 {"async_start", no_argument, 0, 0 },
1080 {"async_stop", no_argument, 0, 0 },
1081 {"async_dump", no_argument, 0, 0 },
1082 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +01001083 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001084 { 0, 0, 0, 0 }
1085 };
1086
John Reck40b26b42016-03-30 09:44:36 -07001087 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001088 long_options, &option_index);
1089
1090 if (ret < 0) {
1091 for (int i = optind; i < argc; i++) {
1092 if (!setCategoryEnable(argv[i], true)) {
1093 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1094 exit(1);
1095 }
1096 }
1097 break;
1098 }
1099
1100 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001101 case 'a':
1102 g_debugAppCmdLine = optarg;
1103 break;
1104
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001105 case 'b':
1106 g_traceBufferSizeKB = atoi(optarg);
1107 break;
1108
1109 case 'c':
1110 g_traceOverwrite = true;
1111 break;
1112
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001113 case 'f':
1114 g_categoriesFile = optarg;
1115 break;
1116
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001117 case 'k':
1118 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001119 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001120
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001121 case 'n':
1122 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001123 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001124
1125 case 's':
1126 g_initialSleepSecs = atoi(optarg);
1127 break;
1128
1129 case 't':
1130 g_traceDurationSeconds = atoi(optarg);
1131 break;
1132
1133 case 'z':
1134 g_compress = true;
1135 break;
1136
John Reck40b26b42016-03-30 09:44:36 -07001137 case 'o':
1138 g_outputFile = optarg;
1139 break;
1140
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001141 case 0:
1142 if (!strcmp(long_options[option_index].name, "async_start")) {
1143 async = true;
1144 traceStop = false;
1145 traceDump = false;
1146 g_traceOverwrite = true;
1147 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1148 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001149 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001150 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1151 async = true;
1152 traceStart = false;
1153 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001154 } else if (!strcmp(long_options[option_index].name, "stream")) {
1155 traceStream = true;
1156 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001157 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1158 listSupportedCategories();
1159 exit(0);
1160 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001161 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001162
1163 default:
1164 fprintf(stderr, "\n");
1165 showHelp(argv[0]);
1166 exit(-1);
1167 break;
1168 }
1169 }
1170
1171 registerSigHandler();
1172
1173 if (g_initialSleepSecs > 0) {
1174 sleep(g_initialSleepSecs);
1175 }
1176
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001177 bool ok = true;
1178 ok &= setUpTrace();
1179 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001180
1181 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001182 if (!traceStream) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001183 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001184 fflush(stdout);
1185 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001186
1187 // We clear the trace after starting it because tracing gets enabled for
1188 // each CPU individually in the kernel. Having the beginning of the trace
1189 // contain entries from only one CPU can cause "begin" entries without a
1190 // matching "end" entry to show up if a task gets migrated from one CPU to
1191 // another.
1192 ok = clearTrace();
1193
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001194 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001195 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001196 // Sleep to allow the trace to be captured.
1197 struct timespec timeLeft;
1198 timeLeft.tv_sec = g_traceDurationSeconds;
1199 timeLeft.tv_nsec = 0;
1200 do {
1201 if (g_traceAborted) {
1202 break;
1203 }
1204 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1205 }
Martijn Coenend9535872015-11-26 10:00:55 +01001206
1207 if (traceStream) {
1208 streamTrace();
1209 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001210 }
1211
1212 // Stop the trace and restore the default settings.
1213 if (traceStop)
1214 stopTrace();
1215
1216 if (ok && traceDump) {
1217 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001218 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001219 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001220 int outFd = STDOUT_FILENO;
1221 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001222 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001223 }
1224 if (outFd == -1) {
1225 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1226 } else {
1227 dprintf(outFd, "TRACE:\n");
1228 dumpTrace(outFd);
1229 if (g_outputFile) {
1230 close(outFd);
1231 }
1232 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001233 } else {
1234 printf("\ntrace aborted.\n");
1235 fflush(stdout);
1236 }
1237 clearTrace();
1238 } else if (!ok) {
1239 fprintf(stderr, "unable to start tracing\n");
1240 }
1241
1242 // Reset the trace buffer size to 1.
1243 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001244 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001245
1246 return g_traceAborted ? 1 : 0;
1247}