blob: ed53af15fe7ec18af00098e851e19ca0078739a2 [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 <sys/sendfile.h>
30#include <time.h>
Martijn Coenend9535872015-11-26 10:00:55 +010031#include <unistd.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080032#include <zlib.h>
33
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#include <cutils/properties.h>
43
Corey Tabakaf70680e2017-04-14 17:52:17 -070044#include <pdx/default_transport/service_utility.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080045#include <utils/String8.h>
John Reck469a1942015-03-26 15:31:35 -070046#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +090047#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080048#include <utils/Trace.h>
Stephane Gasparinid8419c22016-03-02 13:45:15 +010049#include <android-base/file.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080050
51using namespace android;
Corey Tabakaf70680e2017-04-14 17:52:17 -070052using pdx::default_transport::ServiceUtility;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080053
Martijn Coenenee9b97e2016-11-16 16:00:26 +010054using std::string;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080055#define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0])))
56
sergeyv4144eff2016-04-28 11:40:04 -070057#define MAX_SYS_FILES 10
58#define MAX_PACKAGES 16
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080059
60const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
sergeyv4144eff2016-04-28 11:40:04 -070061
62const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
63const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070064const char* k_coreServiceCategory = "core_services";
65const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080066
67typedef enum { OPT, REQ } requiredness ;
68
69struct TracingCategory {
70 // The name identifying the category.
71 const char* name;
72
73 // A longer description of the category.
74 const char* longname;
75
76 // The userland tracing tags that the category enables.
77 uint64_t tags;
78
79 // The fname==NULL terminated list of /sys/ files that the category
80 // enables.
81 struct {
82 // Whether the file must be writable in order to enable the tracing
83 // category.
84 requiredness required;
85
86 // The path to the enable file.
87 const char* path;
88 } sysfiles[MAX_SYS_FILES];
89};
90
91/* Tracing categories */
92static const TracingCategory k_categories[] = {
Jamie Gennisb2a89e32013-03-11 19:37:53 -070093 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, { } },
94 { "input", "Input", ATRACE_TAG_INPUT, { } },
95 { "view", "View System", ATRACE_TAG_VIEW, { } },
96 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
97 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
98 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -050099 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700100 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
101 { "video", "Video", ATRACE_TAG_VIDEO, { } },
102 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
103 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700104 { "app", "Application", ATRACE_TAG_APP, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -0700105 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -0700106 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -0700107 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -0700108 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700109 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 14:36:20 -0700110 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-07-01 01:46:25 +0900111 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Greg Hackmannbbd7d992014-12-01 14:43:34 -0800112 { "database", "Database", ATRACE_TAG_DATABASE, { } },
Felipe Leme0f97c1d2016-09-07 11:33:26 -0700113 { "network", "Network", ATRACE_TAG_NETWORK, { } },
Josh Gao468b4cb2016-11-29 10:55:21 -0800114 { "adb", "ADB", ATRACE_TAG_ADB, { } },
sergeyvdb404152016-05-02 19:26:07 -0700115 { k_coreServiceCategory, "Core services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700116 { "sched", "CPU Scheduling", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800117 { REQ, "events/sched/sched_switch/enable" },
118 { REQ, "events/sched/sched_wakeup/enable" },
119 { OPT, "events/sched/sched_blocked_reason/enable" },
120 { OPT, "events/sched/sched_cpu_hotplug/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800121 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700122 { "irq", "IRQ Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800123 { REQ, "events/irq/enable" },
124 { OPT, "events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700125 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100126 { "i2c", "I2C Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800127 { REQ, "events/i2c/enable" },
128 { REQ, "events/i2c/i2c_read/enable" },
129 { REQ, "events/i2c/i2c_write/enable" },
130 { REQ, "events/i2c/i2c_result/enable" },
131 { REQ, "events/i2c/i2c_reply/enable" },
132 { OPT, "events/i2c/smbus_read/enable" },
133 { OPT, "events/i2c/smbus_write/enable" },
134 { OPT, "events/i2c/smbus_result/enable" },
135 { OPT, "events/i2c/smbus_reply/enable" },
Michael Wright43fb6782016-08-18 19:56:43 +0100136 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700137 { "freq", "CPU Frequency", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800138 { REQ, "events/power/cpu_frequency/enable" },
139 { OPT, "events/power/clock_set_rate/enable" },
140 { OPT, "events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800141 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700142 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800143 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800144 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700145 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800146 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800147 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700148 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800149 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
150 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
151 { OPT, "events/f2fs/f2fs_write_begin/enable" },
152 { OPT, "events/f2fs/f2fs_write_end/enable" },
153 { OPT, "events/ext4/ext4_da_write_begin/enable" },
154 { OPT, "events/ext4/ext4_da_write_end/enable" },
155 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
156 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
157 { REQ, "events/block/block_rq_issue/enable" },
158 { REQ, "events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800159 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700160 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800161 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700162 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700163 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800164 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800165 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700166 { "sync", "Synchronization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800167 { REQ, "events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800168 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700169 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800170 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800171 } },
Colin Cross580407f2014-08-18 15:22:13 -0700172 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800173 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
174 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
175 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
176 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700177 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800178 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800179 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800180 } },
Scott Bauerae473362015-06-08 16:32:36 -0700181 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800182 { REQ, "events/binder/binder_transaction/enable" },
183 { REQ, "events/binder/binder_transaction_received/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700184 } },
185 { "binder_lock", "Binder global lock trace", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800186 { REQ, "events/binder/binder_lock/enable" },
187 { REQ, "events/binder/binder_locked/enable" },
188 { REQ, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700189 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200190 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800191 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200192 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800193};
194
195/* Command line options */
196static int g_traceDurationSeconds = 5;
197static bool g_traceOverwrite = false;
198static int g_traceBufferSizeKB = 2048;
199static bool g_compress = false;
200static bool g_nohup = false;
201static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900202static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700203static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700204static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700205static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800206
207/* Global state */
208static bool g_traceAborted = false;
209static bool g_categoryEnables[NELEM(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800210static std::string g_traceFolder;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800211
212/* Sys file paths */
213static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800214 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800215
216static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800217 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800218
219static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800220 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800221
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700222static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800223 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700224
225static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800226 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700227
228static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800229 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700230
231static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800232 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700233
234static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800235 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700236
237static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800238 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700239
240static const char* k_funcgraphDurationPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800241 "options/funcgraph-duration";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700242
243static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800244 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700245
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800246static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800247 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800248
249static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800250 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800251
Martijn Coenend9535872015-11-26 10:00:55 +0100252static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800253 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100254
John Reck469a1942015-03-26 15:31:35 -0700255static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800256 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700257
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800258// Check whether a file exists.
259static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800260 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800261}
262
263// Check whether a file is writable.
264static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800265 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800266}
267
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700268// Truncate a file.
269static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800270{
Jamie Gennis43122e72013-03-21 14:06:31 -0700271 // This uses creat rather than truncate because some of the debug kernel
272 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
273 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800274 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700275 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800276 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700277 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700278 return false;
279 }
280
Jamie Gennis43122e72013-03-21 14:06:31 -0700281 close(traceFD);
282
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700283 return true;
284}
285
286static bool _writeStr(const char* filename, const char* str, int flags)
287{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800288 std::string fullFilename = g_traceFolder + filename;
289 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800290 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800291 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800292 strerror(errno), errno);
293 return false;
294 }
295
296 bool ok = true;
297 ssize_t len = strlen(str);
298 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800299 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800300 strerror(errno), errno);
301 ok = false;
302 }
303
304 close(fd);
305
306 return ok;
307}
308
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700309// Write a string to a file, returning true if the write was successful.
310static bool writeStr(const char* filename, const char* str)
311{
312 return _writeStr(filename, str, O_WRONLY);
313}
314
315// Append a string to a file, returning true if the write was successful.
316static bool appendStr(const char* filename, const char* str)
317{
318 return _writeStr(filename, str, O_APPEND|O_WRONLY);
319}
320
John Reck469a1942015-03-26 15:31:35 -0700321static void writeClockSyncMarker()
322{
323 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200324 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800325 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200326 if (fd == -1) {
327 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
328 strerror(errno), errno);
329 return;
330 }
John Reck469a1942015-03-26 15:31:35 -0700331 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200332
333 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
334 if (write(fd, buffer, len) != len) {
335 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
336 }
337
338 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
339 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
340 if (write(fd, buffer, len) != len) {
341 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
342 }
343
344 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700345}
346
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800347// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
348// file.
349static bool setKernelOptionEnable(const char* filename, bool enable)
350{
351 return writeStr(filename, enable ? "1" : "0");
352}
353
354// Check whether the category is supported on the device with the current
355// rootness. A category is supported only if all its required /sys/ files are
356// writable and if enabling the category will enable one or more tracing tags
357// or /sys/ files.
358static bool isCategorySupported(const TracingCategory& category)
359{
sergeyvdb404152016-05-02 19:26:07 -0700360 if (strcmp(category.name, k_coreServiceCategory) == 0) {
361 char value[PROPERTY_VALUE_MAX];
362 property_get(k_coreServicesProp, value, "");
363 return strlen(value) != 0;
364 }
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 {
378 ok |= fileIsWritable(path);
379 }
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
Colin Crossb1ce49b2014-08-20 14:28:47 -0700441// Read the trace_clock sysfs file and return true if it matches the requested
442// value. The trace_clock file format is:
443// local [global] counter uptime perf
444static bool isTraceClock(const char *mode)
445{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800446 int fd = open((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
Colin Crossb1ce49b2014-08-20 14:28:47 -0700447 if (fd == -1) {
448 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceClockPath,
449 strerror(errno), errno);
450 return false;
451 }
452
Carmen Jackson56a2ba02017-04-28 10:34:50 -0700453 char buf[100];
454 ssize_t n = read(fd, buf, 99);
Colin Crossb1ce49b2014-08-20 14:28:47 -0700455 close(fd);
456 if (n == -1) {
457 fprintf(stderr, "error reading %s: %s (%d)\n", k_traceClockPath,
458 strerror(errno), errno);
459 return false;
460 }
461 buf[n] = '\0';
462
463 char *start = strchr(buf, '[');
464 if (start == NULL) {
465 return false;
466 }
467 start++;
468
469 char *end = strchr(start, ']');
470 if (end == NULL) {
471 return false;
472 }
473 *end = '\0';
474
475 return strcmp(mode, start) == 0;
476}
477
Carmen Jackson56a2ba02017-04-28 10:34:50 -0700478// Read the trace_clock sysfs file and return true if it contains the requested
479// value. The trace_clock file format is:
480// local [global] counter uptime perf
481static bool traceClockContains(const char *mode)
482{
483 int fd = open((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
484 if (fd == -1) {
485 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceClockPath,
486 strerror(errno), errno);
487 return false;
488 }
489
490 char buf[100];
491 ssize_t n = read(fd, buf, 99);
492 close(fd);
493 if (n == -1) {
494 fprintf(stderr, "error reading %s: %s (%d)\n", k_traceClockPath,
495 strerror(errno), errno);
496 return false;
497 }
498 buf[n] = '\0';
499
500 return strstr(buf, mode) != NULL;
501}
502
503// Set the clock to the best available option while tracing. Use 'boot' if it's
504// available; otherwise, use 'mono'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700505// Any write to the trace_clock sysfs file will reset the buffer, so only
506// update it if the requested value is not the current value.
Carmen Jackson56a2ba02017-04-28 10:34:50 -0700507static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800508{
Carmen Jackson56a2ba02017-04-28 10:34:50 -0700509 const char* clock = traceClockContains("boot") ? "boot" : "mono";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700510
511 if (isTraceClock(clock)) {
512 return true;
513 }
514
515 return writeStr(k_traceClockPath, clock);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800516}
517
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700518static bool setPrintTgidEnableIfPresent(bool enable)
519{
520 if (fileExists(k_printTgidPath)) {
521 return setKernelOptionEnable(k_printTgidPath, enable);
522 }
523 return true;
524}
525
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800526// Poke all the binder-enabled processes in the system to get them to re-read
527// their system properties.
528static bool pokeBinderServices()
529{
530 sp<IServiceManager> sm = defaultServiceManager();
531 Vector<String16> services = sm->listServices();
532 for (size_t i = 0; i < services.size(); i++) {
533 sp<IBinder> obj = sm->checkService(services[i]);
534 if (obj != NULL) {
535 Parcel data;
536 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
537 NULL, 0) != OK) {
538 if (false) {
539 // XXX: For some reason this fails on tablets trying to
540 // poke the "phone" service. It's not clear whether some
541 // are expected to fail.
542 String8 svc(services[i]);
543 fprintf(stderr, "error poking binder service %s\n",
544 svc.string());
545 return false;
546 }
547 }
548 }
549 }
550 return true;
551}
552
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100553// Poke all the HAL processes in the system to get them to re-read
554// their system properties.
555static void pokeHalServices()
556{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100557 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100558 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100559 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100560 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100561
562 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800563
564 if (sm == nullptr) {
565 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
566 return;
567 }
568
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800569 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100570 for (size_t i = 0; i < interfaces.size(); i++) {
571 string fqInstanceName = interfaces[i];
572 string::size_type n = fqInstanceName.find("/");
573 if (n == std::string::npos || interfaces[i].size() == n+1)
574 continue;
575 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
576 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100577 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
578 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100579 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100580 continue;
581 }
Carmen Jackson73206122017-04-18 15:37:57 -0700582
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100583 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700584 if (interface == nullptr) {
585 // ignore
586 continue;
587 }
588
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100589 auto notifyRet = interface->notifySyspropsChanged();
590 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100591 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800592 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100593 }
594 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800595 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100596 // TODO(b/34242478) fix this when we determine the correct ACL
597 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800598 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100599}
600
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800601// Set the trace tags that userland tracing uses, and poke the running
602// processes to pick up the new value.
603static bool setTagsProperty(uint64_t tags)
604{
sergeyv4144eff2016-04-28 11:40:04 -0700605 char buf[PROPERTY_VALUE_MAX];
606 snprintf(buf, sizeof(buf), "%#" PRIx64, tags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800607 if (property_set(k_traceTagsProperty, buf) < 0) {
608 fprintf(stderr, "error setting trace tags system property\n");
609 return false;
610 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700611 return true;
612}
613
sergeyv4144eff2016-04-28 11:40:04 -0700614static void clearAppProperties()
615{
616 char buf[PROPERTY_KEY_MAX];
617 for (int i = 0; i < MAX_PACKAGES; i++) {
618 snprintf(buf, sizeof(buf), k_traceAppsPropertyTemplate, i);
619 if (property_set(buf, "") < 0) {
620 fprintf(stderr, "failed to clear system property: %s\n", buf);
621 }
622 }
623 if (property_set(k_traceAppsNumberProperty, "") < 0) {
624 fprintf(stderr, "failed to clear system property: %s",
625 k_traceAppsNumberProperty);
626 }
627}
628
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700629// Set the system property that indicates which apps should perform
630// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700631static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700632{
sergeyv4144eff2016-04-28 11:40:04 -0700633 char buf[PROPERTY_KEY_MAX];
634 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700635 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700636 while (start != NULL) {
637 if (i == MAX_PACKAGES) {
638 fprintf(stderr, "error: only 16 packages could be traced at once\n");
639 clearAppProperties();
640 return false;
641 }
642 char* end = strchr(start, ',');
643 if (end != NULL) {
644 *end = '\0';
645 end++;
646 }
647 snprintf(buf, sizeof(buf), k_traceAppsPropertyTemplate, i);
648 if (property_set(buf, start) < 0) {
649 fprintf(stderr, "error setting trace app %d property to %s\n", i, buf);
650 clearAppProperties();
651 return false;
652 }
653 start = end;
654 i++;
655 }
656
657 snprintf(buf, sizeof(buf), "%d", i);
658 if (property_set(k_traceAppsNumberProperty, buf) < 0) {
659 fprintf(stderr, "error setting trace app number property to %s\n", buf);
660 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700661 return false;
662 }
663 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800664}
665
666// Disable all /sys/ enable files.
667static bool disableKernelTraceEvents() {
668 bool ok = true;
669 for (int i = 0; i < NELEM(k_categories); i++) {
670 const TracingCategory &c = k_categories[i];
671 for (int j = 0; j < MAX_SYS_FILES; j++) {
672 const char* path = c.sysfiles[j].path;
673 if (path != NULL && fileIsWritable(path)) {
674 ok &= setKernelOptionEnable(path, false);
675 }
676 }
677 }
678 return ok;
679}
680
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700681// Verify that the comma separated list of functions are being traced by the
682// kernel.
683static bool verifyKernelTraceFuncs(const char* funcs)
684{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100685 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800686 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100687 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700688 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100689 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700690 }
691
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100692 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700693
694 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100695 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700696 bool ok = true;
697 char* myFuncs = strdup(funcs);
698 char* func = strtok(myFuncs, ",");
699 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100700 if (!strchr(func, '*')) {
701 String8 fancyFunc = String8::format("\n%s\n", func);
702 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
703 if (!found || func[0] == '\0') {
704 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
705 "to trace.\n", func);
706 ok = false;
707 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700708 }
709 func = strtok(NULL, ",");
710 }
711 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700712 return ok;
713}
714
715// Set the comma separated list of functions that the kernel is to trace.
716static bool setKernelTraceFuncs(const char* funcs)
717{
718 bool ok = true;
719
720 if (funcs == NULL || funcs[0] == '\0') {
721 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700722 if (fileIsWritable(k_currentTracerPath)) {
723 ok &= writeStr(k_currentTracerPath, "nop");
724 }
725 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700726 ok &= truncateFile(k_ftraceFilterPath);
727 }
728 } else {
729 // Enable kernel function tracing.
730 ok &= writeStr(k_currentTracerPath, "function_graph");
731 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
732 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
733 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
734 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
735
736 // Set the requested filter functions.
737 ok &= truncateFile(k_ftraceFilterPath);
738 char* myFuncs = strdup(funcs);
739 char* func = strtok(myFuncs, ",");
740 while (func) {
741 ok &= appendStr(k_ftraceFilterPath, func);
742 func = strtok(NULL, ",");
743 }
744 free(myFuncs);
745
746 // Verify that the set functions are being traced.
747 if (ok) {
748 ok &= verifyKernelTraceFuncs(funcs);
749 }
750 }
751
752 return ok;
753}
754
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900755static bool setCategoryEnable(const char* name, bool enable)
756{
757 for (int i = 0; i < NELEM(k_categories); i++) {
758 const TracingCategory& c = k_categories[i];
759 if (strcmp(name, c.name) == 0) {
760 if (isCategorySupported(c)) {
761 g_categoryEnables[i] = enable;
762 return true;
763 } else {
764 if (isCategorySupportedForRoot(c)) {
765 fprintf(stderr, "error: category \"%s\" requires root "
766 "privileges.\n", name);
767 } else {
768 fprintf(stderr, "error: category \"%s\" is not supported "
769 "on this device.\n", name);
770 }
771 return false;
772 }
773 }
774 }
775 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
776 return false;
777}
778
779static bool setCategoriesEnableFromFile(const char* categories_file)
780{
781 if (!categories_file) {
782 return true;
783 }
784 Tokenizer* tokenizer = NULL;
785 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
786 return false;
787 }
788 bool ok = true;
789 while (!tokenizer->isEol()) {
790 String8 token = tokenizer->nextToken(" ");
791 if (token.isEmpty()) {
792 tokenizer->skipDelimiters(" ");
793 continue;
794 }
795 ok &= setCategoryEnable(token.string(), true);
796 }
797 delete tokenizer;
798 return ok;
799}
800
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700801// Set all the kernel tracing settings to the desired state for this trace
802// capture.
803static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800804{
805 bool ok = true;
806
807 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900808 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800809 ok &= setTraceOverwriteEnable(g_traceOverwrite);
810 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
Carmen Jackson56a2ba02017-04-28 10:34:50 -0700811 ok &= setClock();
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700812 ok &= setPrintTgidEnableIfPresent(true);
813 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800814
815 // Set up the tags property.
816 uint64_t tags = 0;
817 for (int i = 0; i < NELEM(k_categories); i++) {
818 if (g_categoryEnables[i]) {
819 const TracingCategory &c = k_categories[i];
820 tags |= c.tags;
821 }
822 }
823 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700824
825 bool coreServicesTagEnabled = false;
826 for (int i = 0; i < NELEM(k_categories); i++) {
827 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
828 coreServicesTagEnabled = g_categoryEnables[i];
829 }
830 }
831
832 std::string packageList(g_debugAppCmdLine);
833 if (coreServicesTagEnabled) {
834 char value[PROPERTY_VALUE_MAX];
835 property_get(k_coreServicesProp, value, "");
836 if (!packageList.empty()) {
837 packageList += ",";
838 }
839 packageList += value;
840 }
Dan Austin09a79872016-05-31 13:27:03 -0700841 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700842 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100843 pokeHalServices();
Corey Tabakaf70680e2017-04-14 17:52:17 -0700844 ok &= ServiceUtility::PokeServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800845
846 // Disable all the sysfs enables. This is done as a separate loop from
847 // the enables to allow the same enable to exist in multiple categories.
848 ok &= disableKernelTraceEvents();
849
850 // Enable all the sysfs enables that are in an enabled category.
851 for (int i = 0; i < NELEM(k_categories); i++) {
852 if (g_categoryEnables[i]) {
853 const TracingCategory &c = k_categories[i];
854 for (int j = 0; j < MAX_SYS_FILES; j++) {
855 const char* path = c.sysfiles[j].path;
856 bool required = c.sysfiles[j].required == REQ;
857 if (path != NULL) {
858 if (fileIsWritable(path)) {
859 ok &= setKernelOptionEnable(path, true);
860 } else if (required) {
861 fprintf(stderr, "error writing file %s\n", path);
862 ok = false;
863 }
864 }
865 }
866 }
867 }
868
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800869 return ok;
870}
871
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700872// Reset all the kernel tracing settings to their default state.
873static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800874{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800875 // Disable all tracing that we're able to.
876 disableKernelTraceEvents();
877
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700878 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800879 setTagsProperty(0);
sergeyv4144eff2016-04-28 11:40:04 -0700880 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700881 pokeBinderServices();
Corey Tabakaf70680e2017-04-14 17:52:17 -0700882 ServiceUtility::PokeServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800883
884 // Set the options back to their defaults.
885 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700886 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700887 setPrintTgidEnableIfPresent(false);
888 setKernelTraceFuncs(NULL);
889}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800890
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700891
892// Enable tracing in the kernel.
893static bool startTrace()
894{
895 return setTracingEnabled(true);
896}
897
898// Disable tracing in the kernel.
899static void stopTrace()
900{
901 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800902}
903
Martijn Coenend9535872015-11-26 10:00:55 +0100904// Read data from the tracing pipe and forward to stdout
905static void streamTrace()
906{
907 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800908 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100909 if (traceFD == -1) {
910 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
911 strerror(errno), errno);
912 return;
913 }
914 while (!g_traceAborted) {
915 ssize_t bytes_read = read(traceFD, trace_data, 4096);
916 if (bytes_read > 0) {
917 write(STDOUT_FILENO, trace_data, bytes_read);
918 fflush(stdout);
919 } else {
920 if (!g_traceAborted) {
921 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
922 bytes_read, errno, strerror(errno));
923 }
924 break;
925 }
926 }
927}
928
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800929// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700930static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800931{
John Reck6c8ac922016-03-28 11:25:30 -0700932 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800933 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800934 if (traceFD == -1) {
935 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
936 strerror(errno), errno);
937 return;
938 }
939
940 if (g_compress) {
941 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800942 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700943
944 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800945 if (result != Z_OK) {
946 fprintf(stderr, "error initializing zlib: %d\n", result);
947 close(traceFD);
948 return;
949 }
950
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700951 constexpr size_t bufSize = 64*1024;
952 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
953 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
954 if (!in || !out) {
955 fprintf(stderr, "couldn't allocate buffers\n");
956 close(traceFD);
957 return;
958 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800959
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700960 int flush = Z_NO_FLUSH;
961
962 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800963 zs.avail_out = bufSize;
964
965 do {
966
967 if (zs.avail_in == 0) {
968 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700969 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800970 if (result < 0) {
971 fprintf(stderr, "error reading trace: %s (%d)\n",
972 strerror(errno), errno);
973 result = Z_STREAM_END;
974 break;
975 } else if (result == 0) {
976 flush = Z_FINISH;
977 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700978 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800979 zs.avail_in = result;
980 }
981 }
982
983 if (zs.avail_out == 0) {
984 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700985 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800986 if ((size_t)result < bufSize) {
987 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
988 strerror(errno), errno);
989 result = Z_STREAM_END; // skip deflate error message
990 zs.avail_out = bufSize; // skip the final write
991 break;
992 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700993 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800994 zs.avail_out = bufSize;
995 }
996
997 } while ((result = deflate(&zs, flush)) == Z_OK);
998
999 if (result != Z_STREAM_END) {
1000 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
1001 }
1002
1003 if (zs.avail_out < bufSize) {
1004 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -07001005 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001006 if ((size_t)result < bytes) {
1007 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1008 strerror(errno), errno);
1009 }
1010 }
1011
1012 result = deflateEnd(&zs);
1013 if (result != Z_OK) {
1014 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1015 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001016 } else {
1017 ssize_t sent = 0;
John Reck40b26b42016-03-30 09:44:36 -07001018 while ((sent = sendfile(outFd, traceFD, NULL, 64*1024*1024)) > 0);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001019 if (sent == -1) {
1020 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
1021 errno);
1022 }
1023 }
1024
1025 close(traceFD);
1026}
1027
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001028static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001029{
1030 if (!g_nohup) {
1031 g_traceAborted = true;
1032 }
1033}
1034
1035static void registerSigHandler()
1036{
1037 struct sigaction sa;
1038 sigemptyset(&sa.sa_mask);
1039 sa.sa_flags = 0;
1040 sa.sa_handler = handleSignal;
1041 sigaction(SIGHUP, &sa, NULL);
1042 sigaction(SIGINT, &sa, NULL);
1043 sigaction(SIGQUIT, &sa, NULL);
1044 sigaction(SIGTERM, &sa, NULL);
1045}
1046
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001047static void listSupportedCategories()
1048{
1049 for (int i = 0; i < NELEM(k_categories); i++) {
1050 const TracingCategory& c = k_categories[i];
1051 if (isCategorySupported(c)) {
1052 printf(" %10s - %s\n", c.name, c.longname);
1053 }
1054 }
1055}
1056
1057// Print the command usage help to stderr.
1058static void showHelp(const char *cmd)
1059{
1060 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1061 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001062 " -a appname enable app-level tracing for a comma "
1063 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001064 " -b N use a trace buffer size of N KB\n"
1065 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001066 " -f filename use the categories written in a file as space-separated\n"
1067 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001068 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001069 " -n ignore signals\n"
1070 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001071 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001072 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001073 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001074 " --async_dump dump the current contents of circular trace buffer\n"
1075 " --async_stop stop tracing and dump the current contents of circular\n"
1076 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001077 " --stream stream trace to stdout as it enters the trace buffer\n"
1078 " Note: this can take significant CPU time, and is best\n"
1079 " used for measuring things that are not affected by\n"
1080 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001081 " --list_categories\n"
1082 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001083 " -o filename write the trace to the specified file instead\n"
1084 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001085 );
1086}
1087
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001088bool findTraceFiles()
1089{
1090 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1091 static const std::string tracefs_path = "/sys/kernel/tracing/";
1092 static const std::string trace_file = "trace_marker";
1093
1094 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1095 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1096
1097 if (!tracefs && !debugfs) {
1098 fprintf(stderr, "Error: Did not find trace folder\n");
1099 return false;
1100 }
1101
1102 if (tracefs) {
1103 g_traceFolder = tracefs_path;
1104 } else {
1105 g_traceFolder = debugfs_path;
1106 }
1107
1108 return true;
1109}
1110
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001111int main(int argc, char **argv)
1112{
1113 bool async = false;
1114 bool traceStart = true;
1115 bool traceStop = true;
1116 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001117 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001118
1119 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1120 showHelp(argv[0]);
1121 exit(0);
1122 }
1123
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001124 if (!findTraceFiles()) {
1125 fprintf(stderr, "No trace folder found\n");
1126 exit(-1);
1127 }
1128
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001129 for (;;) {
1130 int ret;
1131 int option_index = 0;
1132 static struct option long_options[] = {
1133 {"async_start", no_argument, 0, 0 },
1134 {"async_stop", no_argument, 0, 0 },
1135 {"async_dump", no_argument, 0, 0 },
1136 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +01001137 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001138 { 0, 0, 0, 0 }
1139 };
1140
John Reck40b26b42016-03-30 09:44:36 -07001141 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001142 long_options, &option_index);
1143
1144 if (ret < 0) {
1145 for (int i = optind; i < argc; i++) {
1146 if (!setCategoryEnable(argv[i], true)) {
1147 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1148 exit(1);
1149 }
1150 }
1151 break;
1152 }
1153
1154 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001155 case 'a':
1156 g_debugAppCmdLine = optarg;
1157 break;
1158
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001159 case 'b':
1160 g_traceBufferSizeKB = atoi(optarg);
1161 break;
1162
1163 case 'c':
1164 g_traceOverwrite = true;
1165 break;
1166
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001167 case 'f':
1168 g_categoriesFile = optarg;
1169 break;
1170
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001171 case 'k':
1172 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001173 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001174
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001175 case 'n':
1176 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001177 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001178
1179 case 's':
1180 g_initialSleepSecs = atoi(optarg);
1181 break;
1182
1183 case 't':
1184 g_traceDurationSeconds = atoi(optarg);
1185 break;
1186
1187 case 'z':
1188 g_compress = true;
1189 break;
1190
John Reck40b26b42016-03-30 09:44:36 -07001191 case 'o':
1192 g_outputFile = optarg;
1193 break;
1194
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001195 case 0:
1196 if (!strcmp(long_options[option_index].name, "async_start")) {
1197 async = true;
1198 traceStop = false;
1199 traceDump = false;
1200 g_traceOverwrite = true;
1201 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1202 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001203 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001204 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1205 async = true;
1206 traceStart = false;
1207 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001208 } else if (!strcmp(long_options[option_index].name, "stream")) {
1209 traceStream = true;
1210 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001211 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1212 listSupportedCategories();
1213 exit(0);
1214 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001215 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001216
1217 default:
1218 fprintf(stderr, "\n");
1219 showHelp(argv[0]);
1220 exit(-1);
1221 break;
1222 }
1223 }
1224
1225 registerSigHandler();
1226
1227 if (g_initialSleepSecs > 0) {
1228 sleep(g_initialSleepSecs);
1229 }
1230
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001231 bool ok = true;
1232 ok &= setUpTrace();
1233 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001234
1235 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001236 if (!traceStream) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001237 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001238 fflush(stdout);
1239 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001240
1241 // We clear the trace after starting it because tracing gets enabled for
1242 // each CPU individually in the kernel. Having the beginning of the trace
1243 // contain entries from only one CPU can cause "begin" entries without a
1244 // matching "end" entry to show up if a task gets migrated from one CPU to
1245 // another.
1246 ok = clearTrace();
1247
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001248 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001249 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001250 // Sleep to allow the trace to be captured.
1251 struct timespec timeLeft;
1252 timeLeft.tv_sec = g_traceDurationSeconds;
1253 timeLeft.tv_nsec = 0;
1254 do {
1255 if (g_traceAborted) {
1256 break;
1257 }
1258 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1259 }
Martijn Coenend9535872015-11-26 10:00:55 +01001260
1261 if (traceStream) {
1262 streamTrace();
1263 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001264 }
1265
1266 // Stop the trace and restore the default settings.
1267 if (traceStop)
1268 stopTrace();
1269
1270 if (ok && traceDump) {
1271 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001272 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001273 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001274 int outFd = STDOUT_FILENO;
1275 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001276 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001277 }
1278 if (outFd == -1) {
1279 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1280 } else {
1281 dprintf(outFd, "TRACE:\n");
1282 dumpTrace(outFd);
1283 if (g_outputFile) {
1284 close(outFd);
1285 }
1286 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001287 } else {
1288 printf("\ntrace aborted.\n");
1289 fflush(stdout);
1290 }
1291 clearTrace();
1292 } else if (!ok) {
1293 fprintf(stderr, "unable to start tracing\n");
1294 }
1295
1296 // Reset the trace buffer size to 1.
1297 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001298 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001299
1300 return g_traceAborted ? 1 : 0;
1301}