blob: 054b00ee3d57439cf145731b196c820b02632816 [file] [log] [blame]
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Paul Lawrence2cd93cc2017-01-17 09:50:18 -080017#define LOG_TAG "atrace"
John Reck40b26b42016-03-30 09:44:36 -070018
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080019#include <errno.h>
20#include <fcntl.h>
21#include <getopt.h>
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070022#include <inttypes.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080023#include <signal.h>
24#include <stdarg.h>
25#include <stdbool.h>
26#include <stdio.h>
27#include <stdlib.h>
Elliott Hughes3da5d232015-01-25 08:35:20 -080028#include <string.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080029#include <time.h>
Martijn Coenend9535872015-11-26 10:00:55 +010030#include <unistd.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080031#include <zlib.h>
32
Elliott Hughesa252f4d2016-07-21 17:12:15 -070033#include <memory>
34
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080035#include <binder/IBinder.h>
36#include <binder/IServiceManager.h>
37#include <binder/Parcel.h>
38
Martijn Coenenee9b97e2016-11-16 16:00:26 +010039#include <android/hidl/manager/1.0/IServiceManager.h>
40#include <hidl/ServiceManagement.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080041
42#include <utils/String8.h>
John Reck469a1942015-03-26 15:31:35 -070043#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +090044#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080045#include <utils/Trace.h>
Stephane Gasparinid8419c22016-03-02 13:45:15 +010046#include <android-base/file.h>
Elliott Hughes5fd6ff62017-03-28 14:55:31 -070047#include <android-base/macros.h>
48#include <android-base/properties.h>
49#include <android-base/stringprintf.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080050
51using namespace android;
52
Martijn Coenenee9b97e2016-11-16 16:00:26 +010053using std::string;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080054
sergeyv4144eff2016-04-28 11:40:04 -070055#define MAX_SYS_FILES 10
56#define MAX_PACKAGES 16
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080057
58const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
sergeyv4144eff2016-04-28 11:40:04 -070059
60const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
61const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070062const char* k_coreServiceCategory = "core_services";
63const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080064
65typedef enum { OPT, REQ } requiredness ;
66
67struct TracingCategory {
68 // The name identifying the category.
69 const char* name;
70
71 // A longer description of the category.
72 const char* longname;
73
74 // The userland tracing tags that the category enables.
75 uint64_t tags;
76
77 // The fname==NULL terminated list of /sys/ files that the category
78 // enables.
79 struct {
80 // Whether the file must be writable in order to enable the tracing
81 // category.
82 requiredness required;
83
84 // The path to the enable file.
85 const char* path;
86 } sysfiles[MAX_SYS_FILES];
87};
88
89/* Tracing categories */
90static const TracingCategory k_categories[] = {
Jamie Gennisb2a89e32013-03-11 19:37:53 -070091 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, { } },
92 { "input", "Input", ATRACE_TAG_INPUT, { } },
93 { "view", "View System", ATRACE_TAG_VIEW, { } },
94 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
95 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
96 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -050097 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070098 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
99 { "video", "Video", ATRACE_TAG_VIDEO, { } },
100 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
101 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700102 { "app", "Application", ATRACE_TAG_APP, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -0700103 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -0700104 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -0700105 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -0700106 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700107 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 14:36:20 -0700108 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-07-01 01:46:25 +0900109 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Greg Hackmannbbd7d992014-12-01 14:43:34 -0800110 { "database", "Database", ATRACE_TAG_DATABASE, { } },
Felipe Leme0f97c1d2016-09-07 11:33:26 -0700111 { "network", "Network", ATRACE_TAG_NETWORK, { } },
Josh Gao468b4cb2016-11-29 10:55:21 -0800112 { "adb", "ADB", ATRACE_TAG_ADB, { } },
sergeyvdb404152016-05-02 19:26:07 -0700113 { k_coreServiceCategory, "Core services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700114 { "sched", "CPU Scheduling", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800115 { REQ, "events/sched/sched_switch/enable" },
116 { REQ, "events/sched/sched_wakeup/enable" },
117 { OPT, "events/sched/sched_blocked_reason/enable" },
118 { OPT, "events/sched/sched_cpu_hotplug/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800119 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700120 { "irq", "IRQ Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800121 { REQ, "events/irq/enable" },
122 { OPT, "events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700123 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100124 { "i2c", "I2C Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800125 { REQ, "events/i2c/enable" },
126 { REQ, "events/i2c/i2c_read/enable" },
127 { REQ, "events/i2c/i2c_write/enable" },
128 { REQ, "events/i2c/i2c_result/enable" },
129 { REQ, "events/i2c/i2c_reply/enable" },
130 { OPT, "events/i2c/smbus_read/enable" },
131 { OPT, "events/i2c/smbus_write/enable" },
132 { OPT, "events/i2c/smbus_result/enable" },
133 { OPT, "events/i2c/smbus_reply/enable" },
Michael Wright43fb6782016-08-18 19:56:43 +0100134 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700135 { "freq", "CPU Frequency", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800136 { REQ, "events/power/cpu_frequency/enable" },
137 { OPT, "events/power/clock_set_rate/enable" },
138 { OPT, "events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800139 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700140 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800141 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800142 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700143 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800144 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800145 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700146 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800147 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
148 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
149 { OPT, "events/f2fs/f2fs_write_begin/enable" },
150 { OPT, "events/f2fs/f2fs_write_end/enable" },
151 { OPT, "events/ext4/ext4_da_write_begin/enable" },
152 { OPT, "events/ext4/ext4_da_write_end/enable" },
153 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
154 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
155 { REQ, "events/block/block_rq_issue/enable" },
156 { REQ, "events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800157 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700158 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800159 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700160 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700161 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800162 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800163 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700164 { "sync", "Synchronization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800165 { REQ, "events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800166 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700167 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800168 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800169 } },
Colin Cross580407f2014-08-18 15:22:13 -0700170 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800171 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
172 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
173 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
174 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700175 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800176 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800177 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800178 } },
Scott Bauerae473362015-06-08 16:32:36 -0700179 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800180 { REQ, "events/binder/binder_transaction/enable" },
181 { REQ, "events/binder/binder_transaction_received/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700182 } },
183 { "binder_lock", "Binder global lock trace", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800184 { REQ, "events/binder/binder_lock/enable" },
185 { REQ, "events/binder/binder_locked/enable" },
186 { REQ, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700187 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200188 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800189 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200190 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800191};
192
193/* Command line options */
194static int g_traceDurationSeconds = 5;
195static bool g_traceOverwrite = false;
196static int g_traceBufferSizeKB = 2048;
197static bool g_compress = false;
198static bool g_nohup = false;
199static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900200static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700201static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700202static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700203static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800204
205/* Global state */
206static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700207static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800208static std::string g_traceFolder;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800209
210/* Sys file paths */
211static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800212 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800213
214static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800215 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800216
217static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800218 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800219
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700220static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800221 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700222
223static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800224 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700225
226static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800227 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700228
229static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800230 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700231
232static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800233 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700234
235static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800236 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700237
238static const char* k_funcgraphDurationPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800239 "options/funcgraph-duration";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700240
241static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800242 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700243
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800244static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800245 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800246
247static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800248 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800249
Martijn Coenend9535872015-11-26 10:00:55 +0100250static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800251 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100252
John Reck469a1942015-03-26 15:31:35 -0700253static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800254 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700255
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800256// Check whether a file exists.
257static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800258 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800259}
260
261// Check whether a file is writable.
262static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800263 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800264}
265
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700266// Truncate a file.
267static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800268{
Jamie Gennis43122e72013-03-21 14:06:31 -0700269 // This uses creat rather than truncate because some of the debug kernel
270 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
271 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800272 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700273 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800274 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700275 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700276 return false;
277 }
278
Jamie Gennis43122e72013-03-21 14:06:31 -0700279 close(traceFD);
280
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700281 return true;
282}
283
284static bool _writeStr(const char* filename, const char* str, int flags)
285{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800286 std::string fullFilename = g_traceFolder + filename;
287 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800288 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800289 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800290 strerror(errno), errno);
291 return false;
292 }
293
294 bool ok = true;
295 ssize_t len = strlen(str);
296 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800297 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800298 strerror(errno), errno);
299 ok = false;
300 }
301
302 close(fd);
303
304 return ok;
305}
306
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700307// Write a string to a file, returning true if the write was successful.
308static bool writeStr(const char* filename, const char* str)
309{
310 return _writeStr(filename, str, O_WRONLY);
311}
312
313// Append a string to a file, returning true if the write was successful.
314static bool appendStr(const char* filename, const char* str)
315{
316 return _writeStr(filename, str, O_APPEND|O_WRONLY);
317}
318
John Reck469a1942015-03-26 15:31:35 -0700319static void writeClockSyncMarker()
320{
321 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200322 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800323 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200324 if (fd == -1) {
325 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
326 strerror(errno), errno);
327 return;
328 }
John Reck469a1942015-03-26 15:31:35 -0700329 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200330
331 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
332 if (write(fd, buffer, len) != len) {
333 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
334 }
335
336 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
337 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
338 if (write(fd, buffer, len) != len) {
339 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
340 }
341
342 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700343}
344
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800345// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
346// file.
347static bool setKernelOptionEnable(const char* filename, bool enable)
348{
349 return writeStr(filename, enable ? "1" : "0");
350}
351
352// Check whether the category is supported on the device with the current
353// rootness. A category is supported only if all its required /sys/ files are
354// writable and if enabling the category will enable one or more tracing tags
355// or /sys/ files.
356static bool isCategorySupported(const TracingCategory& category)
357{
sergeyvdb404152016-05-02 19:26:07 -0700358 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700359 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700360 }
361
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800362 bool ok = category.tags != 0;
363 for (int i = 0; i < MAX_SYS_FILES; i++) {
364 const char* path = category.sysfiles[i].path;
365 bool req = category.sysfiles[i].required == REQ;
366 if (path != NULL) {
367 if (req) {
368 if (!fileIsWritable(path)) {
369 return false;
370 } else {
371 ok = true;
372 }
373 } else {
374 ok |= fileIsWritable(path);
375 }
376 }
377 }
378 return ok;
379}
380
381// Check whether the category would be supported on the device if the user
382// were root. This function assumes that root is able to write to any file
383// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700384// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800385static bool isCategorySupportedForRoot(const TracingCategory& category)
386{
387 bool ok = category.tags != 0;
388 for (int i = 0; i < MAX_SYS_FILES; i++) {
389 const char* path = category.sysfiles[i].path;
390 bool req = category.sysfiles[i].required == REQ;
391 if (path != NULL) {
392 if (req) {
393 if (!fileExists(path)) {
394 return false;
395 } else {
396 ok = true;
397 }
398 } else {
399 ok |= fileExists(path);
400 }
401 }
402 }
403 return ok;
404}
405
406// Enable or disable overwriting of the kernel trace buffers. Disabling this
407// will cause tracing to stop once the trace buffers have filled up.
408static bool setTraceOverwriteEnable(bool enable)
409{
410 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
411}
412
413// Enable or disable kernel tracing.
414static bool setTracingEnabled(bool enable)
415{
416 return setKernelOptionEnable(k_tracingOnPath, enable);
417}
418
419// Clear the contents of the kernel trace.
420static bool clearTrace()
421{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700422 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800423}
424
425// Set the size of the kernel's trace buffer in kilobytes.
426static bool setTraceBufferSizeKB(int size)
427{
428 char str[32] = "1";
429 int len;
430 if (size < 1) {
431 size = 1;
432 }
433 snprintf(str, 32, "%d", size);
434 return writeStr(k_traceBufferSizePath, str);
435}
436
Colin Crossb1ce49b2014-08-20 14:28:47 -0700437// Read the trace_clock sysfs file and return true if it matches the requested
438// value. The trace_clock file format is:
439// local [global] counter uptime perf
440static bool isTraceClock(const char *mode)
441{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800442 int fd = open((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
Colin Crossb1ce49b2014-08-20 14:28:47 -0700443 if (fd == -1) {
444 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceClockPath,
445 strerror(errno), errno);
446 return false;
447 }
448
Carmen Jacksondc340972017-05-04 15:01:33 -0700449 char buf[4097];
450 ssize_t n = read(fd, buf, 4096);
Colin Crossb1ce49b2014-08-20 14:28:47 -0700451 close(fd);
452 if (n == -1) {
453 fprintf(stderr, "error reading %s: %s (%d)\n", k_traceClockPath,
454 strerror(errno), errno);
455 return false;
456 }
457 buf[n] = '\0';
458
459 char *start = strchr(buf, '[');
460 if (start == NULL) {
461 return false;
462 }
463 start++;
464
465 char *end = strchr(start, ']');
466 if (end == NULL) {
467 return false;
468 }
469 *end = '\0';
470
471 return strcmp(mode, start) == 0;
472}
473
Carmen Jacksondc340972017-05-04 15:01:33 -0700474// Enable or disable the kernel's use of the global clock. Disabling the global
475// clock will result in the kernel using a per-CPU local clock.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700476// Any write to the trace_clock sysfs file will reset the buffer, so only
477// update it if the requested value is not the current value.
Carmen Jacksondc340972017-05-04 15:01:33 -0700478static bool setGlobalClockEnable(bool enable)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800479{
Carmen Jacksondc340972017-05-04 15:01:33 -0700480 const char *clock = enable ? "global" : "local";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700481
482 if (isTraceClock(clock)) {
483 return true;
484 }
485
486 return writeStr(k_traceClockPath, clock);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800487}
488
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700489static bool setPrintTgidEnableIfPresent(bool enable)
490{
491 if (fileExists(k_printTgidPath)) {
492 return setKernelOptionEnable(k_printTgidPath, enable);
493 }
494 return true;
495}
496
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800497// Poke all the binder-enabled processes in the system to get them to re-read
498// their system properties.
499static bool pokeBinderServices()
500{
501 sp<IServiceManager> sm = defaultServiceManager();
502 Vector<String16> services = sm->listServices();
503 for (size_t i = 0; i < services.size(); i++) {
504 sp<IBinder> obj = sm->checkService(services[i]);
505 if (obj != NULL) {
506 Parcel data;
507 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
508 NULL, 0) != OK) {
509 if (false) {
510 // XXX: For some reason this fails on tablets trying to
511 // poke the "phone" service. It's not clear whether some
512 // are expected to fail.
513 String8 svc(services[i]);
514 fprintf(stderr, "error poking binder service %s\n",
515 svc.string());
516 return false;
517 }
518 }
519 }
520 }
521 return true;
522}
523
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100524// Poke all the HAL processes in the system to get them to re-read
525// their system properties.
526static void pokeHalServices()
527{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100528 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100529 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100530 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100531 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100532
533 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800534
535 if (sm == nullptr) {
536 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
537 return;
538 }
539
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800540 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100541 for (size_t i = 0; i < interfaces.size(); i++) {
542 string fqInstanceName = interfaces[i];
543 string::size_type n = fqInstanceName.find("/");
544 if (n == std::string::npos || interfaces[i].size() == n+1)
545 continue;
546 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
547 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100548 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
549 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100550 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100551 continue;
552 }
Carmen Jackson73206122017-04-18 15:37:57 -0700553
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100554 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700555 if (interface == nullptr) {
556 // ignore
557 continue;
558 }
559
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100560 auto notifyRet = interface->notifySyspropsChanged();
561 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100562 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800563 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100564 }
565 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800566 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100567 // TODO(b/34242478) fix this when we determine the correct ACL
568 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800569 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100570}
571
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800572// Set the trace tags that userland tracing uses, and poke the running
573// processes to pick up the new value.
574static bool setTagsProperty(uint64_t tags)
575{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700576 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
577 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800578 fprintf(stderr, "error setting trace tags system property\n");
579 return false;
580 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700581 return true;
582}
583
sergeyv4144eff2016-04-28 11:40:04 -0700584static void clearAppProperties()
585{
sergeyv4144eff2016-04-28 11:40:04 -0700586 for (int i = 0; i < MAX_PACKAGES; i++) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700587 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
588 if (!android::base::SetProperty(key, "")) {
589 fprintf(stderr, "failed to clear system property: %s\n", key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700590 }
591 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700592 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700593 fprintf(stderr, "failed to clear system property: %s",
594 k_traceAppsNumberProperty);
595 }
596}
597
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700598// Set the system property that indicates which apps should perform
599// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700600static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700601{
sergeyv4144eff2016-04-28 11:40:04 -0700602 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700603 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700604 while (start != NULL) {
605 if (i == MAX_PACKAGES) {
606 fprintf(stderr, "error: only 16 packages could be traced at once\n");
607 clearAppProperties();
608 return false;
609 }
610 char* end = strchr(start, ',');
611 if (end != NULL) {
612 *end = '\0';
613 end++;
614 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700615 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
616 if (!android::base::SetProperty(key, start)) {
617 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700618 clearAppProperties();
619 return false;
620 }
621 start = end;
622 i++;
623 }
624
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700625 std::string value = android::base::StringPrintf("%d", i);
626 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
627 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700628 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700629 return false;
630 }
631 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800632}
633
634// Disable all /sys/ enable files.
635static bool disableKernelTraceEvents() {
636 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700637 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800638 const TracingCategory &c = k_categories[i];
639 for (int j = 0; j < MAX_SYS_FILES; j++) {
640 const char* path = c.sysfiles[j].path;
641 if (path != NULL && fileIsWritable(path)) {
642 ok &= setKernelOptionEnable(path, false);
643 }
644 }
645 }
646 return ok;
647}
648
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700649// Verify that the comma separated list of functions are being traced by the
650// kernel.
651static bool verifyKernelTraceFuncs(const char* funcs)
652{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100653 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800654 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100655 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700656 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100657 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700658 }
659
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100660 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700661
662 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100663 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700664 bool ok = true;
665 char* myFuncs = strdup(funcs);
666 char* func = strtok(myFuncs, ",");
667 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100668 if (!strchr(func, '*')) {
669 String8 fancyFunc = String8::format("\n%s\n", func);
670 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
671 if (!found || func[0] == '\0') {
672 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
673 "to trace.\n", func);
674 ok = false;
675 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700676 }
677 func = strtok(NULL, ",");
678 }
679 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700680 return ok;
681}
682
683// Set the comma separated list of functions that the kernel is to trace.
684static bool setKernelTraceFuncs(const char* funcs)
685{
686 bool ok = true;
687
688 if (funcs == NULL || funcs[0] == '\0') {
689 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700690 if (fileIsWritable(k_currentTracerPath)) {
691 ok &= writeStr(k_currentTracerPath, "nop");
692 }
693 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700694 ok &= truncateFile(k_ftraceFilterPath);
695 }
696 } else {
697 // Enable kernel function tracing.
698 ok &= writeStr(k_currentTracerPath, "function_graph");
699 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
700 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
701 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
702 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
703
704 // Set the requested filter functions.
705 ok &= truncateFile(k_ftraceFilterPath);
706 char* myFuncs = strdup(funcs);
707 char* func = strtok(myFuncs, ",");
708 while (func) {
709 ok &= appendStr(k_ftraceFilterPath, func);
710 func = strtok(NULL, ",");
711 }
712 free(myFuncs);
713
714 // Verify that the set functions are being traced.
715 if (ok) {
716 ok &= verifyKernelTraceFuncs(funcs);
717 }
718 }
719
720 return ok;
721}
722
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900723static bool setCategoryEnable(const char* name, bool enable)
724{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700725 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900726 const TracingCategory& c = k_categories[i];
727 if (strcmp(name, c.name) == 0) {
728 if (isCategorySupported(c)) {
729 g_categoryEnables[i] = enable;
730 return true;
731 } else {
732 if (isCategorySupportedForRoot(c)) {
733 fprintf(stderr, "error: category \"%s\" requires root "
734 "privileges.\n", name);
735 } else {
736 fprintf(stderr, "error: category \"%s\" is not supported "
737 "on this device.\n", name);
738 }
739 return false;
740 }
741 }
742 }
743 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
744 return false;
745}
746
747static bool setCategoriesEnableFromFile(const char* categories_file)
748{
749 if (!categories_file) {
750 return true;
751 }
752 Tokenizer* tokenizer = NULL;
753 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
754 return false;
755 }
756 bool ok = true;
757 while (!tokenizer->isEol()) {
758 String8 token = tokenizer->nextToken(" ");
759 if (token.isEmpty()) {
760 tokenizer->skipDelimiters(" ");
761 continue;
762 }
763 ok &= setCategoryEnable(token.string(), true);
764 }
765 delete tokenizer;
766 return ok;
767}
768
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700769// Set all the kernel tracing settings to the desired state for this trace
770// capture.
771static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800772{
773 bool ok = true;
774
775 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900776 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800777 ok &= setTraceOverwriteEnable(g_traceOverwrite);
778 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
Carmen Jacksondc340972017-05-04 15:01:33 -0700779 ok &= setGlobalClockEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700780 ok &= setPrintTgidEnableIfPresent(true);
781 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800782
783 // Set up the tags property.
784 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700785 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800786 if (g_categoryEnables[i]) {
787 const TracingCategory &c = k_categories[i];
788 tags |= c.tags;
789 }
790 }
791 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700792
793 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700794 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700795 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
796 coreServicesTagEnabled = g_categoryEnables[i];
797 }
798 }
799
800 std::string packageList(g_debugAppCmdLine);
801 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700802 if (!packageList.empty()) {
803 packageList += ",";
804 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700805 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700806 }
Dan Austin09a79872016-05-31 13:27:03 -0700807 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700808 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100809 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800810
811 // Disable all the sysfs enables. This is done as a separate loop from
812 // the enables to allow the same enable to exist in multiple categories.
813 ok &= disableKernelTraceEvents();
814
815 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700816 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800817 if (g_categoryEnables[i]) {
818 const TracingCategory &c = k_categories[i];
819 for (int j = 0; j < MAX_SYS_FILES; j++) {
820 const char* path = c.sysfiles[j].path;
821 bool required = c.sysfiles[j].required == REQ;
822 if (path != NULL) {
823 if (fileIsWritable(path)) {
824 ok &= setKernelOptionEnable(path, true);
825 } else if (required) {
826 fprintf(stderr, "error writing file %s\n", path);
827 ok = false;
828 }
829 }
830 }
831 }
832 }
833
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800834 return ok;
835}
836
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700837// Reset all the kernel tracing settings to their default state.
838static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800839{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800840 // Disable all tracing that we're able to.
841 disableKernelTraceEvents();
842
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700843 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800844 setTagsProperty(0);
sergeyv4144eff2016-04-28 11:40:04 -0700845 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700846 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800847
848 // Set the options back to their defaults.
849 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700850 setTraceBufferSizeKB(1);
Carmen Jacksondc340972017-05-04 15:01:33 -0700851 setGlobalClockEnable(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700852 setPrintTgidEnableIfPresent(false);
853 setKernelTraceFuncs(NULL);
854}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800855
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700856
857// Enable tracing in the kernel.
858static bool startTrace()
859{
860 return setTracingEnabled(true);
861}
862
863// Disable tracing in the kernel.
864static void stopTrace()
865{
866 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800867}
868
Martijn Coenend9535872015-11-26 10:00:55 +0100869// Read data from the tracing pipe and forward to stdout
870static void streamTrace()
871{
872 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800873 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100874 if (traceFD == -1) {
875 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
876 strerror(errno), errno);
877 return;
878 }
879 while (!g_traceAborted) {
880 ssize_t bytes_read = read(traceFD, trace_data, 4096);
881 if (bytes_read > 0) {
882 write(STDOUT_FILENO, trace_data, bytes_read);
883 fflush(stdout);
884 } else {
885 if (!g_traceAborted) {
886 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
887 bytes_read, errno, strerror(errno));
888 }
889 break;
890 }
891 }
892}
893
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800894// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700895static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800896{
John Reck6c8ac922016-03-28 11:25:30 -0700897 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800898 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800899 if (traceFD == -1) {
900 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
901 strerror(errno), errno);
902 return;
903 }
904
905 if (g_compress) {
906 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800907 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700908
909 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800910 if (result != Z_OK) {
911 fprintf(stderr, "error initializing zlib: %d\n", result);
912 close(traceFD);
913 return;
914 }
915
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700916 constexpr size_t bufSize = 64*1024;
917 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
918 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
919 if (!in || !out) {
920 fprintf(stderr, "couldn't allocate buffers\n");
921 close(traceFD);
922 return;
923 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800924
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700925 int flush = Z_NO_FLUSH;
926
927 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800928 zs.avail_out = bufSize;
929
930 do {
931
932 if (zs.avail_in == 0) {
933 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700934 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800935 if (result < 0) {
936 fprintf(stderr, "error reading trace: %s (%d)\n",
937 strerror(errno), errno);
938 result = Z_STREAM_END;
939 break;
940 } else if (result == 0) {
941 flush = Z_FINISH;
942 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700943 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800944 zs.avail_in = result;
945 }
946 }
947
948 if (zs.avail_out == 0) {
949 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700950 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800951 if ((size_t)result < bufSize) {
952 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
953 strerror(errno), errno);
954 result = Z_STREAM_END; // skip deflate error message
955 zs.avail_out = bufSize; // skip the final write
956 break;
957 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700958 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800959 zs.avail_out = bufSize;
960 }
961
962 } while ((result = deflate(&zs, flush)) == Z_OK);
963
964 if (result != Z_STREAM_END) {
965 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
966 }
967
968 if (zs.avail_out < bufSize) {
969 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -0700970 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800971 if ((size_t)result < bytes) {
972 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
973 strerror(errno), errno);
974 }
975 }
976
977 result = deflateEnd(&zs);
978 if (result != Z_OK) {
979 fprintf(stderr, "error cleaning up zlib: %d\n", result);
980 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800981 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -0700982 char buf[4096];
983 ssize_t rc;
984 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
985 if (!android::base::WriteFully(outFd, buf, rc)) {
986 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
987 break;
988 }
989 }
990 if (rc == -1) {
991 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800992 }
993 }
994
995 close(traceFD);
996}
997
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700998static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800999{
1000 if (!g_nohup) {
1001 g_traceAborted = true;
1002 }
1003}
1004
1005static void registerSigHandler()
1006{
1007 struct sigaction sa;
1008 sigemptyset(&sa.sa_mask);
1009 sa.sa_flags = 0;
1010 sa.sa_handler = handleSignal;
1011 sigaction(SIGHUP, &sa, NULL);
1012 sigaction(SIGINT, &sa, NULL);
1013 sigaction(SIGQUIT, &sa, NULL);
1014 sigaction(SIGTERM, &sa, NULL);
1015}
1016
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001017static void listSupportedCategories()
1018{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001019 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001020 const TracingCategory& c = k_categories[i];
1021 if (isCategorySupported(c)) {
1022 printf(" %10s - %s\n", c.name, c.longname);
1023 }
1024 }
1025}
1026
1027// Print the command usage help to stderr.
1028static void showHelp(const char *cmd)
1029{
1030 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1031 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001032 " -a appname enable app-level tracing for a comma "
1033 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001034 " -b N use a trace buffer size of N KB\n"
1035 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001036 " -f filename use the categories written in a file as space-separated\n"
1037 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001038 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001039 " -n ignore signals\n"
1040 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001041 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001042 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001043 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001044 " --async_dump dump the current contents of circular trace buffer\n"
1045 " --async_stop stop tracing and dump the current contents of circular\n"
1046 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001047 " --stream stream trace to stdout as it enters the trace buffer\n"
1048 " Note: this can take significant CPU time, and is best\n"
1049 " used for measuring things that are not affected by\n"
1050 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001051 " --list_categories\n"
1052 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001053 " -o filename write the trace to the specified file instead\n"
1054 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001055 );
1056}
1057
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001058bool findTraceFiles()
1059{
1060 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1061 static const std::string tracefs_path = "/sys/kernel/tracing/";
1062 static const std::string trace_file = "trace_marker";
1063
1064 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1065 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1066
1067 if (!tracefs && !debugfs) {
1068 fprintf(stderr, "Error: Did not find trace folder\n");
1069 return false;
1070 }
1071
1072 if (tracefs) {
1073 g_traceFolder = tracefs_path;
1074 } else {
1075 g_traceFolder = debugfs_path;
1076 }
1077
1078 return true;
1079}
1080
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001081int main(int argc, char **argv)
1082{
1083 bool async = false;
1084 bool traceStart = true;
1085 bool traceStop = true;
1086 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001087 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001088
1089 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1090 showHelp(argv[0]);
1091 exit(0);
1092 }
1093
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001094 if (!findTraceFiles()) {
1095 fprintf(stderr, "No trace folder found\n");
1096 exit(-1);
1097 }
1098
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001099 for (;;) {
1100 int ret;
1101 int option_index = 0;
1102 static struct option long_options[] = {
1103 {"async_start", no_argument, 0, 0 },
1104 {"async_stop", no_argument, 0, 0 },
1105 {"async_dump", no_argument, 0, 0 },
1106 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +01001107 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001108 { 0, 0, 0, 0 }
1109 };
1110
John Reck40b26b42016-03-30 09:44:36 -07001111 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001112 long_options, &option_index);
1113
1114 if (ret < 0) {
1115 for (int i = optind; i < argc; i++) {
1116 if (!setCategoryEnable(argv[i], true)) {
1117 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1118 exit(1);
1119 }
1120 }
1121 break;
1122 }
1123
1124 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001125 case 'a':
1126 g_debugAppCmdLine = optarg;
1127 break;
1128
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001129 case 'b':
1130 g_traceBufferSizeKB = atoi(optarg);
1131 break;
1132
1133 case 'c':
1134 g_traceOverwrite = true;
1135 break;
1136
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001137 case 'f':
1138 g_categoriesFile = optarg;
1139 break;
1140
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001141 case 'k':
1142 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001143 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001144
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001145 case 'n':
1146 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001147 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001148
1149 case 's':
1150 g_initialSleepSecs = atoi(optarg);
1151 break;
1152
1153 case 't':
1154 g_traceDurationSeconds = atoi(optarg);
1155 break;
1156
1157 case 'z':
1158 g_compress = true;
1159 break;
1160
John Reck40b26b42016-03-30 09:44:36 -07001161 case 'o':
1162 g_outputFile = optarg;
1163 break;
1164
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001165 case 0:
1166 if (!strcmp(long_options[option_index].name, "async_start")) {
1167 async = true;
1168 traceStop = false;
1169 traceDump = false;
1170 g_traceOverwrite = true;
1171 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1172 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001173 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001174 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1175 async = true;
1176 traceStart = false;
1177 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001178 } else if (!strcmp(long_options[option_index].name, "stream")) {
1179 traceStream = true;
1180 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001181 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1182 listSupportedCategories();
1183 exit(0);
1184 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001185 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001186
1187 default:
1188 fprintf(stderr, "\n");
1189 showHelp(argv[0]);
1190 exit(-1);
1191 break;
1192 }
1193 }
1194
1195 registerSigHandler();
1196
1197 if (g_initialSleepSecs > 0) {
1198 sleep(g_initialSleepSecs);
1199 }
1200
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001201 bool ok = true;
1202 ok &= setUpTrace();
1203 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001204
1205 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001206 if (!traceStream) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001207 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001208 fflush(stdout);
1209 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001210
1211 // We clear the trace after starting it because tracing gets enabled for
1212 // each CPU individually in the kernel. Having the beginning of the trace
1213 // contain entries from only one CPU can cause "begin" entries without a
1214 // matching "end" entry to show up if a task gets migrated from one CPU to
1215 // another.
1216 ok = clearTrace();
1217
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001218 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001219 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001220 // Sleep to allow the trace to be captured.
1221 struct timespec timeLeft;
1222 timeLeft.tv_sec = g_traceDurationSeconds;
1223 timeLeft.tv_nsec = 0;
1224 do {
1225 if (g_traceAborted) {
1226 break;
1227 }
1228 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1229 }
Martijn Coenend9535872015-11-26 10:00:55 +01001230
1231 if (traceStream) {
1232 streamTrace();
1233 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001234 }
1235
1236 // Stop the trace and restore the default settings.
1237 if (traceStop)
1238 stopTrace();
1239
1240 if (ok && traceDump) {
1241 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001242 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001243 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001244 int outFd = STDOUT_FILENO;
1245 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001246 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001247 }
1248 if (outFd == -1) {
1249 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1250 } else {
1251 dprintf(outFd, "TRACE:\n");
1252 dumpTrace(outFd);
1253 if (g_outputFile) {
1254 close(outFd);
1255 }
1256 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001257 } else {
1258 printf("\ntrace aborted.\n");
1259 fflush(stdout);
1260 }
1261 clearTrace();
1262 } else if (!ok) {
1263 fprintf(stderr, "unable to start tracing\n");
1264 }
1265
1266 // Reset the trace buffer size to 1.
1267 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001268 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001269
1270 return g_traceAborted ? 1 : 0;
1271}