blob: f8e0ad58aa4ac06670bb55607d30fde65c734b7b [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
453 char buf[4097];
454 ssize_t n = read(fd, buf, 4096);
455 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
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800478// Enable or disable the kernel's use of the global clock. Disabling the global
479// clock will result in the kernel using a per-CPU local clock.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700480// Any write to the trace_clock sysfs file will reset the buffer, so only
481// update it if the requested value is not the current value.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800482static bool setGlobalClockEnable(bool enable)
483{
Colin Crossb1ce49b2014-08-20 14:28:47 -0700484 const char *clock = enable ? "global" : "local";
485
486 if (isTraceClock(clock)) {
487 return true;
488 }
489
490 return writeStr(k_traceClockPath, clock);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800491}
492
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700493static bool setPrintTgidEnableIfPresent(bool enable)
494{
495 if (fileExists(k_printTgidPath)) {
496 return setKernelOptionEnable(k_printTgidPath, enable);
497 }
498 return true;
499}
500
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800501// Poke all the binder-enabled processes in the system to get them to re-read
502// their system properties.
503static bool pokeBinderServices()
504{
505 sp<IServiceManager> sm = defaultServiceManager();
506 Vector<String16> services = sm->listServices();
507 for (size_t i = 0; i < services.size(); i++) {
508 sp<IBinder> obj = sm->checkService(services[i]);
509 if (obj != NULL) {
510 Parcel data;
511 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
512 NULL, 0) != OK) {
513 if (false) {
514 // XXX: For some reason this fails on tablets trying to
515 // poke the "phone" service. It's not clear whether some
516 // are expected to fail.
517 String8 svc(services[i]);
518 fprintf(stderr, "error poking binder service %s\n",
519 svc.string());
520 return false;
521 }
522 }
523 }
524 }
525 return true;
526}
527
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100528// Poke all the HAL processes in the system to get them to re-read
529// their system properties.
530static void pokeHalServices()
531{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100532 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100533 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100534 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100535 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100536
537 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800538
539 if (sm == nullptr) {
540 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
541 return;
542 }
543
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800544 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100545 for (size_t i = 0; i < interfaces.size(); i++) {
546 string fqInstanceName = interfaces[i];
547 string::size_type n = fqInstanceName.find("/");
548 if (n == std::string::npos || interfaces[i].size() == n+1)
549 continue;
550 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
551 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100552 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
553 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100554 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100555 continue;
556 }
Carmen Jackson73206122017-04-18 15:37:57 -0700557
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100558 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700559 if (interface == nullptr) {
560 // ignore
561 continue;
562 }
563
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100564 auto notifyRet = interface->notifySyspropsChanged();
565 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100566 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800567 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100568 }
569 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800570 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100571 // TODO(b/34242478) fix this when we determine the correct ACL
572 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800573 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100574}
575
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800576// Set the trace tags that userland tracing uses, and poke the running
577// processes to pick up the new value.
578static bool setTagsProperty(uint64_t tags)
579{
sergeyv4144eff2016-04-28 11:40:04 -0700580 char buf[PROPERTY_VALUE_MAX];
581 snprintf(buf, sizeof(buf), "%#" PRIx64, tags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800582 if (property_set(k_traceTagsProperty, buf) < 0) {
583 fprintf(stderr, "error setting trace tags system property\n");
584 return false;
585 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700586 return true;
587}
588
sergeyv4144eff2016-04-28 11:40:04 -0700589static void clearAppProperties()
590{
591 char buf[PROPERTY_KEY_MAX];
592 for (int i = 0; i < MAX_PACKAGES; i++) {
593 snprintf(buf, sizeof(buf), k_traceAppsPropertyTemplate, i);
594 if (property_set(buf, "") < 0) {
595 fprintf(stderr, "failed to clear system property: %s\n", buf);
596 }
597 }
598 if (property_set(k_traceAppsNumberProperty, "") < 0) {
599 fprintf(stderr, "failed to clear system property: %s",
600 k_traceAppsNumberProperty);
601 }
602}
603
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700604// Set the system property that indicates which apps should perform
605// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700606static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700607{
sergeyv4144eff2016-04-28 11:40:04 -0700608 char buf[PROPERTY_KEY_MAX];
609 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700610 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700611 while (start != NULL) {
612 if (i == MAX_PACKAGES) {
613 fprintf(stderr, "error: only 16 packages could be traced at once\n");
614 clearAppProperties();
615 return false;
616 }
617 char* end = strchr(start, ',');
618 if (end != NULL) {
619 *end = '\0';
620 end++;
621 }
622 snprintf(buf, sizeof(buf), k_traceAppsPropertyTemplate, i);
623 if (property_set(buf, start) < 0) {
624 fprintf(stderr, "error setting trace app %d property to %s\n", i, buf);
625 clearAppProperties();
626 return false;
627 }
628 start = end;
629 i++;
630 }
631
632 snprintf(buf, sizeof(buf), "%d", i);
633 if (property_set(k_traceAppsNumberProperty, buf) < 0) {
634 fprintf(stderr, "error setting trace app number property to %s\n", buf);
635 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700636 return false;
637 }
638 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800639}
640
641// Disable all /sys/ enable files.
642static bool disableKernelTraceEvents() {
643 bool ok = true;
644 for (int i = 0; i < NELEM(k_categories); i++) {
645 const TracingCategory &c = k_categories[i];
646 for (int j = 0; j < MAX_SYS_FILES; j++) {
647 const char* path = c.sysfiles[j].path;
648 if (path != NULL && fileIsWritable(path)) {
649 ok &= setKernelOptionEnable(path, false);
650 }
651 }
652 }
653 return ok;
654}
655
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700656// Verify that the comma separated list of functions are being traced by the
657// kernel.
658static bool verifyKernelTraceFuncs(const char* funcs)
659{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100660 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800661 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100662 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700663 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100664 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700665 }
666
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100667 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700668
669 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100670 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700671 bool ok = true;
672 char* myFuncs = strdup(funcs);
673 char* func = strtok(myFuncs, ",");
674 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100675 if (!strchr(func, '*')) {
676 String8 fancyFunc = String8::format("\n%s\n", func);
677 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
678 if (!found || func[0] == '\0') {
679 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
680 "to trace.\n", func);
681 ok = false;
682 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700683 }
684 func = strtok(NULL, ",");
685 }
686 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700687 return ok;
688}
689
690// Set the comma separated list of functions that the kernel is to trace.
691static bool setKernelTraceFuncs(const char* funcs)
692{
693 bool ok = true;
694
695 if (funcs == NULL || funcs[0] == '\0') {
696 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700697 if (fileIsWritable(k_currentTracerPath)) {
698 ok &= writeStr(k_currentTracerPath, "nop");
699 }
700 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700701 ok &= truncateFile(k_ftraceFilterPath);
702 }
703 } else {
704 // Enable kernel function tracing.
705 ok &= writeStr(k_currentTracerPath, "function_graph");
706 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
707 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
708 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
709 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
710
711 // Set the requested filter functions.
712 ok &= truncateFile(k_ftraceFilterPath);
713 char* myFuncs = strdup(funcs);
714 char* func = strtok(myFuncs, ",");
715 while (func) {
716 ok &= appendStr(k_ftraceFilterPath, func);
717 func = strtok(NULL, ",");
718 }
719 free(myFuncs);
720
721 // Verify that the set functions are being traced.
722 if (ok) {
723 ok &= verifyKernelTraceFuncs(funcs);
724 }
725 }
726
727 return ok;
728}
729
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900730static bool setCategoryEnable(const char* name, bool enable)
731{
732 for (int i = 0; i < NELEM(k_categories); i++) {
733 const TracingCategory& c = k_categories[i];
734 if (strcmp(name, c.name) == 0) {
735 if (isCategorySupported(c)) {
736 g_categoryEnables[i] = enable;
737 return true;
738 } else {
739 if (isCategorySupportedForRoot(c)) {
740 fprintf(stderr, "error: category \"%s\" requires root "
741 "privileges.\n", name);
742 } else {
743 fprintf(stderr, "error: category \"%s\" is not supported "
744 "on this device.\n", name);
745 }
746 return false;
747 }
748 }
749 }
750 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
751 return false;
752}
753
754static bool setCategoriesEnableFromFile(const char* categories_file)
755{
756 if (!categories_file) {
757 return true;
758 }
759 Tokenizer* tokenizer = NULL;
760 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
761 return false;
762 }
763 bool ok = true;
764 while (!tokenizer->isEol()) {
765 String8 token = tokenizer->nextToken(" ");
766 if (token.isEmpty()) {
767 tokenizer->skipDelimiters(" ");
768 continue;
769 }
770 ok &= setCategoryEnable(token.string(), true);
771 }
772 delete tokenizer;
773 return ok;
774}
775
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700776// Set all the kernel tracing settings to the desired state for this trace
777// capture.
778static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800779{
780 bool ok = true;
781
782 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900783 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800784 ok &= setTraceOverwriteEnable(g_traceOverwrite);
785 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
786 ok &= setGlobalClockEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700787 ok &= setPrintTgidEnableIfPresent(true);
788 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800789
790 // Set up the tags property.
791 uint64_t tags = 0;
792 for (int i = 0; i < NELEM(k_categories); i++) {
793 if (g_categoryEnables[i]) {
794 const TracingCategory &c = k_categories[i];
795 tags |= c.tags;
796 }
797 }
798 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700799
800 bool coreServicesTagEnabled = false;
801 for (int i = 0; i < NELEM(k_categories); i++) {
802 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
803 coreServicesTagEnabled = g_categoryEnables[i];
804 }
805 }
806
807 std::string packageList(g_debugAppCmdLine);
808 if (coreServicesTagEnabled) {
809 char value[PROPERTY_VALUE_MAX];
810 property_get(k_coreServicesProp, value, "");
811 if (!packageList.empty()) {
812 packageList += ",";
813 }
814 packageList += value;
815 }
Dan Austin09a79872016-05-31 13:27:03 -0700816 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700817 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100818 pokeHalServices();
Corey Tabakaf70680e2017-04-14 17:52:17 -0700819 ok &= ServiceUtility::PokeServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800820
821 // Disable all the sysfs enables. This is done as a separate loop from
822 // the enables to allow the same enable to exist in multiple categories.
823 ok &= disableKernelTraceEvents();
824
825 // Enable all the sysfs enables that are in an enabled category.
826 for (int i = 0; i < NELEM(k_categories); i++) {
827 if (g_categoryEnables[i]) {
828 const TracingCategory &c = k_categories[i];
829 for (int j = 0; j < MAX_SYS_FILES; j++) {
830 const char* path = c.sysfiles[j].path;
831 bool required = c.sysfiles[j].required == REQ;
832 if (path != NULL) {
833 if (fileIsWritable(path)) {
834 ok &= setKernelOptionEnable(path, true);
835 } else if (required) {
836 fprintf(stderr, "error writing file %s\n", path);
837 ok = false;
838 }
839 }
840 }
841 }
842 }
843
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800844 return ok;
845}
846
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700847// Reset all the kernel tracing settings to their default state.
848static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800849{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800850 // Disable all tracing that we're able to.
851 disableKernelTraceEvents();
852
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700853 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800854 setTagsProperty(0);
sergeyv4144eff2016-04-28 11:40:04 -0700855 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700856 pokeBinderServices();
Corey Tabakaf70680e2017-04-14 17:52:17 -0700857 ServiceUtility::PokeServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800858
859 // Set the options back to their defaults.
860 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700861 setTraceBufferSizeKB(1);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800862 setGlobalClockEnable(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700863 setPrintTgidEnableIfPresent(false);
864 setKernelTraceFuncs(NULL);
865}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800866
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700867
868// Enable tracing in the kernel.
869static bool startTrace()
870{
871 return setTracingEnabled(true);
872}
873
874// Disable tracing in the kernel.
875static void stopTrace()
876{
877 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800878}
879
Martijn Coenend9535872015-11-26 10:00:55 +0100880// Read data from the tracing pipe and forward to stdout
881static void streamTrace()
882{
883 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800884 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100885 if (traceFD == -1) {
886 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
887 strerror(errno), errno);
888 return;
889 }
890 while (!g_traceAborted) {
891 ssize_t bytes_read = read(traceFD, trace_data, 4096);
892 if (bytes_read > 0) {
893 write(STDOUT_FILENO, trace_data, bytes_read);
894 fflush(stdout);
895 } else {
896 if (!g_traceAborted) {
897 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
898 bytes_read, errno, strerror(errno));
899 }
900 break;
901 }
902 }
903}
904
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800905// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700906static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800907{
John Reck6c8ac922016-03-28 11:25:30 -0700908 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800909 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800910 if (traceFD == -1) {
911 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
912 strerror(errno), errno);
913 return;
914 }
915
916 if (g_compress) {
917 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800918 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700919
920 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800921 if (result != Z_OK) {
922 fprintf(stderr, "error initializing zlib: %d\n", result);
923 close(traceFD);
924 return;
925 }
926
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700927 constexpr size_t bufSize = 64*1024;
928 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
929 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
930 if (!in || !out) {
931 fprintf(stderr, "couldn't allocate buffers\n");
932 close(traceFD);
933 return;
934 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800935
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700936 int flush = Z_NO_FLUSH;
937
938 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800939 zs.avail_out = bufSize;
940
941 do {
942
943 if (zs.avail_in == 0) {
944 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700945 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800946 if (result < 0) {
947 fprintf(stderr, "error reading trace: %s (%d)\n",
948 strerror(errno), errno);
949 result = Z_STREAM_END;
950 break;
951 } else if (result == 0) {
952 flush = Z_FINISH;
953 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700954 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800955 zs.avail_in = result;
956 }
957 }
958
959 if (zs.avail_out == 0) {
960 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700961 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800962 if ((size_t)result < bufSize) {
963 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
964 strerror(errno), errno);
965 result = Z_STREAM_END; // skip deflate error message
966 zs.avail_out = bufSize; // skip the final write
967 break;
968 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700969 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800970 zs.avail_out = bufSize;
971 }
972
973 } while ((result = deflate(&zs, flush)) == Z_OK);
974
975 if (result != Z_STREAM_END) {
976 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
977 }
978
979 if (zs.avail_out < bufSize) {
980 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -0700981 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800982 if ((size_t)result < bytes) {
983 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
984 strerror(errno), errno);
985 }
986 }
987
988 result = deflateEnd(&zs);
989 if (result != Z_OK) {
990 fprintf(stderr, "error cleaning up zlib: %d\n", result);
991 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800992 } else {
993 ssize_t sent = 0;
John Reck40b26b42016-03-30 09:44:36 -0700994 while ((sent = sendfile(outFd, traceFD, NULL, 64*1024*1024)) > 0);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800995 if (sent == -1) {
996 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
997 errno);
998 }
999 }
1000
1001 close(traceFD);
1002}
1003
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001004static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001005{
1006 if (!g_nohup) {
1007 g_traceAborted = true;
1008 }
1009}
1010
1011static void registerSigHandler()
1012{
1013 struct sigaction sa;
1014 sigemptyset(&sa.sa_mask);
1015 sa.sa_flags = 0;
1016 sa.sa_handler = handleSignal;
1017 sigaction(SIGHUP, &sa, NULL);
1018 sigaction(SIGINT, &sa, NULL);
1019 sigaction(SIGQUIT, &sa, NULL);
1020 sigaction(SIGTERM, &sa, NULL);
1021}
1022
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001023static void listSupportedCategories()
1024{
1025 for (int i = 0; i < NELEM(k_categories); i++) {
1026 const TracingCategory& c = k_categories[i];
1027 if (isCategorySupported(c)) {
1028 printf(" %10s - %s\n", c.name, c.longname);
1029 }
1030 }
1031}
1032
1033// Print the command usage help to stderr.
1034static void showHelp(const char *cmd)
1035{
1036 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1037 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001038 " -a appname enable app-level tracing for a comma "
1039 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001040 " -b N use a trace buffer size of N KB\n"
1041 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001042 " -f filename use the categories written in a file as space-separated\n"
1043 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001044 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001045 " -n ignore signals\n"
1046 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001047 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001048 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001049 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001050 " --async_dump dump the current contents of circular trace buffer\n"
1051 " --async_stop stop tracing and dump the current contents of circular\n"
1052 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001053 " --stream stream trace to stdout as it enters the trace buffer\n"
1054 " Note: this can take significant CPU time, and is best\n"
1055 " used for measuring things that are not affected by\n"
1056 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001057 " --list_categories\n"
1058 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001059 " -o filename write the trace to the specified file instead\n"
1060 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001061 );
1062}
1063
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001064bool findTraceFiles()
1065{
1066 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1067 static const std::string tracefs_path = "/sys/kernel/tracing/";
1068 static const std::string trace_file = "trace_marker";
1069
1070 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1071 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1072
1073 if (!tracefs && !debugfs) {
1074 fprintf(stderr, "Error: Did not find trace folder\n");
1075 return false;
1076 }
1077
1078 if (tracefs) {
1079 g_traceFolder = tracefs_path;
1080 } else {
1081 g_traceFolder = debugfs_path;
1082 }
1083
1084 return true;
1085}
1086
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001087int main(int argc, char **argv)
1088{
1089 bool async = false;
1090 bool traceStart = true;
1091 bool traceStop = true;
1092 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001093 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001094
1095 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1096 showHelp(argv[0]);
1097 exit(0);
1098 }
1099
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001100 if (!findTraceFiles()) {
1101 fprintf(stderr, "No trace folder found\n");
1102 exit(-1);
1103 }
1104
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001105 for (;;) {
1106 int ret;
1107 int option_index = 0;
1108 static struct option long_options[] = {
1109 {"async_start", no_argument, 0, 0 },
1110 {"async_stop", no_argument, 0, 0 },
1111 {"async_dump", no_argument, 0, 0 },
1112 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +01001113 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001114 { 0, 0, 0, 0 }
1115 };
1116
John Reck40b26b42016-03-30 09:44:36 -07001117 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001118 long_options, &option_index);
1119
1120 if (ret < 0) {
1121 for (int i = optind; i < argc; i++) {
1122 if (!setCategoryEnable(argv[i], true)) {
1123 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1124 exit(1);
1125 }
1126 }
1127 break;
1128 }
1129
1130 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001131 case 'a':
1132 g_debugAppCmdLine = optarg;
1133 break;
1134
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001135 case 'b':
1136 g_traceBufferSizeKB = atoi(optarg);
1137 break;
1138
1139 case 'c':
1140 g_traceOverwrite = true;
1141 break;
1142
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001143 case 'f':
1144 g_categoriesFile = optarg;
1145 break;
1146
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001147 case 'k':
1148 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001149 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001150
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001151 case 'n':
1152 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001153 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001154
1155 case 's':
1156 g_initialSleepSecs = atoi(optarg);
1157 break;
1158
1159 case 't':
1160 g_traceDurationSeconds = atoi(optarg);
1161 break;
1162
1163 case 'z':
1164 g_compress = true;
1165 break;
1166
John Reck40b26b42016-03-30 09:44:36 -07001167 case 'o':
1168 g_outputFile = optarg;
1169 break;
1170
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001171 case 0:
1172 if (!strcmp(long_options[option_index].name, "async_start")) {
1173 async = true;
1174 traceStop = false;
1175 traceDump = false;
1176 g_traceOverwrite = true;
1177 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1178 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001179 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001180 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1181 async = true;
1182 traceStart = false;
1183 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001184 } else if (!strcmp(long_options[option_index].name, "stream")) {
1185 traceStream = true;
1186 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001187 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1188 listSupportedCategories();
1189 exit(0);
1190 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001191 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001192
1193 default:
1194 fprintf(stderr, "\n");
1195 showHelp(argv[0]);
1196 exit(-1);
1197 break;
1198 }
1199 }
1200
1201 registerSigHandler();
1202
1203 if (g_initialSleepSecs > 0) {
1204 sleep(g_initialSleepSecs);
1205 }
1206
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001207 bool ok = true;
1208 ok &= setUpTrace();
1209 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001210
1211 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001212 if (!traceStream) {
1213 printf("capturing trace...");
1214 fflush(stdout);
1215 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001216
1217 // We clear the trace after starting it because tracing gets enabled for
1218 // each CPU individually in the kernel. Having the beginning of the trace
1219 // contain entries from only one CPU can cause "begin" entries without a
1220 // matching "end" entry to show up if a task gets migrated from one CPU to
1221 // another.
1222 ok = clearTrace();
1223
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001224 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001225 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001226 // Sleep to allow the trace to be captured.
1227 struct timespec timeLeft;
1228 timeLeft.tv_sec = g_traceDurationSeconds;
1229 timeLeft.tv_nsec = 0;
1230 do {
1231 if (g_traceAborted) {
1232 break;
1233 }
1234 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1235 }
Martijn Coenend9535872015-11-26 10:00:55 +01001236
1237 if (traceStream) {
1238 streamTrace();
1239 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001240 }
1241
1242 // Stop the trace and restore the default settings.
1243 if (traceStop)
1244 stopTrace();
1245
1246 if (ok && traceDump) {
1247 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001248 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001249 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001250 int outFd = STDOUT_FILENO;
1251 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001252 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001253 }
1254 if (outFd == -1) {
1255 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1256 } else {
1257 dprintf(outFd, "TRACE:\n");
1258 dumpTrace(outFd);
1259 if (g_outputFile) {
1260 close(outFd);
1261 }
1262 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001263 } else {
1264 printf("\ntrace aborted.\n");
1265 fflush(stdout);
1266 }
1267 clearTrace();
1268 } else if (!ok) {
1269 fprintf(stderr, "unable to start tracing\n");
1270 }
1271
1272 // Reset the trace buffer size to 1.
1273 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001274 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001275
1276 return g_traceAborted ? 1 : 0;
1277}