blob: 4d1840802928df2f8510041617086d9697a790f4 [file] [log] [blame]
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Paul Lawrence2cd93cc2017-01-17 09:50:18 -080017#define LOG_TAG "atrace"
John Reck40b26b42016-03-30 09:44:36 -070018
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080019#include <errno.h>
20#include <fcntl.h>
21#include <getopt.h>
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070022#include <inttypes.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080023#include <signal.h>
24#include <stdarg.h>
25#include <stdbool.h>
26#include <stdio.h>
27#include <stdlib.h>
Elliott Hughes3da5d232015-01-25 08:35:20 -080028#include <string.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080029#include <time.h>
Martijn Coenend9535872015-11-26 10:00:55 +010030#include <unistd.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080031#include <zlib.h>
32
Carmen Jacksonea826792017-05-05 11:42:32 -070033#include <fstream>
Elliott Hughesa252f4d2016-07-21 17:12:15 -070034#include <memory>
35
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080036#include <binder/IBinder.h>
37#include <binder/IServiceManager.h>
38#include <binder/Parcel.h>
39
Martijn Coenenee9b97e2016-11-16 16:00:26 +010040#include <android/hidl/manager/1.0/IServiceManager.h>
41#include <hidl/ServiceManagement.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080042
43#include <utils/String8.h>
John Reck469a1942015-03-26 15:31:35 -070044#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +090045#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080046#include <utils/Trace.h>
Stephane Gasparinid8419c22016-03-02 13:45:15 +010047#include <android-base/file.h>
Elliott Hughes5fd6ff62017-03-28 14:55:31 -070048#include <android-base/macros.h>
49#include <android-base/properties.h>
50#include <android-base/stringprintf.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080051
52using namespace android;
53
Martijn Coenenee9b97e2016-11-16 16:00:26 +010054using std::string;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080055
sergeyv4144eff2016-04-28 11:40:04 -070056#define MAX_SYS_FILES 10
57#define MAX_PACKAGES 16
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080058
59const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
sergeyv4144eff2016-04-28 11:40:04 -070060
61const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
62const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070063const char* k_coreServiceCategory = "core_services";
64const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080065
66typedef enum { OPT, REQ } requiredness ;
67
68struct TracingCategory {
69 // The name identifying the category.
70 const char* name;
71
72 // A longer description of the category.
73 const char* longname;
74
75 // The userland tracing tags that the category enables.
76 uint64_t tags;
77
78 // The fname==NULL terminated list of /sys/ files that the category
79 // enables.
80 struct {
81 // Whether the file must be writable in order to enable the tracing
82 // category.
83 requiredness required;
84
85 // The path to the enable file.
86 const char* path;
87 } sysfiles[MAX_SYS_FILES];
88};
89
90/* Tracing categories */
91static const TracingCategory k_categories[] = {
Jamie Gennisb2a89e32013-03-11 19:37:53 -070092 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, { } },
93 { "input", "Input", ATRACE_TAG_INPUT, { } },
94 { "view", "View System", ATRACE_TAG_VIEW, { } },
95 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
96 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
97 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -050098 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070099 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
100 { "video", "Video", ATRACE_TAG_VIDEO, { } },
101 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
102 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700103 { "app", "Application", ATRACE_TAG_APP, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -0700104 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -0700105 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -0700106 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -0700107 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700108 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 14:36:20 -0700109 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-07-01 01:46:25 +0900110 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Greg Hackmannbbd7d992014-12-01 14:43:34 -0800111 { "database", "Database", ATRACE_TAG_DATABASE, { } },
Felipe Leme0f97c1d2016-09-07 11:33:26 -0700112 { "network", "Network", ATRACE_TAG_NETWORK, { } },
Josh Gao468b4cb2016-11-29 10:55:21 -0800113 { "adb", "ADB", ATRACE_TAG_ADB, { } },
sergeyvdb404152016-05-02 19:26:07 -0700114 { k_coreServiceCategory, "Core services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700115 { "sched", "CPU Scheduling", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800116 { REQ, "events/sched/sched_switch/enable" },
117 { REQ, "events/sched/sched_wakeup/enable" },
118 { OPT, "events/sched/sched_blocked_reason/enable" },
119 { OPT, "events/sched/sched_cpu_hotplug/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800120 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700121 { "irq", "IRQ Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800122 { REQ, "events/irq/enable" },
123 { OPT, "events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700124 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100125 { "i2c", "I2C Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800126 { REQ, "events/i2c/enable" },
127 { REQ, "events/i2c/i2c_read/enable" },
128 { REQ, "events/i2c/i2c_write/enable" },
129 { REQ, "events/i2c/i2c_result/enable" },
130 { REQ, "events/i2c/i2c_reply/enable" },
131 { OPT, "events/i2c/smbus_read/enable" },
132 { OPT, "events/i2c/smbus_write/enable" },
133 { OPT, "events/i2c/smbus_result/enable" },
134 { OPT, "events/i2c/smbus_reply/enable" },
Michael Wright43fb6782016-08-18 19:56:43 +0100135 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700136 { "freq", "CPU Frequency", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800137 { REQ, "events/power/cpu_frequency/enable" },
138 { OPT, "events/power/clock_set_rate/enable" },
139 { OPT, "events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800140 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700141 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800142 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800143 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700144 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800145 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800146 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700147 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800148 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
149 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
150 { OPT, "events/f2fs/f2fs_write_begin/enable" },
151 { OPT, "events/f2fs/f2fs_write_end/enable" },
152 { OPT, "events/ext4/ext4_da_write_begin/enable" },
153 { OPT, "events/ext4/ext4_da_write_end/enable" },
154 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
155 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
156 { REQ, "events/block/block_rq_issue/enable" },
157 { REQ, "events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800158 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700159 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800160 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700161 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700162 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800163 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800164 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700165 { "sync", "Synchronization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800166 { REQ, "events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800167 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700168 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800169 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800170 } },
Colin Cross580407f2014-08-18 15:22:13 -0700171 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800172 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
173 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
174 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
175 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Marc Hittingerf1f62e32017-05-17 15:57:43 -0700176 { REQ, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700177 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800178 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800179 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800180 } },
Scott Bauerae473362015-06-08 16:32:36 -0700181 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800182 { REQ, "events/binder/binder_transaction/enable" },
183 { REQ, "events/binder/binder_transaction_received/enable" },
Martijn Coenen7f3d7a22017-05-26 09:50:55 -0700184 { OPT, "events/binder/binder_set_priority/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700185 } },
186 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800187 { OPT, "events/binder/binder_lock/enable" },
188 { OPT, "events/binder/binder_locked/enable" },
189 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700190 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200191 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800192 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200193 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800194};
195
196/* Command line options */
197static int g_traceDurationSeconds = 5;
198static bool g_traceOverwrite = false;
199static int g_traceBufferSizeKB = 2048;
200static bool g_compress = false;
201static bool g_nohup = false;
202static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900203static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700204static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700205static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700206static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800207
208/* Global state */
209static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700210static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800211static std::string g_traceFolder;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800212
213/* Sys file paths */
214static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800215 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800216
217static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800218 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800219
220static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800221 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800222
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700223static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800224 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700225
226static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800227 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700228
229static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800230 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700231
232static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800233 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700234
235static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800236 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700237
238static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800239 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700240
241static const char* k_funcgraphDurationPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800242 "options/funcgraph-duration";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700243
244static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800245 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700246
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800247static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800248 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800249
250static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800251 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800252
Martijn Coenend9535872015-11-26 10:00:55 +0100253static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800254 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100255
John Reck469a1942015-03-26 15:31:35 -0700256static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800257 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700258
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800259// Check whether a file exists.
260static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800261 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800262}
263
264// Check whether a file is writable.
265static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800266 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800267}
268
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700269// Truncate a file.
270static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800271{
Jamie Gennis43122e72013-03-21 14:06:31 -0700272 // This uses creat rather than truncate because some of the debug kernel
273 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
274 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800275 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700276 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800277 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700278 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700279 return false;
280 }
281
Jamie Gennis43122e72013-03-21 14:06:31 -0700282 close(traceFD);
283
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700284 return true;
285}
286
287static bool _writeStr(const char* filename, const char* str, int flags)
288{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800289 std::string fullFilename = g_traceFolder + filename;
290 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800291 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800292 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800293 strerror(errno), errno);
294 return false;
295 }
296
297 bool ok = true;
298 ssize_t len = strlen(str);
299 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800300 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800301 strerror(errno), errno);
302 ok = false;
303 }
304
305 close(fd);
306
307 return ok;
308}
309
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700310// Write a string to a file, returning true if the write was successful.
311static bool writeStr(const char* filename, const char* str)
312{
313 return _writeStr(filename, str, O_WRONLY);
314}
315
316// Append a string to a file, returning true if the write was successful.
317static bool appendStr(const char* filename, const char* str)
318{
319 return _writeStr(filename, str, O_APPEND|O_WRONLY);
320}
321
John Reck469a1942015-03-26 15:31:35 -0700322static void writeClockSyncMarker()
323{
324 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200325 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800326 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200327 if (fd == -1) {
328 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
329 strerror(errno), errno);
330 return;
331 }
John Reck469a1942015-03-26 15:31:35 -0700332 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200333
334 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
335 if (write(fd, buffer, len) != len) {
336 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
337 }
338
339 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
340 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
341 if (write(fd, buffer, len) != len) {
342 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
343 }
344
345 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700346}
347
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800348// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
349// file.
350static bool setKernelOptionEnable(const char* filename, bool enable)
351{
352 return writeStr(filename, enable ? "1" : "0");
353}
354
355// Check whether the category is supported on the device with the current
356// rootness. A category is supported only if all its required /sys/ files are
357// writable and if enabling the category will enable one or more tracing tags
358// or /sys/ files.
359static bool isCategorySupported(const TracingCategory& category)
360{
sergeyvdb404152016-05-02 19:26:07 -0700361 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700362 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700363 }
364
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800365 bool ok = category.tags != 0;
366 for (int i = 0; i < MAX_SYS_FILES; i++) {
367 const char* path = category.sysfiles[i].path;
368 bool req = category.sysfiles[i].required == REQ;
369 if (path != NULL) {
370 if (req) {
371 if (!fileIsWritable(path)) {
372 return false;
373 } else {
374 ok = true;
375 }
376 } else {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800377 ok = true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800378 }
379 }
380 }
381 return ok;
382}
383
384// Check whether the category would be supported on the device if the user
385// were root. This function assumes that root is able to write to any file
386// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700387// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800388static bool isCategorySupportedForRoot(const TracingCategory& category)
389{
390 bool ok = category.tags != 0;
391 for (int i = 0; i < MAX_SYS_FILES; i++) {
392 const char* path = category.sysfiles[i].path;
393 bool req = category.sysfiles[i].required == REQ;
394 if (path != NULL) {
395 if (req) {
396 if (!fileExists(path)) {
397 return false;
398 } else {
399 ok = true;
400 }
401 } else {
402 ok |= fileExists(path);
403 }
404 }
405 }
406 return ok;
407}
408
409// Enable or disable overwriting of the kernel trace buffers. Disabling this
410// will cause tracing to stop once the trace buffers have filled up.
411static bool setTraceOverwriteEnable(bool enable)
412{
413 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
414}
415
416// Enable or disable kernel tracing.
417static bool setTracingEnabled(bool enable)
418{
419 return setKernelOptionEnable(k_tracingOnPath, enable);
420}
421
422// Clear the contents of the kernel trace.
423static bool clearTrace()
424{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700425 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800426}
427
428// Set the size of the kernel's trace buffer in kilobytes.
429static bool setTraceBufferSizeKB(int size)
430{
431 char str[32] = "1";
432 int len;
433 if (size < 1) {
434 size = 1;
435 }
436 snprintf(str, 32, "%d", size);
437 return writeStr(k_traceBufferSizePath, str);
438}
439
Carmen Jacksonea826792017-05-05 11:42:32 -0700440// Set the clock to the best available option while tracing. Use 'boot' if it's
441// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700442// Any write to the trace_clock sysfs file will reset the buffer, so only
443// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700444static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800445{
Carmen Jacksonea826792017-05-05 11:42:32 -0700446 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
447 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
448 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700449
Carmen Jacksonea826792017-05-05 11:42:32 -0700450 std::string newClock;
451 if (clockStr.find("boot") != std::string::npos) {
452 newClock = "boot";
453 } else if (clockStr.find("mono") != std::string::npos) {
454 newClock = "mono";
455 } else {
456 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700457 }
458
Carmen Jacksonea826792017-05-05 11:42:32 -0700459 size_t begin = clockStr.find("[") + 1;
460 size_t end = clockStr.find("]");
461 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
462 return true;
463 }
464 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800465}
466
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700467static bool setPrintTgidEnableIfPresent(bool enable)
468{
469 if (fileExists(k_printTgidPath)) {
470 return setKernelOptionEnable(k_printTgidPath, enable);
471 }
472 return true;
473}
474
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800475// Poke all the binder-enabled processes in the system to get them to re-read
476// their system properties.
477static bool pokeBinderServices()
478{
479 sp<IServiceManager> sm = defaultServiceManager();
480 Vector<String16> services = sm->listServices();
481 for (size_t i = 0; i < services.size(); i++) {
482 sp<IBinder> obj = sm->checkService(services[i]);
483 if (obj != NULL) {
484 Parcel data;
485 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
486 NULL, 0) != OK) {
487 if (false) {
488 // XXX: For some reason this fails on tablets trying to
489 // poke the "phone" service. It's not clear whether some
490 // are expected to fail.
491 String8 svc(services[i]);
492 fprintf(stderr, "error poking binder service %s\n",
493 svc.string());
494 return false;
495 }
496 }
497 }
498 }
499 return true;
500}
501
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100502// Poke all the HAL processes in the system to get them to re-read
503// their system properties.
504static void pokeHalServices()
505{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100506 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100507 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100508 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100509 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100510
511 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800512
513 if (sm == nullptr) {
514 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
515 return;
516 }
517
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800518 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100519 for (size_t i = 0; i < interfaces.size(); i++) {
520 string fqInstanceName = interfaces[i];
521 string::size_type n = fqInstanceName.find("/");
522 if (n == std::string::npos || interfaces[i].size() == n+1)
523 continue;
524 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
525 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100526 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
527 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100528 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100529 continue;
530 }
Carmen Jackson73206122017-04-18 15:37:57 -0700531
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100532 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700533 if (interface == nullptr) {
534 // ignore
535 continue;
536 }
537
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100538 auto notifyRet = interface->notifySyspropsChanged();
539 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100540 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800541 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100542 }
543 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800544 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100545 // TODO(b/34242478) fix this when we determine the correct ACL
546 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800547 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100548}
549
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800550// Set the trace tags that userland tracing uses, and poke the running
551// processes to pick up the new value.
552static bool setTagsProperty(uint64_t tags)
553{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700554 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
555 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800556 fprintf(stderr, "error setting trace tags system property\n");
557 return false;
558 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700559 return true;
560}
561
sergeyv4144eff2016-04-28 11:40:04 -0700562static void clearAppProperties()
563{
sergeyv4144eff2016-04-28 11:40:04 -0700564 for (int i = 0; i < MAX_PACKAGES; i++) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700565 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
566 if (!android::base::SetProperty(key, "")) {
567 fprintf(stderr, "failed to clear system property: %s\n", key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700568 }
569 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700570 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700571 fprintf(stderr, "failed to clear system property: %s",
572 k_traceAppsNumberProperty);
573 }
574}
575
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700576// Set the system property that indicates which apps should perform
577// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700578static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700579{
sergeyv4144eff2016-04-28 11:40:04 -0700580 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700581 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700582 while (start != NULL) {
583 if (i == MAX_PACKAGES) {
584 fprintf(stderr, "error: only 16 packages could be traced at once\n");
585 clearAppProperties();
586 return false;
587 }
588 char* end = strchr(start, ',');
589 if (end != NULL) {
590 *end = '\0';
591 end++;
592 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700593 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
594 if (!android::base::SetProperty(key, start)) {
595 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700596 clearAppProperties();
597 return false;
598 }
599 start = end;
600 i++;
601 }
602
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700603 std::string value = android::base::StringPrintf("%d", i);
604 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
605 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700606 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700607 return false;
608 }
609 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800610}
611
612// Disable all /sys/ enable files.
613static bool disableKernelTraceEvents() {
614 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700615 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800616 const TracingCategory &c = k_categories[i];
617 for (int j = 0; j < MAX_SYS_FILES; j++) {
618 const char* path = c.sysfiles[j].path;
619 if (path != NULL && fileIsWritable(path)) {
620 ok &= setKernelOptionEnable(path, false);
621 }
622 }
623 }
624 return ok;
625}
626
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700627// Verify that the comma separated list of functions are being traced by the
628// kernel.
629static bool verifyKernelTraceFuncs(const char* funcs)
630{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100631 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800632 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100633 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700634 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100635 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700636 }
637
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100638 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700639
640 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100641 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700642 bool ok = true;
643 char* myFuncs = strdup(funcs);
644 char* func = strtok(myFuncs, ",");
645 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100646 if (!strchr(func, '*')) {
647 String8 fancyFunc = String8::format("\n%s\n", func);
648 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
649 if (!found || func[0] == '\0') {
650 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
651 "to trace.\n", func);
652 ok = false;
653 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700654 }
655 func = strtok(NULL, ",");
656 }
657 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700658 return ok;
659}
660
661// Set the comma separated list of functions that the kernel is to trace.
662static bool setKernelTraceFuncs(const char* funcs)
663{
664 bool ok = true;
665
666 if (funcs == NULL || funcs[0] == '\0') {
667 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700668 if (fileIsWritable(k_currentTracerPath)) {
669 ok &= writeStr(k_currentTracerPath, "nop");
670 }
671 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700672 ok &= truncateFile(k_ftraceFilterPath);
673 }
674 } else {
675 // Enable kernel function tracing.
676 ok &= writeStr(k_currentTracerPath, "function_graph");
677 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
678 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
679 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
680 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
681
682 // Set the requested filter functions.
683 ok &= truncateFile(k_ftraceFilterPath);
684 char* myFuncs = strdup(funcs);
685 char* func = strtok(myFuncs, ",");
686 while (func) {
687 ok &= appendStr(k_ftraceFilterPath, func);
688 func = strtok(NULL, ",");
689 }
690 free(myFuncs);
691
692 // Verify that the set functions are being traced.
693 if (ok) {
694 ok &= verifyKernelTraceFuncs(funcs);
695 }
696 }
697
698 return ok;
699}
700
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900701static bool setCategoryEnable(const char* name, bool enable)
702{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700703 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900704 const TracingCategory& c = k_categories[i];
705 if (strcmp(name, c.name) == 0) {
706 if (isCategorySupported(c)) {
707 g_categoryEnables[i] = enable;
708 return true;
709 } else {
710 if (isCategorySupportedForRoot(c)) {
711 fprintf(stderr, "error: category \"%s\" requires root "
712 "privileges.\n", name);
713 } else {
714 fprintf(stderr, "error: category \"%s\" is not supported "
715 "on this device.\n", name);
716 }
717 return false;
718 }
719 }
720 }
721 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
722 return false;
723}
724
725static bool setCategoriesEnableFromFile(const char* categories_file)
726{
727 if (!categories_file) {
728 return true;
729 }
730 Tokenizer* tokenizer = NULL;
731 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
732 return false;
733 }
734 bool ok = true;
735 while (!tokenizer->isEol()) {
736 String8 token = tokenizer->nextToken(" ");
737 if (token.isEmpty()) {
738 tokenizer->skipDelimiters(" ");
739 continue;
740 }
741 ok &= setCategoryEnable(token.string(), true);
742 }
743 delete tokenizer;
744 return ok;
745}
746
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700747// Set all the kernel tracing settings to the desired state for this trace
748// capture.
749static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800750{
751 bool ok = true;
752
753 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900754 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800755 ok &= setTraceOverwriteEnable(g_traceOverwrite);
756 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
Carmen Jacksonea826792017-05-05 11:42:32 -0700757 ok &= setClock();
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700758 ok &= setPrintTgidEnableIfPresent(true);
759 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800760
761 // Set up the tags property.
762 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700763 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800764 if (g_categoryEnables[i]) {
765 const TracingCategory &c = k_categories[i];
766 tags |= c.tags;
767 }
768 }
769 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700770
771 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700772 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700773 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
774 coreServicesTagEnabled = g_categoryEnables[i];
775 }
776 }
777
778 std::string packageList(g_debugAppCmdLine);
779 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700780 if (!packageList.empty()) {
781 packageList += ",";
782 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700783 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700784 }
Dan Austin09a79872016-05-31 13:27:03 -0700785 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700786 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100787 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800788
789 // Disable all the sysfs enables. This is done as a separate loop from
790 // the enables to allow the same enable to exist in multiple categories.
791 ok &= disableKernelTraceEvents();
792
793 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700794 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800795 if (g_categoryEnables[i]) {
796 const TracingCategory &c = k_categories[i];
797 for (int j = 0; j < MAX_SYS_FILES; j++) {
798 const char* path = c.sysfiles[j].path;
799 bool required = c.sysfiles[j].required == REQ;
800 if (path != NULL) {
801 if (fileIsWritable(path)) {
802 ok &= setKernelOptionEnable(path, true);
803 } else if (required) {
804 fprintf(stderr, "error writing file %s\n", path);
805 ok = false;
806 }
807 }
808 }
809 }
810 }
811
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800812 return ok;
813}
814
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700815// Reset all the kernel tracing settings to their default state.
816static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800817{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800818 // Disable all tracing that we're able to.
819 disableKernelTraceEvents();
820
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700821 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800822 setTagsProperty(0);
sergeyv4144eff2016-04-28 11:40:04 -0700823 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700824 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800825
826 // Set the options back to their defaults.
827 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700828 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700829 setPrintTgidEnableIfPresent(false);
830 setKernelTraceFuncs(NULL);
831}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800832
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700833
834// Enable tracing in the kernel.
835static bool startTrace()
836{
837 return setTracingEnabled(true);
838}
839
840// Disable tracing in the kernel.
841static void stopTrace()
842{
843 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800844}
845
Martijn Coenend9535872015-11-26 10:00:55 +0100846// Read data from the tracing pipe and forward to stdout
847static void streamTrace()
848{
849 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800850 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100851 if (traceFD == -1) {
852 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
853 strerror(errno), errno);
854 return;
855 }
856 while (!g_traceAborted) {
857 ssize_t bytes_read = read(traceFD, trace_data, 4096);
858 if (bytes_read > 0) {
859 write(STDOUT_FILENO, trace_data, bytes_read);
860 fflush(stdout);
861 } else {
862 if (!g_traceAborted) {
863 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
864 bytes_read, errno, strerror(errno));
865 }
866 break;
867 }
868 }
869}
870
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800871// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700872static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800873{
John Reck6c8ac922016-03-28 11:25:30 -0700874 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800875 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800876 if (traceFD == -1) {
877 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
878 strerror(errno), errno);
879 return;
880 }
881
882 if (g_compress) {
883 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800884 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700885
886 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800887 if (result != Z_OK) {
888 fprintf(stderr, "error initializing zlib: %d\n", result);
889 close(traceFD);
890 return;
891 }
892
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700893 constexpr size_t bufSize = 64*1024;
894 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
895 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
896 if (!in || !out) {
897 fprintf(stderr, "couldn't allocate buffers\n");
898 close(traceFD);
899 return;
900 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800901
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700902 int flush = Z_NO_FLUSH;
903
904 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800905 zs.avail_out = bufSize;
906
907 do {
908
909 if (zs.avail_in == 0) {
910 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700911 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800912 if (result < 0) {
913 fprintf(stderr, "error reading trace: %s (%d)\n",
914 strerror(errno), errno);
915 result = Z_STREAM_END;
916 break;
917 } else if (result == 0) {
918 flush = Z_FINISH;
919 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700920 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800921 zs.avail_in = result;
922 }
923 }
924
925 if (zs.avail_out == 0) {
926 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700927 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800928 if ((size_t)result < bufSize) {
929 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
930 strerror(errno), errno);
931 result = Z_STREAM_END; // skip deflate error message
932 zs.avail_out = bufSize; // skip the final write
933 break;
934 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700935 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800936 zs.avail_out = bufSize;
937 }
938
939 } while ((result = deflate(&zs, flush)) == Z_OK);
940
941 if (result != Z_STREAM_END) {
942 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
943 }
944
945 if (zs.avail_out < bufSize) {
946 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -0700947 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800948 if ((size_t)result < bytes) {
949 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
950 strerror(errno), errno);
951 }
952 }
953
954 result = deflateEnd(&zs);
955 if (result != Z_OK) {
956 fprintf(stderr, "error cleaning up zlib: %d\n", result);
957 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800958 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -0700959 char buf[4096];
960 ssize_t rc;
961 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
962 if (!android::base::WriteFully(outFd, buf, rc)) {
963 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
964 break;
965 }
966 }
967 if (rc == -1) {
968 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800969 }
970 }
971
972 close(traceFD);
973}
974
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700975static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800976{
977 if (!g_nohup) {
978 g_traceAborted = true;
979 }
980}
981
982static void registerSigHandler()
983{
984 struct sigaction sa;
985 sigemptyset(&sa.sa_mask);
986 sa.sa_flags = 0;
987 sa.sa_handler = handleSignal;
988 sigaction(SIGHUP, &sa, NULL);
989 sigaction(SIGINT, &sa, NULL);
990 sigaction(SIGQUIT, &sa, NULL);
991 sigaction(SIGTERM, &sa, NULL);
992}
993
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800994static void listSupportedCategories()
995{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700996 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800997 const TracingCategory& c = k_categories[i];
998 if (isCategorySupported(c)) {
999 printf(" %10s - %s\n", c.name, c.longname);
1000 }
1001 }
1002}
1003
1004// Print the command usage help to stderr.
1005static void showHelp(const char *cmd)
1006{
1007 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1008 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001009 " -a appname enable app-level tracing for a comma "
1010 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001011 " -b N use a trace buffer size of N KB\n"
1012 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001013 " -f filename use the categories written in a file as space-separated\n"
1014 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001015 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001016 " -n ignore signals\n"
1017 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001018 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001019 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001020 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001021 " --async_dump dump the current contents of circular trace buffer\n"
1022 " --async_stop stop tracing and dump the current contents of circular\n"
1023 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001024 " --stream stream trace to stdout as it enters the trace buffer\n"
1025 " Note: this can take significant CPU time, and is best\n"
1026 " used for measuring things that are not affected by\n"
1027 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001028 " --list_categories\n"
1029 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001030 " -o filename write the trace to the specified file instead\n"
1031 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001032 );
1033}
1034
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001035bool findTraceFiles()
1036{
1037 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1038 static const std::string tracefs_path = "/sys/kernel/tracing/";
1039 static const std::string trace_file = "trace_marker";
1040
1041 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1042 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1043
1044 if (!tracefs && !debugfs) {
1045 fprintf(stderr, "Error: Did not find trace folder\n");
1046 return false;
1047 }
1048
1049 if (tracefs) {
1050 g_traceFolder = tracefs_path;
1051 } else {
1052 g_traceFolder = debugfs_path;
1053 }
1054
1055 return true;
1056}
1057
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001058int main(int argc, char **argv)
1059{
1060 bool async = false;
1061 bool traceStart = true;
1062 bool traceStop = true;
1063 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001064 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001065
1066 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1067 showHelp(argv[0]);
1068 exit(0);
1069 }
1070
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001071 if (!findTraceFiles()) {
1072 fprintf(stderr, "No trace folder found\n");
1073 exit(-1);
1074 }
1075
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001076 for (;;) {
1077 int ret;
1078 int option_index = 0;
1079 static struct option long_options[] = {
1080 {"async_start", no_argument, 0, 0 },
1081 {"async_stop", no_argument, 0, 0 },
1082 {"async_dump", no_argument, 0, 0 },
1083 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +01001084 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001085 { 0, 0, 0, 0 }
1086 };
1087
John Reck40b26b42016-03-30 09:44:36 -07001088 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001089 long_options, &option_index);
1090
1091 if (ret < 0) {
1092 for (int i = optind; i < argc; i++) {
1093 if (!setCategoryEnable(argv[i], true)) {
1094 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1095 exit(1);
1096 }
1097 }
1098 break;
1099 }
1100
1101 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001102 case 'a':
1103 g_debugAppCmdLine = optarg;
1104 break;
1105
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001106 case 'b':
1107 g_traceBufferSizeKB = atoi(optarg);
1108 break;
1109
1110 case 'c':
1111 g_traceOverwrite = true;
1112 break;
1113
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001114 case 'f':
1115 g_categoriesFile = optarg;
1116 break;
1117
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001118 case 'k':
1119 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001120 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001121
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001122 case 'n':
1123 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001124 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001125
1126 case 's':
1127 g_initialSleepSecs = atoi(optarg);
1128 break;
1129
1130 case 't':
1131 g_traceDurationSeconds = atoi(optarg);
1132 break;
1133
1134 case 'z':
1135 g_compress = true;
1136 break;
1137
John Reck40b26b42016-03-30 09:44:36 -07001138 case 'o':
1139 g_outputFile = optarg;
1140 break;
1141
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001142 case 0:
1143 if (!strcmp(long_options[option_index].name, "async_start")) {
1144 async = true;
1145 traceStop = false;
1146 traceDump = false;
1147 g_traceOverwrite = true;
1148 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1149 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001150 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001151 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1152 async = true;
1153 traceStart = false;
1154 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001155 } else if (!strcmp(long_options[option_index].name, "stream")) {
1156 traceStream = true;
1157 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001158 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1159 listSupportedCategories();
1160 exit(0);
1161 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001162 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001163
1164 default:
1165 fprintf(stderr, "\n");
1166 showHelp(argv[0]);
1167 exit(-1);
1168 break;
1169 }
1170 }
1171
1172 registerSigHandler();
1173
1174 if (g_initialSleepSecs > 0) {
1175 sleep(g_initialSleepSecs);
1176 }
1177
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001178 bool ok = true;
1179 ok &= setUpTrace();
1180 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001181
1182 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001183 if (!traceStream) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001184 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001185 fflush(stdout);
1186 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001187
1188 // We clear the trace after starting it because tracing gets enabled for
1189 // each CPU individually in the kernel. Having the beginning of the trace
1190 // contain entries from only one CPU can cause "begin" entries without a
1191 // matching "end" entry to show up if a task gets migrated from one CPU to
1192 // another.
1193 ok = clearTrace();
1194
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001195 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001196 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001197 // Sleep to allow the trace to be captured.
1198 struct timespec timeLeft;
1199 timeLeft.tv_sec = g_traceDurationSeconds;
1200 timeLeft.tv_nsec = 0;
1201 do {
1202 if (g_traceAborted) {
1203 break;
1204 }
1205 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1206 }
Martijn Coenend9535872015-11-26 10:00:55 +01001207
1208 if (traceStream) {
1209 streamTrace();
1210 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001211 }
1212
1213 // Stop the trace and restore the default settings.
1214 if (traceStop)
1215 stopTrace();
1216
1217 if (ok && traceDump) {
1218 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001219 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001220 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001221 int outFd = STDOUT_FILENO;
1222 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001223 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001224 }
1225 if (outFd == -1) {
1226 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1227 } else {
1228 dprintf(outFd, "TRACE:\n");
1229 dumpTrace(outFd);
1230 if (g_outputFile) {
1231 close(outFd);
1232 }
1233 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001234 } else {
1235 printf("\ntrace aborted.\n");
1236 fflush(stdout);
1237 }
1238 clearTrace();
1239 } else if (!ok) {
1240 fprintf(stderr, "unable to start tracing\n");
1241 }
1242
1243 // Reset the trace buffer size to 1.
1244 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001245 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001246
1247 return g_traceAborted ? 1 : 0;
1248}