blob: 94c68215553a641cd649c076451c2466bdd99d86 [file] [log] [blame]
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Paul Lawrence2cd93cc2017-01-17 09:50:18 -080017#define LOG_TAG "atrace"
John Reck40b26b42016-03-30 09:44:36 -070018
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080019#include <errno.h>
20#include <fcntl.h>
21#include <getopt.h>
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070022#include <inttypes.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080023#include <signal.h>
24#include <stdarg.h>
25#include <stdbool.h>
26#include <stdio.h>
27#include <stdlib.h>
Elliott Hughes3da5d232015-01-25 08:35:20 -080028#include <string.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080029#include <time.h>
Martijn Coenend9535872015-11-26 10:00:55 +010030#include <unistd.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080031#include <zlib.h>
32
Carmen Jacksonea826792017-05-05 11:42:32 -070033#include <fstream>
Elliott Hughesa252f4d2016-07-21 17:12:15 -070034#include <memory>
35
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080036#include <binder/IBinder.h>
37#include <binder/IServiceManager.h>
38#include <binder/Parcel.h>
39
Martijn Coenenee9b97e2016-11-16 16:00:26 +010040#include <android/hidl/manager/1.0/IServiceManager.h>
41#include <hidl/ServiceManagement.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080042
43#include <utils/String8.h>
John Reck469a1942015-03-26 15:31:35 -070044#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +090045#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080046#include <utils/Trace.h>
Stephane Gasparinid8419c22016-03-02 13:45:15 +010047#include <android-base/file.h>
Elliott Hughes5fd6ff62017-03-28 14:55:31 -070048#include <android-base/macros.h>
49#include <android-base/properties.h>
50#include <android-base/stringprintf.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080051
52using namespace android;
53
Martijn Coenenee9b97e2016-11-16 16:00:26 +010054using std::string;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080055
sergeyv4144eff2016-04-28 11:40:04 -070056#define MAX_SYS_FILES 10
57#define MAX_PACKAGES 16
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080058
59const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
sergeyv4144eff2016-04-28 11:40:04 -070060
61const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
62const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070063const char* k_coreServiceCategory = "core_services";
64const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080065
66typedef enum { OPT, REQ } requiredness ;
67
68struct TracingCategory {
69 // The name identifying the category.
70 const char* name;
71
72 // A longer description of the category.
73 const char* longname;
74
75 // The userland tracing tags that the category enables.
76 uint64_t tags;
77
78 // The fname==NULL terminated list of /sys/ files that the category
79 // enables.
80 struct {
81 // Whether the file must be writable in order to enable the tracing
82 // category.
83 requiredness required;
84
85 // The path to the enable file.
86 const char* path;
87 } sysfiles[MAX_SYS_FILES];
88};
89
90/* Tracing categories */
91static const TracingCategory k_categories[] = {
John Reck732a29a2017-05-24 16:09:21 -070092 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, {
93 { OPT, "events/mdss/enable" },
94 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070095 { "input", "Input", ATRACE_TAG_INPUT, { } },
96 { "view", "View System", ATRACE_TAG_VIEW, { } },
97 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
98 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
99 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -0500100 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700101 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
102 { "video", "Video", ATRACE_TAG_VIDEO, { } },
103 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
104 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700105 { "app", "Application", ATRACE_TAG_APP, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -0700106 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -0700107 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -0700108 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -0700109 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700110 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 14:36:20 -0700111 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-07-01 01:46:25 +0900112 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Greg Hackmannbbd7d992014-12-01 14:43:34 -0800113 { "database", "Database", ATRACE_TAG_DATABASE, { } },
Felipe Leme0f97c1d2016-09-07 11:33:26 -0700114 { "network", "Network", ATRACE_TAG_NETWORK, { } },
Josh Gao468b4cb2016-11-29 10:55:21 -0800115 { "adb", "ADB", ATRACE_TAG_ADB, { } },
sergeyvdb404152016-05-02 19:26:07 -0700116 { k_coreServiceCategory, "Core services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700117 { "sched", "CPU Scheduling", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800118 { REQ, "events/sched/sched_switch/enable" },
119 { REQ, "events/sched/sched_wakeup/enable" },
120 { OPT, "events/sched/sched_blocked_reason/enable" },
121 { OPT, "events/sched/sched_cpu_hotplug/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800122 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700123 { "irq", "IRQ Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800124 { REQ, "events/irq/enable" },
125 { OPT, "events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700126 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100127 { "i2c", "I2C Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800128 { REQ, "events/i2c/enable" },
129 { REQ, "events/i2c/i2c_read/enable" },
130 { REQ, "events/i2c/i2c_write/enable" },
131 { REQ, "events/i2c/i2c_result/enable" },
132 { REQ, "events/i2c/i2c_reply/enable" },
133 { OPT, "events/i2c/smbus_read/enable" },
134 { OPT, "events/i2c/smbus_write/enable" },
135 { OPT, "events/i2c/smbus_result/enable" },
136 { OPT, "events/i2c/smbus_reply/enable" },
Michael Wright43fb6782016-08-18 19:56:43 +0100137 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700138 { "freq", "CPU Frequency", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800139 { REQ, "events/power/cpu_frequency/enable" },
140 { OPT, "events/power/clock_set_rate/enable" },
141 { OPT, "events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800142 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700143 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800144 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800145 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700146 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800147 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800148 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700149 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800150 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
151 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
152 { OPT, "events/f2fs/f2fs_write_begin/enable" },
153 { OPT, "events/f2fs/f2fs_write_end/enable" },
154 { OPT, "events/ext4/ext4_da_write_begin/enable" },
155 { OPT, "events/ext4/ext4_da_write_end/enable" },
156 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
157 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
158 { REQ, "events/block/block_rq_issue/enable" },
159 { REQ, "events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800160 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700161 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800162 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700163 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700164 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800165 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800166 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700167 { "sync", "Synchronization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800168 { REQ, "events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800169 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700170 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800171 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800172 } },
Colin Cross580407f2014-08-18 15:22:13 -0700173 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800174 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
175 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
176 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
177 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Marc Hittingerf1f62e32017-05-17 15:57:43 -0700178 { REQ, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700179 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800180 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800181 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800182 } },
Scott Bauerae473362015-06-08 16:32:36 -0700183 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800184 { REQ, "events/binder/binder_transaction/enable" },
185 { REQ, "events/binder/binder_transaction_received/enable" },
Martijn Coenen7f3d7a22017-05-26 09:50:55 -0700186 { OPT, "events/binder/binder_set_priority/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700187 } },
188 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800189 { OPT, "events/binder/binder_lock/enable" },
190 { OPT, "events/binder/binder_locked/enable" },
191 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700192 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200193 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800194 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200195 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800196};
197
198/* Command line options */
199static int g_traceDurationSeconds = 5;
200static bool g_traceOverwrite = false;
201static int g_traceBufferSizeKB = 2048;
202static bool g_compress = false;
203static bool g_nohup = false;
204static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900205static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700206static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700207static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700208static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800209
210/* Global state */
211static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700212static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800213static std::string g_traceFolder;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800214
215/* Sys file paths */
216static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800217 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800218
219static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800220 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800221
Joel Fernandesed80bd02017-06-02 10:19:28 -0700222static const char* k_traceCmdlineSizePath =
223 "saved_cmdlines_size";
224
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800225static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800226 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800227
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700228static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800229 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700230
231static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800232 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700233
234static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800235 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700236
237static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800238 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700239
240static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800241 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700242
243static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800244 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700245
246static const char* k_funcgraphDurationPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800247 "options/funcgraph-duration";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700248
249static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800250 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700251
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800252static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800253 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800254
255static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800256 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800257
Martijn Coenend9535872015-11-26 10:00:55 +0100258static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800259 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100260
John Reck469a1942015-03-26 15:31:35 -0700261static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800262 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700263
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800264// Check whether a file exists.
265static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800266 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800267}
268
269// Check whether a file is writable.
270static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800271 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800272}
273
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700274// Truncate a file.
275static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800276{
Jamie Gennis43122e72013-03-21 14:06:31 -0700277 // This uses creat rather than truncate because some of the debug kernel
278 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
279 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800280 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700281 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800282 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700283 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700284 return false;
285 }
286
Jamie Gennis43122e72013-03-21 14:06:31 -0700287 close(traceFD);
288
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700289 return true;
290}
291
292static bool _writeStr(const char* filename, const char* str, int flags)
293{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800294 std::string fullFilename = g_traceFolder + filename;
295 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800296 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800297 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800298 strerror(errno), errno);
299 return false;
300 }
301
302 bool ok = true;
303 ssize_t len = strlen(str);
304 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800305 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800306 strerror(errno), errno);
307 ok = false;
308 }
309
310 close(fd);
311
312 return ok;
313}
314
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700315// Write a string to a file, returning true if the write was successful.
316static bool writeStr(const char* filename, const char* str)
317{
318 return _writeStr(filename, str, O_WRONLY);
319}
320
321// Append a string to a file, returning true if the write was successful.
322static bool appendStr(const char* filename, const char* str)
323{
324 return _writeStr(filename, str, O_APPEND|O_WRONLY);
325}
326
John Reck469a1942015-03-26 15:31:35 -0700327static void writeClockSyncMarker()
328{
329 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200330 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800331 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200332 if (fd == -1) {
333 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
334 strerror(errno), errno);
335 return;
336 }
John Reck469a1942015-03-26 15:31:35 -0700337 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200338
339 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
340 if (write(fd, buffer, len) != len) {
341 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
342 }
343
344 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
345 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
346 if (write(fd, buffer, len) != len) {
347 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
348 }
349
350 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700351}
352
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800353// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
354// file.
355static bool setKernelOptionEnable(const char* filename, bool enable)
356{
357 return writeStr(filename, enable ? "1" : "0");
358}
359
360// Check whether the category is supported on the device with the current
361// rootness. A category is supported only if all its required /sys/ files are
362// writable and if enabling the category will enable one or more tracing tags
363// or /sys/ files.
364static bool isCategorySupported(const TracingCategory& category)
365{
sergeyvdb404152016-05-02 19:26:07 -0700366 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700367 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700368 }
369
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800370 bool ok = category.tags != 0;
371 for (int i = 0; i < MAX_SYS_FILES; i++) {
372 const char* path = category.sysfiles[i].path;
373 bool req = category.sysfiles[i].required == REQ;
374 if (path != NULL) {
375 if (req) {
376 if (!fileIsWritable(path)) {
377 return false;
378 } else {
379 ok = true;
380 }
381 } else {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800382 ok = true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800383 }
384 }
385 }
386 return ok;
387}
388
389// Check whether the category would be supported on the device if the user
390// were root. This function assumes that root is able to write to any file
391// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700392// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800393static bool isCategorySupportedForRoot(const TracingCategory& category)
394{
395 bool ok = category.tags != 0;
396 for (int i = 0; i < MAX_SYS_FILES; i++) {
397 const char* path = category.sysfiles[i].path;
398 bool req = category.sysfiles[i].required == REQ;
399 if (path != NULL) {
400 if (req) {
401 if (!fileExists(path)) {
402 return false;
403 } else {
404 ok = true;
405 }
406 } else {
407 ok |= fileExists(path);
408 }
409 }
410 }
411 return ok;
412}
413
414// Enable or disable overwriting of the kernel trace buffers. Disabling this
415// will cause tracing to stop once the trace buffers have filled up.
416static bool setTraceOverwriteEnable(bool enable)
417{
418 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
419}
420
421// Enable or disable kernel tracing.
422static bool setTracingEnabled(bool enable)
423{
424 return setKernelOptionEnable(k_tracingOnPath, enable);
425}
426
427// Clear the contents of the kernel trace.
428static bool clearTrace()
429{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700430 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800431}
432
433// Set the size of the kernel's trace buffer in kilobytes.
434static bool setTraceBufferSizeKB(int size)
435{
436 char str[32] = "1";
437 int len;
438 if (size < 1) {
439 size = 1;
440 }
441 snprintf(str, 32, "%d", size);
442 return writeStr(k_traceBufferSizePath, str);
443}
444
Joel Fernandesed80bd02017-06-02 10:19:28 -0700445// Set the default size of cmdline hashtable
446static bool setCmdlineSize()
447{
448 return writeStr(k_traceCmdlineSizePath, "8192");
449}
450
Carmen Jacksonea826792017-05-05 11:42:32 -0700451// Set the clock to the best available option while tracing. Use 'boot' if it's
452// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700453// Any write to the trace_clock sysfs file will reset the buffer, so only
454// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700455static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800456{
Carmen Jacksonea826792017-05-05 11:42:32 -0700457 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
458 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
459 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700460
Carmen Jacksonea826792017-05-05 11:42:32 -0700461 std::string newClock;
462 if (clockStr.find("boot") != std::string::npos) {
463 newClock = "boot";
464 } else if (clockStr.find("mono") != std::string::npos) {
465 newClock = "mono";
466 } else {
467 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700468 }
469
Carmen Jacksonea826792017-05-05 11:42:32 -0700470 size_t begin = clockStr.find("[") + 1;
471 size_t end = clockStr.find("]");
472 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
473 return true;
474 }
475 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800476}
477
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700478static bool setPrintTgidEnableIfPresent(bool enable)
479{
480 if (fileExists(k_printTgidPath)) {
481 return setKernelOptionEnable(k_printTgidPath, enable);
482 }
483 return true;
484}
485
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800486// Poke all the binder-enabled processes in the system to get them to re-read
487// their system properties.
488static bool pokeBinderServices()
489{
490 sp<IServiceManager> sm = defaultServiceManager();
491 Vector<String16> services = sm->listServices();
492 for (size_t i = 0; i < services.size(); i++) {
493 sp<IBinder> obj = sm->checkService(services[i]);
494 if (obj != NULL) {
495 Parcel data;
496 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
497 NULL, 0) != OK) {
498 if (false) {
499 // XXX: For some reason this fails on tablets trying to
500 // poke the "phone" service. It's not clear whether some
501 // are expected to fail.
502 String8 svc(services[i]);
503 fprintf(stderr, "error poking binder service %s\n",
504 svc.string());
505 return false;
506 }
507 }
508 }
509 }
510 return true;
511}
512
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100513// Poke all the HAL processes in the system to get them to re-read
514// their system properties.
515static void pokeHalServices()
516{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100517 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100518 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100519 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100520 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100521
522 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800523
524 if (sm == nullptr) {
525 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
526 return;
527 }
528
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800529 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100530 for (size_t i = 0; i < interfaces.size(); i++) {
531 string fqInstanceName = interfaces[i];
532 string::size_type n = fqInstanceName.find("/");
533 if (n == std::string::npos || interfaces[i].size() == n+1)
534 continue;
535 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
536 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100537 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
538 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100539 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100540 continue;
541 }
Carmen Jackson73206122017-04-18 15:37:57 -0700542
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100543 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700544 if (interface == nullptr) {
545 // ignore
546 continue;
547 }
548
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100549 auto notifyRet = interface->notifySyspropsChanged();
550 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100551 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800552 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100553 }
554 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800555 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100556 // TODO(b/34242478) fix this when we determine the correct ACL
557 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800558 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100559}
560
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800561// Set the trace tags that userland tracing uses, and poke the running
562// processes to pick up the new value.
563static bool setTagsProperty(uint64_t tags)
564{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700565 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
566 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800567 fprintf(stderr, "error setting trace tags system property\n");
568 return false;
569 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700570 return true;
571}
572
sergeyv4144eff2016-04-28 11:40:04 -0700573static void clearAppProperties()
574{
sergeyv4144eff2016-04-28 11:40:04 -0700575 for (int i = 0; i < MAX_PACKAGES; i++) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700576 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
577 if (!android::base::SetProperty(key, "")) {
578 fprintf(stderr, "failed to clear system property: %s\n", key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700579 }
580 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700581 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700582 fprintf(stderr, "failed to clear system property: %s",
583 k_traceAppsNumberProperty);
584 }
585}
586
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700587// Set the system property that indicates which apps should perform
588// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700589static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700590{
sergeyv4144eff2016-04-28 11:40:04 -0700591 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700592 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700593 while (start != NULL) {
594 if (i == MAX_PACKAGES) {
595 fprintf(stderr, "error: only 16 packages could be traced at once\n");
596 clearAppProperties();
597 return false;
598 }
599 char* end = strchr(start, ',');
600 if (end != NULL) {
601 *end = '\0';
602 end++;
603 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700604 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
605 if (!android::base::SetProperty(key, start)) {
606 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700607 clearAppProperties();
608 return false;
609 }
610 start = end;
611 i++;
612 }
613
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700614 std::string value = android::base::StringPrintf("%d", i);
615 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
616 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700617 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700618 return false;
619 }
620 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800621}
622
623// Disable all /sys/ enable files.
624static bool disableKernelTraceEvents() {
625 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700626 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800627 const TracingCategory &c = k_categories[i];
628 for (int j = 0; j < MAX_SYS_FILES; j++) {
629 const char* path = c.sysfiles[j].path;
630 if (path != NULL && fileIsWritable(path)) {
631 ok &= setKernelOptionEnable(path, false);
632 }
633 }
634 }
635 return ok;
636}
637
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700638// Verify that the comma separated list of functions are being traced by the
639// kernel.
640static bool verifyKernelTraceFuncs(const char* funcs)
641{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100642 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800643 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100644 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700645 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100646 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700647 }
648
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100649 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700650
651 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100652 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700653 bool ok = true;
654 char* myFuncs = strdup(funcs);
655 char* func = strtok(myFuncs, ",");
656 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100657 if (!strchr(func, '*')) {
658 String8 fancyFunc = String8::format("\n%s\n", func);
659 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
660 if (!found || func[0] == '\0') {
661 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
662 "to trace.\n", func);
663 ok = false;
664 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700665 }
666 func = strtok(NULL, ",");
667 }
668 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700669 return ok;
670}
671
672// Set the comma separated list of functions that the kernel is to trace.
673static bool setKernelTraceFuncs(const char* funcs)
674{
675 bool ok = true;
676
677 if (funcs == NULL || funcs[0] == '\0') {
678 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700679 if (fileIsWritable(k_currentTracerPath)) {
680 ok &= writeStr(k_currentTracerPath, "nop");
681 }
682 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700683 ok &= truncateFile(k_ftraceFilterPath);
684 }
685 } else {
686 // Enable kernel function tracing.
687 ok &= writeStr(k_currentTracerPath, "function_graph");
688 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
689 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
690 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
691 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
692
693 // Set the requested filter functions.
694 ok &= truncateFile(k_ftraceFilterPath);
695 char* myFuncs = strdup(funcs);
696 char* func = strtok(myFuncs, ",");
697 while (func) {
698 ok &= appendStr(k_ftraceFilterPath, func);
699 func = strtok(NULL, ",");
700 }
701 free(myFuncs);
702
703 // Verify that the set functions are being traced.
704 if (ok) {
705 ok &= verifyKernelTraceFuncs(funcs);
706 }
707 }
708
709 return ok;
710}
711
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900712static bool setCategoryEnable(const char* name, bool enable)
713{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700714 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900715 const TracingCategory& c = k_categories[i];
716 if (strcmp(name, c.name) == 0) {
717 if (isCategorySupported(c)) {
718 g_categoryEnables[i] = enable;
719 return true;
720 } else {
721 if (isCategorySupportedForRoot(c)) {
722 fprintf(stderr, "error: category \"%s\" requires root "
723 "privileges.\n", name);
724 } else {
725 fprintf(stderr, "error: category \"%s\" is not supported "
726 "on this device.\n", name);
727 }
728 return false;
729 }
730 }
731 }
732 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
733 return false;
734}
735
736static bool setCategoriesEnableFromFile(const char* categories_file)
737{
738 if (!categories_file) {
739 return true;
740 }
741 Tokenizer* tokenizer = NULL;
742 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
743 return false;
744 }
745 bool ok = true;
746 while (!tokenizer->isEol()) {
747 String8 token = tokenizer->nextToken(" ");
748 if (token.isEmpty()) {
749 tokenizer->skipDelimiters(" ");
750 continue;
751 }
752 ok &= setCategoryEnable(token.string(), true);
753 }
754 delete tokenizer;
755 return ok;
756}
757
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700758// Set all the kernel tracing settings to the desired state for this trace
759// capture.
760static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800761{
762 bool ok = true;
763
764 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900765 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800766 ok &= setTraceOverwriteEnable(g_traceOverwrite);
767 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
Joel Fernandesed80bd02017-06-02 10:19:28 -0700768 ok &= setCmdlineSize();
Carmen Jacksonea826792017-05-05 11:42:32 -0700769 ok &= setClock();
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700770 ok &= setPrintTgidEnableIfPresent(true);
771 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800772
773 // Set up the tags property.
774 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700775 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800776 if (g_categoryEnables[i]) {
777 const TracingCategory &c = k_categories[i];
778 tags |= c.tags;
779 }
780 }
781 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700782
783 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700784 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700785 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
786 coreServicesTagEnabled = g_categoryEnables[i];
787 }
788 }
789
790 std::string packageList(g_debugAppCmdLine);
791 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700792 if (!packageList.empty()) {
793 packageList += ",";
794 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700795 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700796 }
Dan Austin09a79872016-05-31 13:27:03 -0700797 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700798 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100799 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800800
801 // Disable all the sysfs enables. This is done as a separate loop from
802 // the enables to allow the same enable to exist in multiple categories.
803 ok &= disableKernelTraceEvents();
804
805 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700806 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800807 if (g_categoryEnables[i]) {
808 const TracingCategory &c = k_categories[i];
809 for (int j = 0; j < MAX_SYS_FILES; j++) {
810 const char* path = c.sysfiles[j].path;
811 bool required = c.sysfiles[j].required == REQ;
812 if (path != NULL) {
813 if (fileIsWritable(path)) {
814 ok &= setKernelOptionEnable(path, true);
815 } else if (required) {
816 fprintf(stderr, "error writing file %s\n", path);
817 ok = false;
818 }
819 }
820 }
821 }
822 }
823
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800824 return ok;
825}
826
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700827// Reset all the kernel tracing settings to their default state.
828static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800829{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800830 // Disable all tracing that we're able to.
831 disableKernelTraceEvents();
832
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700833 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800834 setTagsProperty(0);
sergeyv4144eff2016-04-28 11:40:04 -0700835 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700836 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800837
838 // Set the options back to their defaults.
839 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700840 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700841 setPrintTgidEnableIfPresent(false);
842 setKernelTraceFuncs(NULL);
843}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800844
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700845
846// Enable tracing in the kernel.
847static bool startTrace()
848{
849 return setTracingEnabled(true);
850}
851
852// Disable tracing in the kernel.
853static void stopTrace()
854{
855 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800856}
857
Martijn Coenend9535872015-11-26 10:00:55 +0100858// Read data from the tracing pipe and forward to stdout
859static void streamTrace()
860{
861 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800862 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100863 if (traceFD == -1) {
864 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
865 strerror(errno), errno);
866 return;
867 }
868 while (!g_traceAborted) {
869 ssize_t bytes_read = read(traceFD, trace_data, 4096);
870 if (bytes_read > 0) {
871 write(STDOUT_FILENO, trace_data, bytes_read);
872 fflush(stdout);
873 } else {
874 if (!g_traceAborted) {
875 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
876 bytes_read, errno, strerror(errno));
877 }
878 break;
879 }
880 }
881}
882
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800883// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700884static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800885{
John Reck6c8ac922016-03-28 11:25:30 -0700886 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800887 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800888 if (traceFD == -1) {
889 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
890 strerror(errno), errno);
891 return;
892 }
893
894 if (g_compress) {
895 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800896 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700897
898 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800899 if (result != Z_OK) {
900 fprintf(stderr, "error initializing zlib: %d\n", result);
901 close(traceFD);
902 return;
903 }
904
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700905 constexpr size_t bufSize = 64*1024;
906 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
907 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
908 if (!in || !out) {
909 fprintf(stderr, "couldn't allocate buffers\n");
910 close(traceFD);
911 return;
912 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800913
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700914 int flush = Z_NO_FLUSH;
915
916 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800917 zs.avail_out = bufSize;
918
919 do {
920
921 if (zs.avail_in == 0) {
922 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700923 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800924 if (result < 0) {
925 fprintf(stderr, "error reading trace: %s (%d)\n",
926 strerror(errno), errno);
927 result = Z_STREAM_END;
928 break;
929 } else if (result == 0) {
930 flush = Z_FINISH;
931 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700932 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800933 zs.avail_in = result;
934 }
935 }
936
937 if (zs.avail_out == 0) {
938 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700939 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800940 if ((size_t)result < bufSize) {
941 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
942 strerror(errno), errno);
943 result = Z_STREAM_END; // skip deflate error message
944 zs.avail_out = bufSize; // skip the final write
945 break;
946 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700947 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800948 zs.avail_out = bufSize;
949 }
950
951 } while ((result = deflate(&zs, flush)) == Z_OK);
952
953 if (result != Z_STREAM_END) {
954 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
955 }
956
957 if (zs.avail_out < bufSize) {
958 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -0700959 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800960 if ((size_t)result < bytes) {
961 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
962 strerror(errno), errno);
963 }
964 }
965
966 result = deflateEnd(&zs);
967 if (result != Z_OK) {
968 fprintf(stderr, "error cleaning up zlib: %d\n", result);
969 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800970 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -0700971 char buf[4096];
972 ssize_t rc;
973 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
974 if (!android::base::WriteFully(outFd, buf, rc)) {
975 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
976 break;
977 }
978 }
979 if (rc == -1) {
980 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800981 }
982 }
983
984 close(traceFD);
985}
986
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700987static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800988{
989 if (!g_nohup) {
990 g_traceAborted = true;
991 }
992}
993
994static void registerSigHandler()
995{
996 struct sigaction sa;
997 sigemptyset(&sa.sa_mask);
998 sa.sa_flags = 0;
999 sa.sa_handler = handleSignal;
1000 sigaction(SIGHUP, &sa, NULL);
1001 sigaction(SIGINT, &sa, NULL);
1002 sigaction(SIGQUIT, &sa, NULL);
1003 sigaction(SIGTERM, &sa, NULL);
1004}
1005
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001006static void listSupportedCategories()
1007{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001008 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001009 const TracingCategory& c = k_categories[i];
1010 if (isCategorySupported(c)) {
1011 printf(" %10s - %s\n", c.name, c.longname);
1012 }
1013 }
1014}
1015
1016// Print the command usage help to stderr.
1017static void showHelp(const char *cmd)
1018{
1019 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1020 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001021 " -a appname enable app-level tracing for a comma "
1022 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001023 " -b N use a trace buffer size of N KB\n"
1024 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001025 " -f filename use the categories written in a file as space-separated\n"
1026 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001027 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001028 " -n ignore signals\n"
1029 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001030 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001031 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001032 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001033 " --async_dump dump the current contents of circular trace buffer\n"
1034 " --async_stop stop tracing and dump the current contents of circular\n"
1035 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001036 " --stream stream trace to stdout as it enters the trace buffer\n"
1037 " Note: this can take significant CPU time, and is best\n"
1038 " used for measuring things that are not affected by\n"
1039 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001040 " --list_categories\n"
1041 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001042 " -o filename write the trace to the specified file instead\n"
1043 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001044 );
1045}
1046
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001047bool findTraceFiles()
1048{
1049 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1050 static const std::string tracefs_path = "/sys/kernel/tracing/";
1051 static const std::string trace_file = "trace_marker";
1052
1053 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1054 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1055
1056 if (!tracefs && !debugfs) {
1057 fprintf(stderr, "Error: Did not find trace folder\n");
1058 return false;
1059 }
1060
1061 if (tracefs) {
1062 g_traceFolder = tracefs_path;
1063 } else {
1064 g_traceFolder = debugfs_path;
1065 }
1066
1067 return true;
1068}
1069
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001070int main(int argc, char **argv)
1071{
1072 bool async = false;
1073 bool traceStart = true;
1074 bool traceStop = true;
1075 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001076 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001077
1078 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1079 showHelp(argv[0]);
1080 exit(0);
1081 }
1082
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001083 if (!findTraceFiles()) {
1084 fprintf(stderr, "No trace folder found\n");
1085 exit(-1);
1086 }
1087
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001088 for (;;) {
1089 int ret;
1090 int option_index = 0;
1091 static struct option long_options[] = {
1092 {"async_start", no_argument, 0, 0 },
1093 {"async_stop", no_argument, 0, 0 },
1094 {"async_dump", no_argument, 0, 0 },
1095 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +01001096 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001097 { 0, 0, 0, 0 }
1098 };
1099
John Reck40b26b42016-03-30 09:44:36 -07001100 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001101 long_options, &option_index);
1102
1103 if (ret < 0) {
1104 for (int i = optind; i < argc; i++) {
1105 if (!setCategoryEnable(argv[i], true)) {
1106 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1107 exit(1);
1108 }
1109 }
1110 break;
1111 }
1112
1113 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001114 case 'a':
1115 g_debugAppCmdLine = optarg;
1116 break;
1117
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001118 case 'b':
1119 g_traceBufferSizeKB = atoi(optarg);
1120 break;
1121
1122 case 'c':
1123 g_traceOverwrite = true;
1124 break;
1125
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001126 case 'f':
1127 g_categoriesFile = optarg;
1128 break;
1129
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001130 case 'k':
1131 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001132 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001133
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001134 case 'n':
1135 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001136 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001137
1138 case 's':
1139 g_initialSleepSecs = atoi(optarg);
1140 break;
1141
1142 case 't':
1143 g_traceDurationSeconds = atoi(optarg);
1144 break;
1145
1146 case 'z':
1147 g_compress = true;
1148 break;
1149
John Reck40b26b42016-03-30 09:44:36 -07001150 case 'o':
1151 g_outputFile = optarg;
1152 break;
1153
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001154 case 0:
1155 if (!strcmp(long_options[option_index].name, "async_start")) {
1156 async = true;
1157 traceStop = false;
1158 traceDump = false;
1159 g_traceOverwrite = true;
1160 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1161 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001162 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001163 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1164 async = true;
1165 traceStart = false;
1166 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001167 } else if (!strcmp(long_options[option_index].name, "stream")) {
1168 traceStream = true;
1169 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001170 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1171 listSupportedCategories();
1172 exit(0);
1173 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001174 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001175
1176 default:
1177 fprintf(stderr, "\n");
1178 showHelp(argv[0]);
1179 exit(-1);
1180 break;
1181 }
1182 }
1183
1184 registerSigHandler();
1185
1186 if (g_initialSleepSecs > 0) {
1187 sleep(g_initialSleepSecs);
1188 }
1189
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001190 bool ok = true;
1191 ok &= setUpTrace();
1192 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001193
1194 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001195 if (!traceStream) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001196 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001197 fflush(stdout);
1198 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001199
1200 // We clear the trace after starting it because tracing gets enabled for
1201 // each CPU individually in the kernel. Having the beginning of the trace
1202 // contain entries from only one CPU can cause "begin" entries without a
1203 // matching "end" entry to show up if a task gets migrated from one CPU to
1204 // another.
1205 ok = clearTrace();
1206
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001207 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001208 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001209 // Sleep to allow the trace to be captured.
1210 struct timespec timeLeft;
1211 timeLeft.tv_sec = g_traceDurationSeconds;
1212 timeLeft.tv_nsec = 0;
1213 do {
1214 if (g_traceAborted) {
1215 break;
1216 }
1217 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1218 }
Martijn Coenend9535872015-11-26 10:00:55 +01001219
1220 if (traceStream) {
1221 streamTrace();
1222 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001223 }
1224
1225 // Stop the trace and restore the default settings.
1226 if (traceStop)
1227 stopTrace();
1228
1229 if (ok && traceDump) {
1230 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001231 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001232 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001233 int outFd = STDOUT_FILENO;
1234 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001235 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001236 }
1237 if (outFd == -1) {
1238 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1239 } else {
1240 dprintf(outFd, "TRACE:\n");
1241 dumpTrace(outFd);
1242 if (g_outputFile) {
1243 close(outFd);
1244 }
1245 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001246 } else {
1247 printf("\ntrace aborted.\n");
1248 fflush(stdout);
1249 }
1250 clearTrace();
1251 } else if (!ok) {
1252 fprintf(stderr, "unable to start tracing\n");
1253 }
1254
1255 // Reset the trace buffer size to 1.
1256 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001257 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001258
1259 return g_traceAborted ? 1 : 0;
1260}