blob: ca799c9436b043ca3e39589d7c7354677b8407b7 [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" },
Scott Bauerae473362015-06-08 16:32:36 -0700186 } },
187 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800188 { OPT, "events/binder/binder_lock/enable" },
189 { OPT, "events/binder/binder_locked/enable" },
190 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700191 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200192 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800193 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200194 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800195};
196
197/* Command line options */
198static int g_traceDurationSeconds = 5;
199static bool g_traceOverwrite = false;
200static int g_traceBufferSizeKB = 2048;
201static bool g_compress = false;
202static bool g_nohup = false;
203static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900204static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700205static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700206static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700207static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800208
209/* Global state */
210static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700211static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800212static std::string g_traceFolder;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800213
214/* Sys file paths */
215static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800216 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800217
218static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800219 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800220
221static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800222 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800223
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700224static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800225 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700226
227static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800228 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700229
230static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800231 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700232
233static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800234 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700235
236static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800237 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700238
239static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800240 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700241
242static const char* k_funcgraphDurationPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800243 "options/funcgraph-duration";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700244
245static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800246 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700247
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800248static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800249 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800250
251static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800252 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800253
Martijn Coenend9535872015-11-26 10:00:55 +0100254static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800255 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100256
John Reck469a1942015-03-26 15:31:35 -0700257static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800258 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700259
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800260// Check whether a file exists.
261static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800262 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800263}
264
265// Check whether a file is writable.
266static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800267 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800268}
269
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700270// Truncate a file.
271static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800272{
Jamie Gennis43122e72013-03-21 14:06:31 -0700273 // This uses creat rather than truncate because some of the debug kernel
274 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
275 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800276 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700277 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800278 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700279 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700280 return false;
281 }
282
Jamie Gennis43122e72013-03-21 14:06:31 -0700283 close(traceFD);
284
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700285 return true;
286}
287
288static bool _writeStr(const char* filename, const char* str, int flags)
289{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800290 std::string fullFilename = g_traceFolder + filename;
291 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800292 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800293 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800294 strerror(errno), errno);
295 return false;
296 }
297
298 bool ok = true;
299 ssize_t len = strlen(str);
300 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800301 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800302 strerror(errno), errno);
303 ok = false;
304 }
305
306 close(fd);
307
308 return ok;
309}
310
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700311// Write a string to a file, returning true if the write was successful.
312static bool writeStr(const char* filename, const char* str)
313{
314 return _writeStr(filename, str, O_WRONLY);
315}
316
317// Append a string to a file, returning true if the write was successful.
318static bool appendStr(const char* filename, const char* str)
319{
320 return _writeStr(filename, str, O_APPEND|O_WRONLY);
321}
322
John Reck469a1942015-03-26 15:31:35 -0700323static void writeClockSyncMarker()
324{
325 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200326 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800327 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200328 if (fd == -1) {
329 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
330 strerror(errno), errno);
331 return;
332 }
John Reck469a1942015-03-26 15:31:35 -0700333 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200334
335 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
336 if (write(fd, buffer, len) != len) {
337 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
338 }
339
340 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
341 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
342 if (write(fd, buffer, len) != len) {
343 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
344 }
345
346 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700347}
348
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800349// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
350// file.
351static bool setKernelOptionEnable(const char* filename, bool enable)
352{
353 return writeStr(filename, enable ? "1" : "0");
354}
355
356// Check whether the category is supported on the device with the current
357// rootness. A category is supported only if all its required /sys/ files are
358// writable and if enabling the category will enable one or more tracing tags
359// or /sys/ files.
360static bool isCategorySupported(const TracingCategory& category)
361{
sergeyvdb404152016-05-02 19:26:07 -0700362 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700363 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700364 }
365
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800366 bool ok = category.tags != 0;
367 for (int i = 0; i < MAX_SYS_FILES; i++) {
368 const char* path = category.sysfiles[i].path;
369 bool req = category.sysfiles[i].required == REQ;
370 if (path != NULL) {
371 if (req) {
372 if (!fileIsWritable(path)) {
373 return false;
374 } else {
375 ok = true;
376 }
377 } else {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800378 ok = true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800379 }
380 }
381 }
382 return ok;
383}
384
385// Check whether the category would be supported on the device if the user
386// were root. This function assumes that root is able to write to any file
387// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700388// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800389static bool isCategorySupportedForRoot(const TracingCategory& category)
390{
391 bool ok = category.tags != 0;
392 for (int i = 0; i < MAX_SYS_FILES; i++) {
393 const char* path = category.sysfiles[i].path;
394 bool req = category.sysfiles[i].required == REQ;
395 if (path != NULL) {
396 if (req) {
397 if (!fileExists(path)) {
398 return false;
399 } else {
400 ok = true;
401 }
402 } else {
403 ok |= fileExists(path);
404 }
405 }
406 }
407 return ok;
408}
409
410// Enable or disable overwriting of the kernel trace buffers. Disabling this
411// will cause tracing to stop once the trace buffers have filled up.
412static bool setTraceOverwriteEnable(bool enable)
413{
414 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
415}
416
417// Enable or disable kernel tracing.
418static bool setTracingEnabled(bool enable)
419{
420 return setKernelOptionEnable(k_tracingOnPath, enable);
421}
422
423// Clear the contents of the kernel trace.
424static bool clearTrace()
425{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700426 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800427}
428
429// Set the size of the kernel's trace buffer in kilobytes.
430static bool setTraceBufferSizeKB(int size)
431{
432 char str[32] = "1";
433 int len;
434 if (size < 1) {
435 size = 1;
436 }
437 snprintf(str, 32, "%d", size);
438 return writeStr(k_traceBufferSizePath, str);
439}
440
Carmen Jacksonea826792017-05-05 11:42:32 -0700441// Set the clock to the best available option while tracing. Use 'boot' if it's
442// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700443// Any write to the trace_clock sysfs file will reset the buffer, so only
444// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700445static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800446{
Carmen Jacksonea826792017-05-05 11:42:32 -0700447 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
448 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
449 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700450
Carmen Jacksonea826792017-05-05 11:42:32 -0700451 std::string newClock;
452 if (clockStr.find("boot") != std::string::npos) {
453 newClock = "boot";
454 } else if (clockStr.find("mono") != std::string::npos) {
455 newClock = "mono";
456 } else {
457 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700458 }
459
Carmen Jacksonea826792017-05-05 11:42:32 -0700460 size_t begin = clockStr.find("[") + 1;
461 size_t end = clockStr.find("]");
462 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
463 return true;
464 }
465 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800466}
467
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700468static bool setPrintTgidEnableIfPresent(bool enable)
469{
470 if (fileExists(k_printTgidPath)) {
471 return setKernelOptionEnable(k_printTgidPath, enable);
472 }
473 return true;
474}
475
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800476// Poke all the binder-enabled processes in the system to get them to re-read
477// their system properties.
478static bool pokeBinderServices()
479{
480 sp<IServiceManager> sm = defaultServiceManager();
481 Vector<String16> services = sm->listServices();
482 for (size_t i = 0; i < services.size(); i++) {
483 sp<IBinder> obj = sm->checkService(services[i]);
484 if (obj != NULL) {
485 Parcel data;
486 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
487 NULL, 0) != OK) {
488 if (false) {
489 // XXX: For some reason this fails on tablets trying to
490 // poke the "phone" service. It's not clear whether some
491 // are expected to fail.
492 String8 svc(services[i]);
493 fprintf(stderr, "error poking binder service %s\n",
494 svc.string());
495 return false;
496 }
497 }
498 }
499 }
500 return true;
501}
502
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100503// Poke all the HAL processes in the system to get them to re-read
504// their system properties.
505static void pokeHalServices()
506{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100507 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100508 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100509 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100510 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100511
512 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800513
514 if (sm == nullptr) {
515 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
516 return;
517 }
518
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800519 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100520 for (size_t i = 0; i < interfaces.size(); i++) {
521 string fqInstanceName = interfaces[i];
522 string::size_type n = fqInstanceName.find("/");
523 if (n == std::string::npos || interfaces[i].size() == n+1)
524 continue;
525 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
526 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100527 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
528 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100529 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100530 continue;
531 }
Carmen Jackson73206122017-04-18 15:37:57 -0700532
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100533 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700534 if (interface == nullptr) {
535 // ignore
536 continue;
537 }
538
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100539 auto notifyRet = interface->notifySyspropsChanged();
540 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100541 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800542 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100543 }
544 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800545 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100546 // TODO(b/34242478) fix this when we determine the correct ACL
547 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800548 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100549}
550
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800551// Set the trace tags that userland tracing uses, and poke the running
552// processes to pick up the new value.
553static bool setTagsProperty(uint64_t tags)
554{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700555 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
556 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800557 fprintf(stderr, "error setting trace tags system property\n");
558 return false;
559 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700560 return true;
561}
562
sergeyv4144eff2016-04-28 11:40:04 -0700563static void clearAppProperties()
564{
sergeyv4144eff2016-04-28 11:40:04 -0700565 for (int i = 0; i < MAX_PACKAGES; i++) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700566 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
567 if (!android::base::SetProperty(key, "")) {
568 fprintf(stderr, "failed to clear system property: %s\n", key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700569 }
570 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700571 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700572 fprintf(stderr, "failed to clear system property: %s",
573 k_traceAppsNumberProperty);
574 }
575}
576
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700577// Set the system property that indicates which apps should perform
578// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700579static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700580{
sergeyv4144eff2016-04-28 11:40:04 -0700581 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700582 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700583 while (start != NULL) {
584 if (i == MAX_PACKAGES) {
585 fprintf(stderr, "error: only 16 packages could be traced at once\n");
586 clearAppProperties();
587 return false;
588 }
589 char* end = strchr(start, ',');
590 if (end != NULL) {
591 *end = '\0';
592 end++;
593 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700594 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
595 if (!android::base::SetProperty(key, start)) {
596 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700597 clearAppProperties();
598 return false;
599 }
600 start = end;
601 i++;
602 }
603
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700604 std::string value = android::base::StringPrintf("%d", i);
605 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
606 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700607 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700608 return false;
609 }
610 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800611}
612
613// Disable all /sys/ enable files.
614static bool disableKernelTraceEvents() {
615 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700616 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800617 const TracingCategory &c = k_categories[i];
618 for (int j = 0; j < MAX_SYS_FILES; j++) {
619 const char* path = c.sysfiles[j].path;
620 if (path != NULL && fileIsWritable(path)) {
621 ok &= setKernelOptionEnable(path, false);
622 }
623 }
624 }
625 return ok;
626}
627
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700628// Verify that the comma separated list of functions are being traced by the
629// kernel.
630static bool verifyKernelTraceFuncs(const char* funcs)
631{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100632 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800633 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100634 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700635 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100636 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700637 }
638
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100639 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700640
641 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100642 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700643 bool ok = true;
644 char* myFuncs = strdup(funcs);
645 char* func = strtok(myFuncs, ",");
646 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100647 if (!strchr(func, '*')) {
648 String8 fancyFunc = String8::format("\n%s\n", func);
649 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
650 if (!found || func[0] == '\0') {
651 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
652 "to trace.\n", func);
653 ok = false;
654 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700655 }
656 func = strtok(NULL, ",");
657 }
658 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700659 return ok;
660}
661
662// Set the comma separated list of functions that the kernel is to trace.
663static bool setKernelTraceFuncs(const char* funcs)
664{
665 bool ok = true;
666
667 if (funcs == NULL || funcs[0] == '\0') {
668 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700669 if (fileIsWritable(k_currentTracerPath)) {
670 ok &= writeStr(k_currentTracerPath, "nop");
671 }
672 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700673 ok &= truncateFile(k_ftraceFilterPath);
674 }
675 } else {
676 // Enable kernel function tracing.
677 ok &= writeStr(k_currentTracerPath, "function_graph");
678 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
679 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
680 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
681 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
682
683 // Set the requested filter functions.
684 ok &= truncateFile(k_ftraceFilterPath);
685 char* myFuncs = strdup(funcs);
686 char* func = strtok(myFuncs, ",");
687 while (func) {
688 ok &= appendStr(k_ftraceFilterPath, func);
689 func = strtok(NULL, ",");
690 }
691 free(myFuncs);
692
693 // Verify that the set functions are being traced.
694 if (ok) {
695 ok &= verifyKernelTraceFuncs(funcs);
696 }
697 }
698
699 return ok;
700}
701
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900702static bool setCategoryEnable(const char* name, bool enable)
703{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700704 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900705 const TracingCategory& c = k_categories[i];
706 if (strcmp(name, c.name) == 0) {
707 if (isCategorySupported(c)) {
708 g_categoryEnables[i] = enable;
709 return true;
710 } else {
711 if (isCategorySupportedForRoot(c)) {
712 fprintf(stderr, "error: category \"%s\" requires root "
713 "privileges.\n", name);
714 } else {
715 fprintf(stderr, "error: category \"%s\" is not supported "
716 "on this device.\n", name);
717 }
718 return false;
719 }
720 }
721 }
722 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
723 return false;
724}
725
726static bool setCategoriesEnableFromFile(const char* categories_file)
727{
728 if (!categories_file) {
729 return true;
730 }
731 Tokenizer* tokenizer = NULL;
732 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
733 return false;
734 }
735 bool ok = true;
736 while (!tokenizer->isEol()) {
737 String8 token = tokenizer->nextToken(" ");
738 if (token.isEmpty()) {
739 tokenizer->skipDelimiters(" ");
740 continue;
741 }
742 ok &= setCategoryEnable(token.string(), true);
743 }
744 delete tokenizer;
745 return ok;
746}
747
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700748// Set all the kernel tracing settings to the desired state for this trace
749// capture.
750static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800751{
752 bool ok = true;
753
754 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900755 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800756 ok &= setTraceOverwriteEnable(g_traceOverwrite);
757 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
Carmen Jacksonea826792017-05-05 11:42:32 -0700758 ok &= setClock();
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700759 ok &= setPrintTgidEnableIfPresent(true);
760 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800761
762 // Set up the tags property.
763 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700764 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800765 if (g_categoryEnables[i]) {
766 const TracingCategory &c = k_categories[i];
767 tags |= c.tags;
768 }
769 }
770 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700771
772 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700773 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700774 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
775 coreServicesTagEnabled = g_categoryEnables[i];
776 }
777 }
778
779 std::string packageList(g_debugAppCmdLine);
780 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700781 if (!packageList.empty()) {
782 packageList += ",";
783 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700784 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700785 }
Dan Austin09a79872016-05-31 13:27:03 -0700786 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700787 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100788 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800789
790 // Disable all the sysfs enables. This is done as a separate loop from
791 // the enables to allow the same enable to exist in multiple categories.
792 ok &= disableKernelTraceEvents();
793
794 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700795 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800796 if (g_categoryEnables[i]) {
797 const TracingCategory &c = k_categories[i];
798 for (int j = 0; j < MAX_SYS_FILES; j++) {
799 const char* path = c.sysfiles[j].path;
800 bool required = c.sysfiles[j].required == REQ;
801 if (path != NULL) {
802 if (fileIsWritable(path)) {
803 ok &= setKernelOptionEnable(path, true);
804 } else if (required) {
805 fprintf(stderr, "error writing file %s\n", path);
806 ok = false;
807 }
808 }
809 }
810 }
811 }
812
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800813 return ok;
814}
815
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700816// Reset all the kernel tracing settings to their default state.
817static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800818{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800819 // Disable all tracing that we're able to.
820 disableKernelTraceEvents();
821
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700822 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800823 setTagsProperty(0);
sergeyv4144eff2016-04-28 11:40:04 -0700824 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700825 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800826
827 // Set the options back to their defaults.
828 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700829 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700830 setPrintTgidEnableIfPresent(false);
831 setKernelTraceFuncs(NULL);
832}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800833
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700834
835// Enable tracing in the kernel.
836static bool startTrace()
837{
838 return setTracingEnabled(true);
839}
840
841// Disable tracing in the kernel.
842static void stopTrace()
843{
844 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800845}
846
Martijn Coenend9535872015-11-26 10:00:55 +0100847// Read data from the tracing pipe and forward to stdout
848static void streamTrace()
849{
850 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800851 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100852 if (traceFD == -1) {
853 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
854 strerror(errno), errno);
855 return;
856 }
857 while (!g_traceAborted) {
858 ssize_t bytes_read = read(traceFD, trace_data, 4096);
859 if (bytes_read > 0) {
860 write(STDOUT_FILENO, trace_data, bytes_read);
861 fflush(stdout);
862 } else {
863 if (!g_traceAborted) {
864 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
865 bytes_read, errno, strerror(errno));
866 }
867 break;
868 }
869 }
870}
871
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800872// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700873static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800874{
John Reck6c8ac922016-03-28 11:25:30 -0700875 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800876 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800877 if (traceFD == -1) {
878 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
879 strerror(errno), errno);
880 return;
881 }
882
883 if (g_compress) {
884 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800885 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700886
887 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800888 if (result != Z_OK) {
889 fprintf(stderr, "error initializing zlib: %d\n", result);
890 close(traceFD);
891 return;
892 }
893
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700894 constexpr size_t bufSize = 64*1024;
895 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
896 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
897 if (!in || !out) {
898 fprintf(stderr, "couldn't allocate buffers\n");
899 close(traceFD);
900 return;
901 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800902
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700903 int flush = Z_NO_FLUSH;
904
905 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800906 zs.avail_out = bufSize;
907
908 do {
909
910 if (zs.avail_in == 0) {
911 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700912 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800913 if (result < 0) {
914 fprintf(stderr, "error reading trace: %s (%d)\n",
915 strerror(errno), errno);
916 result = Z_STREAM_END;
917 break;
918 } else if (result == 0) {
919 flush = Z_FINISH;
920 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700921 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800922 zs.avail_in = result;
923 }
924 }
925
926 if (zs.avail_out == 0) {
927 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700928 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800929 if ((size_t)result < bufSize) {
930 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
931 strerror(errno), errno);
932 result = Z_STREAM_END; // skip deflate error message
933 zs.avail_out = bufSize; // skip the final write
934 break;
935 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700936 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800937 zs.avail_out = bufSize;
938 }
939
940 } while ((result = deflate(&zs, flush)) == Z_OK);
941
942 if (result != Z_STREAM_END) {
943 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
944 }
945
946 if (zs.avail_out < bufSize) {
947 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -0700948 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800949 if ((size_t)result < bytes) {
950 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
951 strerror(errno), errno);
952 }
953 }
954
955 result = deflateEnd(&zs);
956 if (result != Z_OK) {
957 fprintf(stderr, "error cleaning up zlib: %d\n", result);
958 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800959 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -0700960 char buf[4096];
961 ssize_t rc;
962 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
963 if (!android::base::WriteFully(outFd, buf, rc)) {
964 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
965 break;
966 }
967 }
968 if (rc == -1) {
969 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800970 }
971 }
972
973 close(traceFD);
974}
975
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700976static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800977{
978 if (!g_nohup) {
979 g_traceAborted = true;
980 }
981}
982
983static void registerSigHandler()
984{
985 struct sigaction sa;
986 sigemptyset(&sa.sa_mask);
987 sa.sa_flags = 0;
988 sa.sa_handler = handleSignal;
989 sigaction(SIGHUP, &sa, NULL);
990 sigaction(SIGINT, &sa, NULL);
991 sigaction(SIGQUIT, &sa, NULL);
992 sigaction(SIGTERM, &sa, NULL);
993}
994
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800995static void listSupportedCategories()
996{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700997 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800998 const TracingCategory& c = k_categories[i];
999 if (isCategorySupported(c)) {
1000 printf(" %10s - %s\n", c.name, c.longname);
1001 }
1002 }
1003}
1004
1005// Print the command usage help to stderr.
1006static void showHelp(const char *cmd)
1007{
1008 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1009 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001010 " -a appname enable app-level tracing for a comma "
1011 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001012 " -b N use a trace buffer size of N KB\n"
1013 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001014 " -f filename use the categories written in a file as space-separated\n"
1015 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001016 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001017 " -n ignore signals\n"
1018 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001019 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001020 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001021 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001022 " --async_dump dump the current contents of circular trace buffer\n"
1023 " --async_stop stop tracing and dump the current contents of circular\n"
1024 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001025 " --stream stream trace to stdout as it enters the trace buffer\n"
1026 " Note: this can take significant CPU time, and is best\n"
1027 " used for measuring things that are not affected by\n"
1028 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001029 " --list_categories\n"
1030 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001031 " -o filename write the trace to the specified file instead\n"
1032 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001033 );
1034}
1035
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001036bool findTraceFiles()
1037{
1038 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1039 static const std::string tracefs_path = "/sys/kernel/tracing/";
1040 static const std::string trace_file = "trace_marker";
1041
1042 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1043 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1044
1045 if (!tracefs && !debugfs) {
1046 fprintf(stderr, "Error: Did not find trace folder\n");
1047 return false;
1048 }
1049
1050 if (tracefs) {
1051 g_traceFolder = tracefs_path;
1052 } else {
1053 g_traceFolder = debugfs_path;
1054 }
1055
1056 return true;
1057}
1058
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001059int main(int argc, char **argv)
1060{
1061 bool async = false;
1062 bool traceStart = true;
1063 bool traceStop = true;
1064 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001065 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001066
1067 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1068 showHelp(argv[0]);
1069 exit(0);
1070 }
1071
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001072 if (!findTraceFiles()) {
1073 fprintf(stderr, "No trace folder found\n");
1074 exit(-1);
1075 }
1076
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001077 for (;;) {
1078 int ret;
1079 int option_index = 0;
1080 static struct option long_options[] = {
1081 {"async_start", no_argument, 0, 0 },
1082 {"async_stop", no_argument, 0, 0 },
1083 {"async_dump", no_argument, 0, 0 },
1084 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +01001085 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001086 { 0, 0, 0, 0 }
1087 };
1088
John Reck40b26b42016-03-30 09:44:36 -07001089 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001090 long_options, &option_index);
1091
1092 if (ret < 0) {
1093 for (int i = optind; i < argc; i++) {
1094 if (!setCategoryEnable(argv[i], true)) {
1095 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1096 exit(1);
1097 }
1098 }
1099 break;
1100 }
1101
1102 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001103 case 'a':
1104 g_debugAppCmdLine = optarg;
1105 break;
1106
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001107 case 'b':
1108 g_traceBufferSizeKB = atoi(optarg);
1109 break;
1110
1111 case 'c':
1112 g_traceOverwrite = true;
1113 break;
1114
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001115 case 'f':
1116 g_categoriesFile = optarg;
1117 break;
1118
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001119 case 'k':
1120 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001121 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001122
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001123 case 'n':
1124 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001125 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001126
1127 case 's':
1128 g_initialSleepSecs = atoi(optarg);
1129 break;
1130
1131 case 't':
1132 g_traceDurationSeconds = atoi(optarg);
1133 break;
1134
1135 case 'z':
1136 g_compress = true;
1137 break;
1138
John Reck40b26b42016-03-30 09:44:36 -07001139 case 'o':
1140 g_outputFile = optarg;
1141 break;
1142
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001143 case 0:
1144 if (!strcmp(long_options[option_index].name, "async_start")) {
1145 async = true;
1146 traceStop = false;
1147 traceDump = false;
1148 g_traceOverwrite = true;
1149 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1150 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001151 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001152 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1153 async = true;
1154 traceStart = false;
1155 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001156 } else if (!strcmp(long_options[option_index].name, "stream")) {
1157 traceStream = true;
1158 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001159 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1160 listSupportedCategories();
1161 exit(0);
1162 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001163 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001164
1165 default:
1166 fprintf(stderr, "\n");
1167 showHelp(argv[0]);
1168 exit(-1);
1169 break;
1170 }
1171 }
1172
1173 registerSigHandler();
1174
1175 if (g_initialSleepSecs > 0) {
1176 sleep(g_initialSleepSecs);
1177 }
1178
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001179 bool ok = true;
1180 ok &= setUpTrace();
1181 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001182
1183 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001184 if (!traceStream) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001185 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001186 fflush(stdout);
1187 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001188
1189 // We clear the trace after starting it because tracing gets enabled for
1190 // each CPU individually in the kernel. Having the beginning of the trace
1191 // contain entries from only one CPU can cause "begin" entries without a
1192 // matching "end" entry to show up if a task gets migrated from one CPU to
1193 // another.
1194 ok = clearTrace();
1195
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001196 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001197 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001198 // Sleep to allow the trace to be captured.
1199 struct timespec timeLeft;
1200 timeLeft.tv_sec = g_traceDurationSeconds;
1201 timeLeft.tv_nsec = 0;
1202 do {
1203 if (g_traceAborted) {
1204 break;
1205 }
1206 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1207 }
Martijn Coenend9535872015-11-26 10:00:55 +01001208
1209 if (traceStream) {
1210 streamTrace();
1211 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001212 }
1213
1214 // Stop the trace and restore the default settings.
1215 if (traceStop)
1216 stopTrace();
1217
1218 if (ok && traceDump) {
1219 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001220 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001221 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001222 int outFd = STDOUT_FILENO;
1223 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001224 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001225 }
1226 if (outFd == -1) {
1227 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1228 } else {
1229 dprintf(outFd, "TRACE:\n");
1230 dumpTrace(outFd);
1231 if (g_outputFile) {
1232 close(outFd);
1233 }
1234 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001235 } else {
1236 printf("\ntrace aborted.\n");
1237 fflush(stdout);
1238 }
1239 clearTrace();
1240 } else if (!ok) {
1241 fprintf(stderr, "unable to start tracing\n");
1242 }
1243
1244 // Reset the trace buffer size to 1.
1245 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001246 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001247
1248 return g_traceAborted ? 1 : 0;
1249}