blob: 58133784a913edb7837d67855408c3b4cc478f73 [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
Corey Tabakaf70680e2017-04-14 17:52:17 -070042#include <pdx/default_transport/service_utility.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080043#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;
Corey Tabakaf70680e2017-04-14 17:52:17 -070053using pdx::default_transport::ServiceUtility;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080054
Martijn Coenenee9b97e2016-11-16 16:00:26 +010055using std::string;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080056
sergeyv4144eff2016-04-28 11:40:04 -070057#define MAX_SYS_FILES 10
58#define MAX_PACKAGES 16
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080059
60const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
sergeyv4144eff2016-04-28 11:40:04 -070061
62const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
63const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070064const char* k_coreServiceCategory = "core_services";
65const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080066
67typedef enum { OPT, REQ } requiredness ;
68
69struct TracingCategory {
70 // The name identifying the category.
71 const char* name;
72
73 // A longer description of the category.
74 const char* longname;
75
76 // The userland tracing tags that the category enables.
77 uint64_t tags;
78
79 // The fname==NULL terminated list of /sys/ files that the category
80 // enables.
81 struct {
82 // Whether the file must be writable in order to enable the tracing
83 // category.
84 requiredness required;
85
86 // The path to the enable file.
87 const char* path;
88 } sysfiles[MAX_SYS_FILES];
89};
90
91/* Tracing categories */
92static const TracingCategory k_categories[] = {
Jamie Gennisb2a89e32013-03-11 19:37:53 -070093 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, { } },
94 { "input", "Input", ATRACE_TAG_INPUT, { } },
95 { "view", "View System", ATRACE_TAG_VIEW, { } },
96 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
97 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
98 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -050099 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700100 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
101 { "video", "Video", ATRACE_TAG_VIDEO, { } },
102 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
103 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700104 { "app", "Application", ATRACE_TAG_APP, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -0700105 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -0700106 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -0700107 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -0700108 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700109 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 14:36:20 -0700110 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-07-01 01:46:25 +0900111 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Greg Hackmannbbd7d992014-12-01 14:43:34 -0800112 { "database", "Database", ATRACE_TAG_DATABASE, { } },
Felipe Leme0f97c1d2016-09-07 11:33:26 -0700113 { "network", "Network", ATRACE_TAG_NETWORK, { } },
Josh Gao468b4cb2016-11-29 10:55:21 -0800114 { "adb", "ADB", ATRACE_TAG_ADB, { } },
sergeyvdb404152016-05-02 19:26:07 -0700115 { k_coreServiceCategory, "Core services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700116 { "sched", "CPU Scheduling", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800117 { REQ, "events/sched/sched_switch/enable" },
118 { REQ, "events/sched/sched_wakeup/enable" },
119 { OPT, "events/sched/sched_blocked_reason/enable" },
120 { OPT, "events/sched/sched_cpu_hotplug/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800121 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700122 { "irq", "IRQ Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800123 { REQ, "events/irq/enable" },
124 { OPT, "events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700125 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100126 { "i2c", "I2C Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800127 { REQ, "events/i2c/enable" },
128 { REQ, "events/i2c/i2c_read/enable" },
129 { REQ, "events/i2c/i2c_write/enable" },
130 { REQ, "events/i2c/i2c_result/enable" },
131 { REQ, "events/i2c/i2c_reply/enable" },
132 { OPT, "events/i2c/smbus_read/enable" },
133 { OPT, "events/i2c/smbus_write/enable" },
134 { OPT, "events/i2c/smbus_result/enable" },
135 { OPT, "events/i2c/smbus_reply/enable" },
Michael Wright43fb6782016-08-18 19:56:43 +0100136 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700137 { "freq", "CPU Frequency", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800138 { REQ, "events/power/cpu_frequency/enable" },
139 { OPT, "events/power/clock_set_rate/enable" },
140 { OPT, "events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800141 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700142 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800143 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800144 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700145 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800146 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800147 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700148 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800149 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
150 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
151 { OPT, "events/f2fs/f2fs_write_begin/enable" },
152 { OPT, "events/f2fs/f2fs_write_end/enable" },
153 { OPT, "events/ext4/ext4_da_write_begin/enable" },
154 { OPT, "events/ext4/ext4_da_write_end/enable" },
155 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
156 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
157 { REQ, "events/block/block_rq_issue/enable" },
158 { REQ, "events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800159 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700160 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800161 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700162 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700163 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800164 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800165 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700166 { "sync", "Synchronization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800167 { REQ, "events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800168 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700169 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800170 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800171 } },
Colin Cross580407f2014-08-18 15:22:13 -0700172 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800173 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
174 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
175 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
176 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/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, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800186 { REQ, "events/binder/binder_lock/enable" },
187 { REQ, "events/binder/binder_locked/enable" },
188 { REQ, "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 {
376 ok |= fileIsWritable(path);
377 }
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
Colin Crossb1ce49b2014-08-20 14:28:47 -0700439// Read the trace_clock sysfs file and return true if it matches the requested
440// value. The trace_clock file format is:
441// local [global] counter uptime perf
442static bool isTraceClock(const char *mode)
443{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800444 int fd = open((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
Colin Crossb1ce49b2014-08-20 14:28:47 -0700445 if (fd == -1) {
446 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceClockPath,
447 strerror(errno), errno);
448 return false;
449 }
450
Carmen Jackson56a2ba02017-04-28 10:34:50 -0700451 char buf[100];
452 ssize_t n = read(fd, buf, 99);
Colin Crossb1ce49b2014-08-20 14:28:47 -0700453 close(fd);
454 if (n == -1) {
455 fprintf(stderr, "error reading %s: %s (%d)\n", k_traceClockPath,
456 strerror(errno), errno);
457 return false;
458 }
459 buf[n] = '\0';
460
461 char *start = strchr(buf, '[');
462 if (start == NULL) {
463 return false;
464 }
465 start++;
466
467 char *end = strchr(start, ']');
468 if (end == NULL) {
469 return false;
470 }
471 *end = '\0';
472
473 return strcmp(mode, start) == 0;
474}
475
Carmen Jackson56a2ba02017-04-28 10:34:50 -0700476// Read the trace_clock sysfs file and return true if it contains the requested
477// value. The trace_clock file format is:
478// local [global] counter uptime perf
479static bool traceClockContains(const char *mode)
480{
481 int fd = open((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
482 if (fd == -1) {
483 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceClockPath,
484 strerror(errno), errno);
485 return false;
486 }
487
488 char buf[100];
489 ssize_t n = read(fd, buf, 99);
490 close(fd);
491 if (n == -1) {
492 fprintf(stderr, "error reading %s: %s (%d)\n", k_traceClockPath,
493 strerror(errno), errno);
494 return false;
495 }
496 buf[n] = '\0';
497
498 return strstr(buf, mode) != NULL;
499}
500
501// Set the clock to the best available option while tracing. Use 'boot' if it's
502// available; otherwise, use 'mono'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700503// Any write to the trace_clock sysfs file will reset the buffer, so only
504// update it if the requested value is not the current value.
Carmen Jackson56a2ba02017-04-28 10:34:50 -0700505static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800506{
Carmen Jackson56a2ba02017-04-28 10:34:50 -0700507 const char* clock = traceClockContains("boot") ? "boot" : "mono";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700508
509 if (isTraceClock(clock)) {
510 return true;
511 }
512
513 return writeStr(k_traceClockPath, clock);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800514}
515
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700516static bool setPrintTgidEnableIfPresent(bool enable)
517{
518 if (fileExists(k_printTgidPath)) {
519 return setKernelOptionEnable(k_printTgidPath, enable);
520 }
521 return true;
522}
523
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800524// Poke all the binder-enabled processes in the system to get them to re-read
525// their system properties.
526static bool pokeBinderServices()
527{
528 sp<IServiceManager> sm = defaultServiceManager();
529 Vector<String16> services = sm->listServices();
530 for (size_t i = 0; i < services.size(); i++) {
531 sp<IBinder> obj = sm->checkService(services[i]);
532 if (obj != NULL) {
533 Parcel data;
534 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
535 NULL, 0) != OK) {
536 if (false) {
537 // XXX: For some reason this fails on tablets trying to
538 // poke the "phone" service. It's not clear whether some
539 // are expected to fail.
540 String8 svc(services[i]);
541 fprintf(stderr, "error poking binder service %s\n",
542 svc.string());
543 return false;
544 }
545 }
546 }
547 }
548 return true;
549}
550
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100551// Poke all the HAL processes in the system to get them to re-read
552// their system properties.
553static void pokeHalServices()
554{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100555 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100556 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100557 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100558 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100559
560 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800561
562 if (sm == nullptr) {
563 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
564 return;
565 }
566
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800567 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100568 for (size_t i = 0; i < interfaces.size(); i++) {
569 string fqInstanceName = interfaces[i];
570 string::size_type n = fqInstanceName.find("/");
571 if (n == std::string::npos || interfaces[i].size() == n+1)
572 continue;
573 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
574 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100575 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
576 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100577 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100578 continue;
579 }
Carmen Jackson73206122017-04-18 15:37:57 -0700580
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100581 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700582 if (interface == nullptr) {
583 // ignore
584 continue;
585 }
586
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100587 auto notifyRet = interface->notifySyspropsChanged();
588 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100589 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800590 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100591 }
592 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800593 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100594 // TODO(b/34242478) fix this when we determine the correct ACL
595 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800596 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100597}
598
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800599// Set the trace tags that userland tracing uses, and poke the running
600// processes to pick up the new value.
601static bool setTagsProperty(uint64_t tags)
602{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700603 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
604 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800605 fprintf(stderr, "error setting trace tags system property\n");
606 return false;
607 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700608 return true;
609}
610
sergeyv4144eff2016-04-28 11:40:04 -0700611static void clearAppProperties()
612{
sergeyv4144eff2016-04-28 11:40:04 -0700613 for (int i = 0; i < MAX_PACKAGES; i++) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700614 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
615 if (!android::base::SetProperty(key, "")) {
616 fprintf(stderr, "failed to clear system property: %s\n", key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700617 }
618 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700619 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700620 fprintf(stderr, "failed to clear system property: %s",
621 k_traceAppsNumberProperty);
622 }
623}
624
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700625// Set the system property that indicates which apps should perform
626// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700627static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700628{
sergeyv4144eff2016-04-28 11:40:04 -0700629 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700630 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700631 while (start != NULL) {
632 if (i == MAX_PACKAGES) {
633 fprintf(stderr, "error: only 16 packages could be traced at once\n");
634 clearAppProperties();
635 return false;
636 }
637 char* end = strchr(start, ',');
638 if (end != NULL) {
639 *end = '\0';
640 end++;
641 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700642 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
643 if (!android::base::SetProperty(key, start)) {
644 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700645 clearAppProperties();
646 return false;
647 }
648 start = end;
649 i++;
650 }
651
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700652 std::string value = android::base::StringPrintf("%d", i);
653 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
654 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700655 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700656 return false;
657 }
658 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800659}
660
661// Disable all /sys/ enable files.
662static bool disableKernelTraceEvents() {
663 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700664 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800665 const TracingCategory &c = k_categories[i];
666 for (int j = 0; j < MAX_SYS_FILES; j++) {
667 const char* path = c.sysfiles[j].path;
668 if (path != NULL && fileIsWritable(path)) {
669 ok &= setKernelOptionEnable(path, false);
670 }
671 }
672 }
673 return ok;
674}
675
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700676// Verify that the comma separated list of functions are being traced by the
677// kernel.
678static bool verifyKernelTraceFuncs(const char* funcs)
679{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100680 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800681 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100682 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700683 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100684 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700685 }
686
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100687 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700688
689 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100690 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700691 bool ok = true;
692 char* myFuncs = strdup(funcs);
693 char* func = strtok(myFuncs, ",");
694 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100695 if (!strchr(func, '*')) {
696 String8 fancyFunc = String8::format("\n%s\n", func);
697 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
698 if (!found || func[0] == '\0') {
699 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
700 "to trace.\n", func);
701 ok = false;
702 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700703 }
704 func = strtok(NULL, ",");
705 }
706 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700707 return ok;
708}
709
710// Set the comma separated list of functions that the kernel is to trace.
711static bool setKernelTraceFuncs(const char* funcs)
712{
713 bool ok = true;
714
715 if (funcs == NULL || funcs[0] == '\0') {
716 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700717 if (fileIsWritable(k_currentTracerPath)) {
718 ok &= writeStr(k_currentTracerPath, "nop");
719 }
720 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700721 ok &= truncateFile(k_ftraceFilterPath);
722 }
723 } else {
724 // Enable kernel function tracing.
725 ok &= writeStr(k_currentTracerPath, "function_graph");
726 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
727 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
728 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
729 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
730
731 // Set the requested filter functions.
732 ok &= truncateFile(k_ftraceFilterPath);
733 char* myFuncs = strdup(funcs);
734 char* func = strtok(myFuncs, ",");
735 while (func) {
736 ok &= appendStr(k_ftraceFilterPath, func);
737 func = strtok(NULL, ",");
738 }
739 free(myFuncs);
740
741 // Verify that the set functions are being traced.
742 if (ok) {
743 ok &= verifyKernelTraceFuncs(funcs);
744 }
745 }
746
747 return ok;
748}
749
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900750static bool setCategoryEnable(const char* name, bool enable)
751{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700752 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900753 const TracingCategory& c = k_categories[i];
754 if (strcmp(name, c.name) == 0) {
755 if (isCategorySupported(c)) {
756 g_categoryEnables[i] = enable;
757 return true;
758 } else {
759 if (isCategorySupportedForRoot(c)) {
760 fprintf(stderr, "error: category \"%s\" requires root "
761 "privileges.\n", name);
762 } else {
763 fprintf(stderr, "error: category \"%s\" is not supported "
764 "on this device.\n", name);
765 }
766 return false;
767 }
768 }
769 }
770 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
771 return false;
772}
773
774static bool setCategoriesEnableFromFile(const char* categories_file)
775{
776 if (!categories_file) {
777 return true;
778 }
779 Tokenizer* tokenizer = NULL;
780 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
781 return false;
782 }
783 bool ok = true;
784 while (!tokenizer->isEol()) {
785 String8 token = tokenizer->nextToken(" ");
786 if (token.isEmpty()) {
787 tokenizer->skipDelimiters(" ");
788 continue;
789 }
790 ok &= setCategoryEnable(token.string(), true);
791 }
792 delete tokenizer;
793 return ok;
794}
795
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700796// Set all the kernel tracing settings to the desired state for this trace
797// capture.
798static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800799{
800 bool ok = true;
801
802 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900803 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800804 ok &= setTraceOverwriteEnable(g_traceOverwrite);
805 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
Carmen Jackson56a2ba02017-04-28 10:34:50 -0700806 ok &= setClock();
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700807 ok &= setPrintTgidEnableIfPresent(true);
808 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800809
810 // Set up the tags property.
811 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700812 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800813 if (g_categoryEnables[i]) {
814 const TracingCategory &c = k_categories[i];
815 tags |= c.tags;
816 }
817 }
818 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700819
820 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700821 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700822 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
823 coreServicesTagEnabled = g_categoryEnables[i];
824 }
825 }
826
827 std::string packageList(g_debugAppCmdLine);
828 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700829 if (!packageList.empty()) {
830 packageList += ",";
831 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700832 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700833 }
Dan Austin09a79872016-05-31 13:27:03 -0700834 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700835 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100836 pokeHalServices();
Corey Tabakaf70680e2017-04-14 17:52:17 -0700837 ok &= ServiceUtility::PokeServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800838
839 // Disable all the sysfs enables. This is done as a separate loop from
840 // the enables to allow the same enable to exist in multiple categories.
841 ok &= disableKernelTraceEvents();
842
843 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700844 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800845 if (g_categoryEnables[i]) {
846 const TracingCategory &c = k_categories[i];
847 for (int j = 0; j < MAX_SYS_FILES; j++) {
848 const char* path = c.sysfiles[j].path;
849 bool required = c.sysfiles[j].required == REQ;
850 if (path != NULL) {
851 if (fileIsWritable(path)) {
852 ok &= setKernelOptionEnable(path, true);
853 } else if (required) {
854 fprintf(stderr, "error writing file %s\n", path);
855 ok = false;
856 }
857 }
858 }
859 }
860 }
861
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800862 return ok;
863}
864
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700865// Reset all the kernel tracing settings to their default state.
866static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800867{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800868 // Disable all tracing that we're able to.
869 disableKernelTraceEvents();
870
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700871 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800872 setTagsProperty(0);
sergeyv4144eff2016-04-28 11:40:04 -0700873 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700874 pokeBinderServices();
Corey Tabakaf70680e2017-04-14 17:52:17 -0700875 ServiceUtility::PokeServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800876
877 // Set the options back to their defaults.
878 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700879 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700880 setPrintTgidEnableIfPresent(false);
881 setKernelTraceFuncs(NULL);
882}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800883
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700884
885// Enable tracing in the kernel.
886static bool startTrace()
887{
888 return setTracingEnabled(true);
889}
890
891// Disable tracing in the kernel.
892static void stopTrace()
893{
894 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800895}
896
Martijn Coenend9535872015-11-26 10:00:55 +0100897// Read data from the tracing pipe and forward to stdout
898static void streamTrace()
899{
900 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800901 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100902 if (traceFD == -1) {
903 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
904 strerror(errno), errno);
905 return;
906 }
907 while (!g_traceAborted) {
908 ssize_t bytes_read = read(traceFD, trace_data, 4096);
909 if (bytes_read > 0) {
910 write(STDOUT_FILENO, trace_data, bytes_read);
911 fflush(stdout);
912 } else {
913 if (!g_traceAborted) {
914 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
915 bytes_read, errno, strerror(errno));
916 }
917 break;
918 }
919 }
920}
921
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800922// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700923static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800924{
John Reck6c8ac922016-03-28 11:25:30 -0700925 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800926 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800927 if (traceFD == -1) {
928 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
929 strerror(errno), errno);
930 return;
931 }
932
933 if (g_compress) {
934 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800935 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700936
937 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800938 if (result != Z_OK) {
939 fprintf(stderr, "error initializing zlib: %d\n", result);
940 close(traceFD);
941 return;
942 }
943
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700944 constexpr size_t bufSize = 64*1024;
945 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
946 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
947 if (!in || !out) {
948 fprintf(stderr, "couldn't allocate buffers\n");
949 close(traceFD);
950 return;
951 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800952
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700953 int flush = Z_NO_FLUSH;
954
955 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800956 zs.avail_out = bufSize;
957
958 do {
959
960 if (zs.avail_in == 0) {
961 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700962 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800963 if (result < 0) {
964 fprintf(stderr, "error reading trace: %s (%d)\n",
965 strerror(errno), errno);
966 result = Z_STREAM_END;
967 break;
968 } else if (result == 0) {
969 flush = Z_FINISH;
970 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700971 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800972 zs.avail_in = result;
973 }
974 }
975
976 if (zs.avail_out == 0) {
977 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700978 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800979 if ((size_t)result < bufSize) {
980 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
981 strerror(errno), errno);
982 result = Z_STREAM_END; // skip deflate error message
983 zs.avail_out = bufSize; // skip the final write
984 break;
985 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700986 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800987 zs.avail_out = bufSize;
988 }
989
990 } while ((result = deflate(&zs, flush)) == Z_OK);
991
992 if (result != Z_STREAM_END) {
993 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
994 }
995
996 if (zs.avail_out < bufSize) {
997 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -0700998 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800999 if ((size_t)result < bytes) {
1000 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1001 strerror(errno), errno);
1002 }
1003 }
1004
1005 result = deflateEnd(&zs);
1006 if (result != Z_OK) {
1007 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1008 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001009 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001010 char buf[4096];
1011 ssize_t rc;
1012 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1013 if (!android::base::WriteFully(outFd, buf, rc)) {
1014 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1015 break;
1016 }
1017 }
1018 if (rc == -1) {
1019 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001020 }
1021 }
1022
1023 close(traceFD);
1024}
1025
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001026static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001027{
1028 if (!g_nohup) {
1029 g_traceAborted = true;
1030 }
1031}
1032
1033static void registerSigHandler()
1034{
1035 struct sigaction sa;
1036 sigemptyset(&sa.sa_mask);
1037 sa.sa_flags = 0;
1038 sa.sa_handler = handleSignal;
1039 sigaction(SIGHUP, &sa, NULL);
1040 sigaction(SIGINT, &sa, NULL);
1041 sigaction(SIGQUIT, &sa, NULL);
1042 sigaction(SIGTERM, &sa, NULL);
1043}
1044
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001045static void listSupportedCategories()
1046{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001047 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001048 const TracingCategory& c = k_categories[i];
1049 if (isCategorySupported(c)) {
1050 printf(" %10s - %s\n", c.name, c.longname);
1051 }
1052 }
1053}
1054
1055// Print the command usage help to stderr.
1056static void showHelp(const char *cmd)
1057{
1058 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1059 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001060 " -a appname enable app-level tracing for a comma "
1061 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001062 " -b N use a trace buffer size of N KB\n"
1063 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001064 " -f filename use the categories written in a file as space-separated\n"
1065 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001066 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001067 " -n ignore signals\n"
1068 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001069 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001070 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001071 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001072 " --async_dump dump the current contents of circular trace buffer\n"
1073 " --async_stop stop tracing and dump the current contents of circular\n"
1074 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001075 " --stream stream trace to stdout as it enters the trace buffer\n"
1076 " Note: this can take significant CPU time, and is best\n"
1077 " used for measuring things that are not affected by\n"
1078 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001079 " --list_categories\n"
1080 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001081 " -o filename write the trace to the specified file instead\n"
1082 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001083 );
1084}
1085
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001086bool findTraceFiles()
1087{
1088 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1089 static const std::string tracefs_path = "/sys/kernel/tracing/";
1090 static const std::string trace_file = "trace_marker";
1091
1092 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1093 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1094
1095 if (!tracefs && !debugfs) {
1096 fprintf(stderr, "Error: Did not find trace folder\n");
1097 return false;
1098 }
1099
1100 if (tracefs) {
1101 g_traceFolder = tracefs_path;
1102 } else {
1103 g_traceFolder = debugfs_path;
1104 }
1105
1106 return true;
1107}
1108
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001109int main(int argc, char **argv)
1110{
1111 bool async = false;
1112 bool traceStart = true;
1113 bool traceStop = true;
1114 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001115 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001116
1117 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1118 showHelp(argv[0]);
1119 exit(0);
1120 }
1121
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001122 if (!findTraceFiles()) {
1123 fprintf(stderr, "No trace folder found\n");
1124 exit(-1);
1125 }
1126
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001127 for (;;) {
1128 int ret;
1129 int option_index = 0;
1130 static struct option long_options[] = {
1131 {"async_start", no_argument, 0, 0 },
1132 {"async_stop", no_argument, 0, 0 },
1133 {"async_dump", no_argument, 0, 0 },
1134 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +01001135 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001136 { 0, 0, 0, 0 }
1137 };
1138
John Reck40b26b42016-03-30 09:44:36 -07001139 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001140 long_options, &option_index);
1141
1142 if (ret < 0) {
1143 for (int i = optind; i < argc; i++) {
1144 if (!setCategoryEnable(argv[i], true)) {
1145 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1146 exit(1);
1147 }
1148 }
1149 break;
1150 }
1151
1152 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001153 case 'a':
1154 g_debugAppCmdLine = optarg;
1155 break;
1156
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001157 case 'b':
1158 g_traceBufferSizeKB = atoi(optarg);
1159 break;
1160
1161 case 'c':
1162 g_traceOverwrite = true;
1163 break;
1164
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001165 case 'f':
1166 g_categoriesFile = optarg;
1167 break;
1168
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001169 case 'k':
1170 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001171 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001172
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001173 case 'n':
1174 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001175 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001176
1177 case 's':
1178 g_initialSleepSecs = atoi(optarg);
1179 break;
1180
1181 case 't':
1182 g_traceDurationSeconds = atoi(optarg);
1183 break;
1184
1185 case 'z':
1186 g_compress = true;
1187 break;
1188
John Reck40b26b42016-03-30 09:44:36 -07001189 case 'o':
1190 g_outputFile = optarg;
1191 break;
1192
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001193 case 0:
1194 if (!strcmp(long_options[option_index].name, "async_start")) {
1195 async = true;
1196 traceStop = false;
1197 traceDump = false;
1198 g_traceOverwrite = true;
1199 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1200 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001201 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001202 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1203 async = true;
1204 traceStart = false;
1205 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001206 } else if (!strcmp(long_options[option_index].name, "stream")) {
1207 traceStream = true;
1208 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001209 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1210 listSupportedCategories();
1211 exit(0);
1212 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001213 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001214
1215 default:
1216 fprintf(stderr, "\n");
1217 showHelp(argv[0]);
1218 exit(-1);
1219 break;
1220 }
1221 }
1222
1223 registerSigHandler();
1224
1225 if (g_initialSleepSecs > 0) {
1226 sleep(g_initialSleepSecs);
1227 }
1228
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001229 bool ok = true;
1230 ok &= setUpTrace();
1231 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001232
1233 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001234 if (!traceStream) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001235 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001236 fflush(stdout);
1237 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001238
1239 // We clear the trace after starting it because tracing gets enabled for
1240 // each CPU individually in the kernel. Having the beginning of the trace
1241 // contain entries from only one CPU can cause "begin" entries without a
1242 // matching "end" entry to show up if a task gets migrated from one CPU to
1243 // another.
1244 ok = clearTrace();
1245
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001246 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001247 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001248 // Sleep to allow the trace to be captured.
1249 struct timespec timeLeft;
1250 timeLeft.tv_sec = g_traceDurationSeconds;
1251 timeLeft.tv_nsec = 0;
1252 do {
1253 if (g_traceAborted) {
1254 break;
1255 }
1256 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1257 }
Martijn Coenend9535872015-11-26 10:00:55 +01001258
1259 if (traceStream) {
1260 streamTrace();
1261 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001262 }
1263
1264 // Stop the trace and restore the default settings.
1265 if (traceStop)
1266 stopTrace();
1267
1268 if (ok && traceDump) {
1269 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001270 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001271 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001272 int outFd = STDOUT_FILENO;
1273 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001274 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001275 }
1276 if (outFd == -1) {
1277 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1278 } else {
1279 dprintf(outFd, "TRACE:\n");
1280 dumpTrace(outFd);
1281 if (g_outputFile) {
1282 close(outFd);
1283 }
1284 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001285 } else {
1286 printf("\ntrace aborted.\n");
1287 fflush(stdout);
1288 }
1289 clearTrace();
1290 } else if (!ok) {
1291 fprintf(stderr, "unable to start tracing\n");
1292 }
1293
1294 // Reset the trace buffer size to 1.
1295 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001296 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001297
1298 return g_traceAborted ? 1 : 0;
1299}