blob: c79692e94d1ca20659013f2da3c1aec8fcc0d081 [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
Elliott Hughesa252f4d2016-07-21 17:12:15 -070033#include <memory>
34
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080035#include <binder/IBinder.h>
36#include <binder/IServiceManager.h>
37#include <binder/Parcel.h>
38
Martijn Coenenee9b97e2016-11-16 16:00:26 +010039#include <android/hidl/manager/1.0/IServiceManager.h>
40#include <hidl/ServiceManagement.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080041
42#include <utils/String8.h>
John Reck469a1942015-03-26 15:31:35 -070043#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +090044#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080045#include <utils/Trace.h>
Stephane Gasparinid8419c22016-03-02 13:45:15 +010046#include <android-base/file.h>
Elliott Hughes5fd6ff62017-03-28 14:55:31 -070047#include <android-base/macros.h>
48#include <android-base/properties.h>
49#include <android-base/stringprintf.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080050
51using namespace android;
52
Martijn Coenenee9b97e2016-11-16 16:00:26 +010053using std::string;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080054
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, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800115 { REQ, "events/sched/sched_switch/enable" },
116 { REQ, "events/sched/sched_wakeup/enable" },
117 { OPT, "events/sched/sched_blocked_reason/enable" },
118 { OPT, "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, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800121 { REQ, "events/irq/enable" },
122 { OPT, "events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700123 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100124 { "i2c", "I2C Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800125 { REQ, "events/i2c/enable" },
126 { REQ, "events/i2c/i2c_read/enable" },
127 { REQ, "events/i2c/i2c_write/enable" },
128 { REQ, "events/i2c/i2c_result/enable" },
129 { REQ, "events/i2c/i2c_reply/enable" },
130 { OPT, "events/i2c/smbus_read/enable" },
131 { OPT, "events/i2c/smbus_write/enable" },
132 { OPT, "events/i2c/smbus_result/enable" },
133 { OPT, "events/i2c/smbus_reply/enable" },
Michael Wright43fb6782016-08-18 19:56:43 +0100134 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700135 { "freq", "CPU Frequency", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800136 { REQ, "events/power/cpu_frequency/enable" },
137 { OPT, "events/power/clock_set_rate/enable" },
138 { OPT, "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, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800141 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800142 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700143 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800144 { REQ, "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, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800147 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
148 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
149 { OPT, "events/f2fs/f2fs_write_begin/enable" },
150 { OPT, "events/f2fs/f2fs_write_end/enable" },
151 { OPT, "events/ext4/ext4_da_write_begin/enable" },
152 { OPT, "events/ext4/ext4_da_write_end/enable" },
153 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
154 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
155 { REQ, "events/block/block_rq_issue/enable" },
156 { REQ, "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, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800159 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700160 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700161 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800162 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800163 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700164 { "sync", "Synchronization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800165 { REQ, "events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800166 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700167 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800168 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800169 } },
Colin Cross580407f2014-08-18 15:22:13 -0700170 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800171 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
172 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
173 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
174 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Marc Hittingerf1f62e32017-05-17 15:57:43 -0700175 { REQ, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700176 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800177 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800178 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800179 } },
Scott Bauerae473362015-06-08 16:32:36 -0700180 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800181 { REQ, "events/binder/binder_transaction/enable" },
182 { REQ, "events/binder/binder_transaction_received/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700183 } },
184 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800185 { OPT, "events/binder/binder_lock/enable" },
186 { OPT, "events/binder/binder_locked/enable" },
187 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700188 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200189 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800190 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200191 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800192};
193
194/* Command line options */
195static int g_traceDurationSeconds = 5;
196static bool g_traceOverwrite = false;
197static int g_traceBufferSizeKB = 2048;
198static bool g_compress = false;
199static bool g_nohup = false;
200static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900201static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700202static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700203static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700204static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800205
206/* Global state */
207static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700208static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800209static std::string g_traceFolder;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800210
211/* Sys file paths */
212static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800213 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800214
215static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800216 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800217
218static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800219 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800220
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700221static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800222 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700223
224static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800225 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700226
227static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800228 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700229
230static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800231 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700232
233static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800234 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700235
236static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800237 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700238
239static const char* k_funcgraphDurationPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800240 "options/funcgraph-duration";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700241
242static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800243 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700244
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800245static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800246 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800247
248static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800249 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800250
Martijn Coenend9535872015-11-26 10:00:55 +0100251static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800252 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100253
John Reck469a1942015-03-26 15:31:35 -0700254static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800255 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700256
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800257// Check whether a file exists.
258static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800259 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800260}
261
262// Check whether a file is writable.
263static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800264 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800265}
266
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700267// Truncate a file.
268static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800269{
Jamie Gennis43122e72013-03-21 14:06:31 -0700270 // This uses creat rather than truncate because some of the debug kernel
271 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
272 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800273 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700274 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800275 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700276 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700277 return false;
278 }
279
Jamie Gennis43122e72013-03-21 14:06:31 -0700280 close(traceFD);
281
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700282 return true;
283}
284
285static bool _writeStr(const char* filename, const char* str, int flags)
286{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800287 std::string fullFilename = g_traceFolder + filename;
288 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800289 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800290 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800291 strerror(errno), errno);
292 return false;
293 }
294
295 bool ok = true;
296 ssize_t len = strlen(str);
297 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800298 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800299 strerror(errno), errno);
300 ok = false;
301 }
302
303 close(fd);
304
305 return ok;
306}
307
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700308// Write a string to a file, returning true if the write was successful.
309static bool writeStr(const char* filename, const char* str)
310{
311 return _writeStr(filename, str, O_WRONLY);
312}
313
314// Append a string to a file, returning true if the write was successful.
315static bool appendStr(const char* filename, const char* str)
316{
317 return _writeStr(filename, str, O_APPEND|O_WRONLY);
318}
319
John Reck469a1942015-03-26 15:31:35 -0700320static void writeClockSyncMarker()
321{
322 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200323 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800324 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200325 if (fd == -1) {
326 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
327 strerror(errno), errno);
328 return;
329 }
John Reck469a1942015-03-26 15:31:35 -0700330 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200331
332 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
333 if (write(fd, buffer, len) != len) {
334 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
335 }
336
337 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
338 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
339 if (write(fd, buffer, len) != len) {
340 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
341 }
342
343 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700344}
345
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800346// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
347// file.
348static bool setKernelOptionEnable(const char* filename, bool enable)
349{
350 return writeStr(filename, enable ? "1" : "0");
351}
352
353// Check whether the category is supported on the device with the current
354// rootness. A category is supported only if all its required /sys/ files are
355// writable and if enabling the category will enable one or more tracing tags
356// or /sys/ files.
357static bool isCategorySupported(const TracingCategory& category)
358{
sergeyvdb404152016-05-02 19:26:07 -0700359 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700360 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700361 }
362
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800363 bool ok = category.tags != 0;
364 for (int i = 0; i < MAX_SYS_FILES; i++) {
365 const char* path = category.sysfiles[i].path;
366 bool req = category.sysfiles[i].required == REQ;
367 if (path != NULL) {
368 if (req) {
369 if (!fileIsWritable(path)) {
370 return false;
371 } else {
372 ok = true;
373 }
374 } else {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800375 ok = true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800376 }
377 }
378 }
379 return ok;
380}
381
382// Check whether the category would be supported on the device if the user
383// were root. This function assumes that root is able to write to any file
384// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700385// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800386static bool isCategorySupportedForRoot(const TracingCategory& category)
387{
388 bool ok = category.tags != 0;
389 for (int i = 0; i < MAX_SYS_FILES; i++) {
390 const char* path = category.sysfiles[i].path;
391 bool req = category.sysfiles[i].required == REQ;
392 if (path != NULL) {
393 if (req) {
394 if (!fileExists(path)) {
395 return false;
396 } else {
397 ok = true;
398 }
399 } else {
400 ok |= fileExists(path);
401 }
402 }
403 }
404 return ok;
405}
406
407// Enable or disable overwriting of the kernel trace buffers. Disabling this
408// will cause tracing to stop once the trace buffers have filled up.
409static bool setTraceOverwriteEnable(bool enable)
410{
411 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
412}
413
414// Enable or disable kernel tracing.
415static bool setTracingEnabled(bool enable)
416{
417 return setKernelOptionEnable(k_tracingOnPath, enable);
418}
419
420// Clear the contents of the kernel trace.
421static bool clearTrace()
422{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700423 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800424}
425
426// Set the size of the kernel's trace buffer in kilobytes.
427static bool setTraceBufferSizeKB(int size)
428{
429 char str[32] = "1";
430 int len;
431 if (size < 1) {
432 size = 1;
433 }
434 snprintf(str, 32, "%d", size);
435 return writeStr(k_traceBufferSizePath, str);
436}
437
Colin Crossb1ce49b2014-08-20 14:28:47 -0700438// Read the trace_clock sysfs file and return true if it matches the requested
439// value. The trace_clock file format is:
440// local [global] counter uptime perf
441static bool isTraceClock(const char *mode)
442{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800443 int fd = open((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
Colin Crossb1ce49b2014-08-20 14:28:47 -0700444 if (fd == -1) {
445 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceClockPath,
446 strerror(errno), errno);
447 return false;
448 }
449
Carmen Jacksondc340972017-05-04 15:01:33 -0700450 char buf[4097];
451 ssize_t n = read(fd, buf, 4096);
Colin Crossb1ce49b2014-08-20 14:28:47 -0700452 close(fd);
453 if (n == -1) {
454 fprintf(stderr, "error reading %s: %s (%d)\n", k_traceClockPath,
455 strerror(errno), errno);
456 return false;
457 }
458 buf[n] = '\0';
459
460 char *start = strchr(buf, '[');
461 if (start == NULL) {
462 return false;
463 }
464 start++;
465
466 char *end = strchr(start, ']');
467 if (end == NULL) {
468 return false;
469 }
470 *end = '\0';
471
472 return strcmp(mode, start) == 0;
473}
474
Carmen Jacksondc340972017-05-04 15:01:33 -0700475// Enable or disable the kernel's use of the global clock. Disabling the global
476// clock will result in the kernel using a per-CPU local clock.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700477// Any write to the trace_clock sysfs file will reset the buffer, so only
478// update it if the requested value is not the current value.
Carmen Jacksondc340972017-05-04 15:01:33 -0700479static bool setGlobalClockEnable(bool enable)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800480{
Carmen Jacksondc340972017-05-04 15:01:33 -0700481 const char *clock = enable ? "global" : "local";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700482
483 if (isTraceClock(clock)) {
484 return true;
485 }
486
487 return writeStr(k_traceClockPath, clock);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800488}
489
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700490static bool setPrintTgidEnableIfPresent(bool enable)
491{
492 if (fileExists(k_printTgidPath)) {
493 return setKernelOptionEnable(k_printTgidPath, enable);
494 }
495 return true;
496}
497
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800498// Poke all the binder-enabled processes in the system to get them to re-read
499// their system properties.
500static bool pokeBinderServices()
501{
502 sp<IServiceManager> sm = defaultServiceManager();
503 Vector<String16> services = sm->listServices();
504 for (size_t i = 0; i < services.size(); i++) {
505 sp<IBinder> obj = sm->checkService(services[i]);
506 if (obj != NULL) {
507 Parcel data;
508 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
509 NULL, 0) != OK) {
510 if (false) {
511 // XXX: For some reason this fails on tablets trying to
512 // poke the "phone" service. It's not clear whether some
513 // are expected to fail.
514 String8 svc(services[i]);
515 fprintf(stderr, "error poking binder service %s\n",
516 svc.string());
517 return false;
518 }
519 }
520 }
521 }
522 return true;
523}
524
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100525// Poke all the HAL processes in the system to get them to re-read
526// their system properties.
527static void pokeHalServices()
528{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100529 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100530 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100531 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100532 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100533
534 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800535
536 if (sm == nullptr) {
537 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
538 return;
539 }
540
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800541 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100542 for (size_t i = 0; i < interfaces.size(); i++) {
543 string fqInstanceName = interfaces[i];
544 string::size_type n = fqInstanceName.find("/");
545 if (n == std::string::npos || interfaces[i].size() == n+1)
546 continue;
547 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
548 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100549 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
550 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100551 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100552 continue;
553 }
Carmen Jackson73206122017-04-18 15:37:57 -0700554
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100555 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700556 if (interface == nullptr) {
557 // ignore
558 continue;
559 }
560
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100561 auto notifyRet = interface->notifySyspropsChanged();
562 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100563 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800564 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100565 }
566 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800567 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100568 // TODO(b/34242478) fix this when we determine the correct ACL
569 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800570 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100571}
572
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800573// Set the trace tags that userland tracing uses, and poke the running
574// processes to pick up the new value.
575static bool setTagsProperty(uint64_t tags)
576{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700577 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
578 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800579 fprintf(stderr, "error setting trace tags system property\n");
580 return false;
581 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700582 return true;
583}
584
sergeyv4144eff2016-04-28 11:40:04 -0700585static void clearAppProperties()
586{
sergeyv4144eff2016-04-28 11:40:04 -0700587 for (int i = 0; i < MAX_PACKAGES; i++) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700588 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
589 if (!android::base::SetProperty(key, "")) {
590 fprintf(stderr, "failed to clear system property: %s\n", key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700591 }
592 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700593 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700594 fprintf(stderr, "failed to clear system property: %s",
595 k_traceAppsNumberProperty);
596 }
597}
598
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700599// Set the system property that indicates which apps should perform
600// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700601static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700602{
sergeyv4144eff2016-04-28 11:40:04 -0700603 int i = 0;
Dan Austin09a79872016-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 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700616 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
617 if (!android::base::SetProperty(key, start)) {
618 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700619 clearAppProperties();
620 return false;
621 }
622 start = end;
623 i++;
624 }
625
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700626 std::string value = android::base::StringPrintf("%d", i);
627 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
628 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700629 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;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700638 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800639 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;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800655 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100656 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{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700726 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900727 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);
Carmen Jacksondc340972017-05-04 15:01:33 -0700780 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;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700786 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800787 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;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700795 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700796 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) {
sergeyvdb404152016-05-02 19:26:07 -0700803 if (!packageList.empty()) {
804 packageList += ",";
805 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700806 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700807 }
Dan Austin09a79872016-05-31 13:27:03 -0700808 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700809 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100810 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800811
812 // Disable all the sysfs enables. This is done as a separate loop from
813 // the enables to allow the same enable to exist in multiple categories.
814 ok &= disableKernelTraceEvents();
815
816 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700817 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800818 if (g_categoryEnables[i]) {
819 const TracingCategory &c = k_categories[i];
820 for (int j = 0; j < MAX_SYS_FILES; j++) {
821 const char* path = c.sysfiles[j].path;
822 bool required = c.sysfiles[j].required == REQ;
823 if (path != NULL) {
824 if (fileIsWritable(path)) {
825 ok &= setKernelOptionEnable(path, true);
826 } else if (required) {
827 fprintf(stderr, "error writing file %s\n", path);
828 ok = false;
829 }
830 }
831 }
832 }
833 }
834
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800835 return ok;
836}
837
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700838// Reset all the kernel tracing settings to their default state.
839static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800840{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800841 // Disable all tracing that we're able to.
842 disableKernelTraceEvents();
843
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700844 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800845 setTagsProperty(0);
sergeyv4144eff2016-04-28 11:40:04 -0700846 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700847 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800848
849 // Set the options back to their defaults.
850 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700851 setTraceBufferSizeKB(1);
Carmen Jacksondc340972017-05-04 15:01:33 -0700852 setGlobalClockEnable(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700853 setPrintTgidEnableIfPresent(false);
854 setKernelTraceFuncs(NULL);
855}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800856
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700857
858// Enable tracing in the kernel.
859static bool startTrace()
860{
861 return setTracingEnabled(true);
862}
863
864// Disable tracing in the kernel.
865static void stopTrace()
866{
867 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800868}
869
Martijn Coenend9535872015-11-26 10:00:55 +0100870// Read data from the tracing pipe and forward to stdout
871static void streamTrace()
872{
873 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800874 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100875 if (traceFD == -1) {
876 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
877 strerror(errno), errno);
878 return;
879 }
880 while (!g_traceAborted) {
881 ssize_t bytes_read = read(traceFD, trace_data, 4096);
882 if (bytes_read > 0) {
883 write(STDOUT_FILENO, trace_data, bytes_read);
884 fflush(stdout);
885 } else {
886 if (!g_traceAborted) {
887 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
888 bytes_read, errno, strerror(errno));
889 }
890 break;
891 }
892 }
893}
894
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800895// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700896static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800897{
John Reck6c8ac922016-03-28 11:25:30 -0700898 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800899 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800900 if (traceFD == -1) {
901 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
902 strerror(errno), errno);
903 return;
904 }
905
906 if (g_compress) {
907 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800908 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700909
910 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800911 if (result != Z_OK) {
912 fprintf(stderr, "error initializing zlib: %d\n", result);
913 close(traceFD);
914 return;
915 }
916
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700917 constexpr size_t bufSize = 64*1024;
918 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
919 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
920 if (!in || !out) {
921 fprintf(stderr, "couldn't allocate buffers\n");
922 close(traceFD);
923 return;
924 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800925
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700926 int flush = Z_NO_FLUSH;
927
928 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800929 zs.avail_out = bufSize;
930
931 do {
932
933 if (zs.avail_in == 0) {
934 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700935 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800936 if (result < 0) {
937 fprintf(stderr, "error reading trace: %s (%d)\n",
938 strerror(errno), errno);
939 result = Z_STREAM_END;
940 break;
941 } else if (result == 0) {
942 flush = Z_FINISH;
943 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700944 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800945 zs.avail_in = result;
946 }
947 }
948
949 if (zs.avail_out == 0) {
950 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700951 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800952 if ((size_t)result < bufSize) {
953 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
954 strerror(errno), errno);
955 result = Z_STREAM_END; // skip deflate error message
956 zs.avail_out = bufSize; // skip the final write
957 break;
958 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700959 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800960 zs.avail_out = bufSize;
961 }
962
963 } while ((result = deflate(&zs, flush)) == Z_OK);
964
965 if (result != Z_STREAM_END) {
966 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
967 }
968
969 if (zs.avail_out < bufSize) {
970 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -0700971 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800972 if ((size_t)result < bytes) {
973 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
974 strerror(errno), errno);
975 }
976 }
977
978 result = deflateEnd(&zs);
979 if (result != Z_OK) {
980 fprintf(stderr, "error cleaning up zlib: %d\n", result);
981 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800982 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -0700983 char buf[4096];
984 ssize_t rc;
985 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
986 if (!android::base::WriteFully(outFd, buf, rc)) {
987 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
988 break;
989 }
990 }
991 if (rc == -1) {
992 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800993 }
994 }
995
996 close(traceFD);
997}
998
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700999static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001000{
1001 if (!g_nohup) {
1002 g_traceAborted = true;
1003 }
1004}
1005
1006static void registerSigHandler()
1007{
1008 struct sigaction sa;
1009 sigemptyset(&sa.sa_mask);
1010 sa.sa_flags = 0;
1011 sa.sa_handler = handleSignal;
1012 sigaction(SIGHUP, &sa, NULL);
1013 sigaction(SIGINT, &sa, NULL);
1014 sigaction(SIGQUIT, &sa, NULL);
1015 sigaction(SIGTERM, &sa, NULL);
1016}
1017
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001018static void listSupportedCategories()
1019{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001020 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001021 const TracingCategory& c = k_categories[i];
1022 if (isCategorySupported(c)) {
1023 printf(" %10s - %s\n", c.name, c.longname);
1024 }
1025 }
1026}
1027
1028// Print the command usage help to stderr.
1029static void showHelp(const char *cmd)
1030{
1031 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1032 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001033 " -a appname enable app-level tracing for a comma "
1034 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001035 " -b N use a trace buffer size of N KB\n"
1036 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001037 " -f filename use the categories written in a file as space-separated\n"
1038 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001039 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001040 " -n ignore signals\n"
1041 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001042 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001043 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001044 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001045 " --async_dump dump the current contents of circular trace buffer\n"
1046 " --async_stop stop tracing and dump the current contents of circular\n"
1047 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001048 " --stream stream trace to stdout as it enters the trace buffer\n"
1049 " Note: this can take significant CPU time, and is best\n"
1050 " used for measuring things that are not affected by\n"
1051 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001052 " --list_categories\n"
1053 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001054 " -o filename write the trace to the specified file instead\n"
1055 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001056 );
1057}
1058
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001059bool findTraceFiles()
1060{
1061 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1062 static const std::string tracefs_path = "/sys/kernel/tracing/";
1063 static const std::string trace_file = "trace_marker";
1064
1065 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1066 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1067
1068 if (!tracefs && !debugfs) {
1069 fprintf(stderr, "Error: Did not find trace folder\n");
1070 return false;
1071 }
1072
1073 if (tracefs) {
1074 g_traceFolder = tracefs_path;
1075 } else {
1076 g_traceFolder = debugfs_path;
1077 }
1078
1079 return true;
1080}
1081
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001082int main(int argc, char **argv)
1083{
1084 bool async = false;
1085 bool traceStart = true;
1086 bool traceStop = true;
1087 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001088 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001089
1090 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1091 showHelp(argv[0]);
1092 exit(0);
1093 }
1094
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001095 if (!findTraceFiles()) {
1096 fprintf(stderr, "No trace folder found\n");
1097 exit(-1);
1098 }
1099
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001100 for (;;) {
1101 int ret;
1102 int option_index = 0;
1103 static struct option long_options[] = {
1104 {"async_start", no_argument, 0, 0 },
1105 {"async_stop", no_argument, 0, 0 },
1106 {"async_dump", no_argument, 0, 0 },
1107 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +01001108 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001109 { 0, 0, 0, 0 }
1110 };
1111
John Reck40b26b42016-03-30 09:44:36 -07001112 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001113 long_options, &option_index);
1114
1115 if (ret < 0) {
1116 for (int i = optind; i < argc; i++) {
1117 if (!setCategoryEnable(argv[i], true)) {
1118 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1119 exit(1);
1120 }
1121 }
1122 break;
1123 }
1124
1125 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001126 case 'a':
1127 g_debugAppCmdLine = optarg;
1128 break;
1129
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001130 case 'b':
1131 g_traceBufferSizeKB = atoi(optarg);
1132 break;
1133
1134 case 'c':
1135 g_traceOverwrite = true;
1136 break;
1137
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001138 case 'f':
1139 g_categoriesFile = optarg;
1140 break;
1141
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001142 case 'k':
1143 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001144 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001145
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001146 case 'n':
1147 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001148 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001149
1150 case 's':
1151 g_initialSleepSecs = atoi(optarg);
1152 break;
1153
1154 case 't':
1155 g_traceDurationSeconds = atoi(optarg);
1156 break;
1157
1158 case 'z':
1159 g_compress = true;
1160 break;
1161
John Reck40b26b42016-03-30 09:44:36 -07001162 case 'o':
1163 g_outputFile = optarg;
1164 break;
1165
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001166 case 0:
1167 if (!strcmp(long_options[option_index].name, "async_start")) {
1168 async = true;
1169 traceStop = false;
1170 traceDump = false;
1171 g_traceOverwrite = true;
1172 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1173 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001174 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001175 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1176 async = true;
1177 traceStart = false;
1178 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001179 } else if (!strcmp(long_options[option_index].name, "stream")) {
1180 traceStream = true;
1181 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001182 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1183 listSupportedCategories();
1184 exit(0);
1185 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001186 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001187
1188 default:
1189 fprintf(stderr, "\n");
1190 showHelp(argv[0]);
1191 exit(-1);
1192 break;
1193 }
1194 }
1195
1196 registerSigHandler();
1197
1198 if (g_initialSleepSecs > 0) {
1199 sleep(g_initialSleepSecs);
1200 }
1201
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001202 bool ok = true;
1203 ok &= setUpTrace();
1204 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001205
1206 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001207 if (!traceStream) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001208 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001209 fflush(stdout);
1210 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001211
1212 // We clear the trace after starting it because tracing gets enabled for
1213 // each CPU individually in the kernel. Having the beginning of the trace
1214 // contain entries from only one CPU can cause "begin" entries without a
1215 // matching "end" entry to show up if a task gets migrated from one CPU to
1216 // another.
1217 ok = clearTrace();
1218
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001219 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001220 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001221 // Sleep to allow the trace to be captured.
1222 struct timespec timeLeft;
1223 timeLeft.tv_sec = g_traceDurationSeconds;
1224 timeLeft.tv_nsec = 0;
1225 do {
1226 if (g_traceAborted) {
1227 break;
1228 }
1229 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1230 }
Martijn Coenend9535872015-11-26 10:00:55 +01001231
1232 if (traceStream) {
1233 streamTrace();
1234 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001235 }
1236
1237 // Stop the trace and restore the default settings.
1238 if (traceStop)
1239 stopTrace();
1240
1241 if (ok && traceDump) {
1242 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001243 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001244 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001245 int outFd = STDOUT_FILENO;
1246 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001247 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001248 }
1249 if (outFd == -1) {
1250 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1251 } else {
1252 dprintf(outFd, "TRACE:\n");
1253 dumpTrace(outFd);
1254 if (g_outputFile) {
1255 close(outFd);
1256 }
1257 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001258 } else {
1259 printf("\ntrace aborted.\n");
1260 fflush(stdout);
1261 }
1262 clearTrace();
1263 } else if (!ok) {
1264 fprintf(stderr, "unable to start tracing\n");
1265 }
1266
1267 // Reset the trace buffer size to 1.
1268 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001269 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001270
1271 return g_traceAborted ? 1 : 0;
1272}