blob: 1a803f39bcc29237a04864fd5d5667403b8a2a90 [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
Carmen Jacksonea826792017-05-05 11:42:32 -070034#include <fstream>
Elliott Hughesa252f4d2016-07-21 17:12:15 -070035#include <memory>
36
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080037#include <binder/IBinder.h>
38#include <binder/IServiceManager.h>
39#include <binder/Parcel.h>
40
Martijn Coenenee9b97e2016-11-16 16:00:26 +010041#include <android/hidl/manager/1.0/IServiceManager.h>
42#include <hidl/ServiceManagement.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080043#include <cutils/properties.h>
44
45#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;
52
Martijn Coenenee9b97e2016-11-16 16:00:26 +010053using std::string;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080054#define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0])))
55
sergeyv4144eff2016-04-28 11:40:04 -070056#define MAX_SYS_FILES 10
57#define MAX_PACKAGES 16
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080058
59const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
sergeyv4144eff2016-04-28 11:40:04 -070060
61const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
62const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070063const char* k_coreServiceCategory = "core_services";
64const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080065
66typedef enum { OPT, REQ } requiredness ;
67
68struct TracingCategory {
69 // The name identifying the category.
70 const char* name;
71
72 // A longer description of the category.
73 const char* longname;
74
75 // The userland tracing tags that the category enables.
76 uint64_t tags;
77
78 // The fname==NULL terminated list of /sys/ files that the category
79 // enables.
80 struct {
81 // Whether the file must be writable in order to enable the tracing
82 // category.
83 requiredness required;
84
85 // The path to the enable file.
86 const char* path;
87 } sysfiles[MAX_SYS_FILES];
88};
89
90/* Tracing categories */
91static const TracingCategory k_categories[] = {
Jamie Gennisb2a89e32013-03-11 19:37:53 -070092 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, { } },
93 { "input", "Input", ATRACE_TAG_INPUT, { } },
94 { "view", "View System", ATRACE_TAG_VIEW, { } },
95 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
96 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
97 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -050098 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070099 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
100 { "video", "Video", ATRACE_TAG_VIDEO, { } },
101 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
102 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700103 { "app", "Application", ATRACE_TAG_APP, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -0700104 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -0700105 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -0700106 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -0700107 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700108 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 14:36:20 -0700109 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-07-01 01:46:25 +0900110 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Greg Hackmannbbd7d992014-12-01 14:43:34 -0800111 { "database", "Database", ATRACE_TAG_DATABASE, { } },
Felipe Leme0f97c1d2016-09-07 11:33:26 -0700112 { "network", "Network", ATRACE_TAG_NETWORK, { } },
Josh Gao468b4cb2016-11-29 10:55:21 -0800113 { "adb", "ADB", ATRACE_TAG_ADB, { } },
sergeyvdb404152016-05-02 19:26:07 -0700114 { k_coreServiceCategory, "Core services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700115 { "sched", "CPU Scheduling", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800116 { REQ, "events/sched/sched_switch/enable" },
117 { REQ, "events/sched/sched_wakeup/enable" },
118 { OPT, "events/sched/sched_blocked_reason/enable" },
119 { OPT, "events/sched/sched_cpu_hotplug/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800120 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700121 { "irq", "IRQ Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800122 { REQ, "events/irq/enable" },
123 { OPT, "events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700124 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100125 { "i2c", "I2C Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800126 { REQ, "events/i2c/enable" },
127 { REQ, "events/i2c/i2c_read/enable" },
128 { REQ, "events/i2c/i2c_write/enable" },
129 { REQ, "events/i2c/i2c_result/enable" },
130 { REQ, "events/i2c/i2c_reply/enable" },
131 { OPT, "events/i2c/smbus_read/enable" },
132 { OPT, "events/i2c/smbus_write/enable" },
133 { OPT, "events/i2c/smbus_result/enable" },
134 { OPT, "events/i2c/smbus_reply/enable" },
Michael Wright43fb6782016-08-18 19:56:43 +0100135 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700136 { "freq", "CPU Frequency", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800137 { REQ, "events/power/cpu_frequency/enable" },
138 { OPT, "events/power/clock_set_rate/enable" },
139 { OPT, "events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800140 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700141 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800142 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800143 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700144 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800145 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800146 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700147 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800148 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
149 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
150 { OPT, "events/f2fs/f2fs_write_begin/enable" },
151 { OPT, "events/f2fs/f2fs_write_end/enable" },
152 { OPT, "events/ext4/ext4_da_write_begin/enable" },
153 { OPT, "events/ext4/ext4_da_write_end/enable" },
154 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
155 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
156 { REQ, "events/block/block_rq_issue/enable" },
157 { REQ, "events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800158 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700159 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800160 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700161 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700162 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800163 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800164 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700165 { "sync", "Synchronization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800166 { REQ, "events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800167 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700168 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800169 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800170 } },
Colin Cross580407f2014-08-18 15:22:13 -0700171 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800172 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
173 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
174 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
175 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700176 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800177 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800178 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800179 } },
Scott Bauerae473362015-06-08 16:32:36 -0700180 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800181 { REQ, "events/binder/binder_transaction/enable" },
182 { REQ, "events/binder/binder_transaction_received/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700183 } },
184 { "binder_lock", "Binder global lock trace", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800185 { REQ, "events/binder/binder_lock/enable" },
186 { REQ, "events/binder/binder_locked/enable" },
187 { REQ, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700188 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200189 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800190 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200191 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800192};
193
194/* Command line options */
195static int g_traceDurationSeconds = 5;
196static bool g_traceOverwrite = false;
197static int g_traceBufferSizeKB = 2048;
198static bool g_compress = false;
199static bool g_nohup = false;
200static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900201static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700202static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700203static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700204static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800205
206/* Global state */
207static bool g_traceAborted = false;
208static bool g_categoryEnables[NELEM(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800209static std::string g_traceFolder;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800210
211/* Sys file paths */
212static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800213 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800214
215static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800216 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800217
Joel Fernandesefb73a92017-06-02 10:19:28 -0700218static const char* k_traceCmdlineSizePath =
219 "saved_cmdlines_size";
220
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800221static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800222 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800223
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700224static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800225 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700226
227static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800228 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700229
230static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800231 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700232
233static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800234 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700235
236static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800237 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700238
239static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800240 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700241
242static const char* k_funcgraphDurationPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800243 "options/funcgraph-duration";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700244
245static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800246 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700247
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800248static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800249 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800250
251static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800252 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800253
Martijn Coenend9535872015-11-26 10:00:55 +0100254static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800255 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100256
John Reck469a1942015-03-26 15:31:35 -0700257static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800258 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700259
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800260// Check whether a file exists.
261static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800262 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800263}
264
265// Check whether a file is writable.
266static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800267 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800268}
269
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700270// Truncate a file.
271static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800272{
Jamie Gennis43122e72013-03-21 14:06:31 -0700273 // This uses creat rather than truncate because some of the debug kernel
274 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
275 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800276 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700277 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800278 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700279 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700280 return false;
281 }
282
Jamie Gennis43122e72013-03-21 14:06:31 -0700283 close(traceFD);
284
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700285 return true;
286}
287
288static bool _writeStr(const char* filename, const char* str, int flags)
289{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800290 std::string fullFilename = g_traceFolder + filename;
291 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800292 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800293 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800294 strerror(errno), errno);
295 return false;
296 }
297
298 bool ok = true;
299 ssize_t len = strlen(str);
300 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800301 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800302 strerror(errno), errno);
303 ok = false;
304 }
305
306 close(fd);
307
308 return ok;
309}
310
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700311// Write a string to a file, returning true if the write was successful.
312static bool writeStr(const char* filename, const char* str)
313{
314 return _writeStr(filename, str, O_WRONLY);
315}
316
317// Append a string to a file, returning true if the write was successful.
318static bool appendStr(const char* filename, const char* str)
319{
320 return _writeStr(filename, str, O_APPEND|O_WRONLY);
321}
322
John Reck469a1942015-03-26 15:31:35 -0700323static void writeClockSyncMarker()
324{
325 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200326 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800327 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200328 if (fd == -1) {
329 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
330 strerror(errno), errno);
331 return;
332 }
John Reck469a1942015-03-26 15:31:35 -0700333 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200334
335 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
336 if (write(fd, buffer, len) != len) {
337 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
338 }
339
340 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
341 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
342 if (write(fd, buffer, len) != len) {
343 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
344 }
345
346 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700347}
348
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800349// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
350// file.
351static bool setKernelOptionEnable(const char* filename, bool enable)
352{
353 return writeStr(filename, enable ? "1" : "0");
354}
355
356// Check whether the category is supported on the device with the current
357// rootness. A category is supported only if all its required /sys/ files are
358// writable and if enabling the category will enable one or more tracing tags
359// or /sys/ files.
360static bool isCategorySupported(const TracingCategory& category)
361{
sergeyvdb404152016-05-02 19:26:07 -0700362 if (strcmp(category.name, k_coreServiceCategory) == 0) {
363 char value[PROPERTY_VALUE_MAX];
364 property_get(k_coreServicesProp, value, "");
365 return strlen(value) != 0;
366 }
367
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800368 bool ok = category.tags != 0;
369 for (int i = 0; i < MAX_SYS_FILES; i++) {
370 const char* path = category.sysfiles[i].path;
371 bool req = category.sysfiles[i].required == REQ;
372 if (path != NULL) {
373 if (req) {
374 if (!fileIsWritable(path)) {
375 return false;
376 } else {
377 ok = true;
378 }
379 } else {
380 ok |= fileIsWritable(path);
381 }
382 }
383 }
384 return ok;
385}
386
387// Check whether the category would be supported on the device if the user
388// were root. This function assumes that root is able to write to any file
389// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700390// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800391static bool isCategorySupportedForRoot(const TracingCategory& category)
392{
393 bool ok = category.tags != 0;
394 for (int i = 0; i < MAX_SYS_FILES; i++) {
395 const char* path = category.sysfiles[i].path;
396 bool req = category.sysfiles[i].required == REQ;
397 if (path != NULL) {
398 if (req) {
399 if (!fileExists(path)) {
400 return false;
401 } else {
402 ok = true;
403 }
404 } else {
405 ok |= fileExists(path);
406 }
407 }
408 }
409 return ok;
410}
411
412// Enable or disable overwriting of the kernel trace buffers. Disabling this
413// will cause tracing to stop once the trace buffers have filled up.
414static bool setTraceOverwriteEnable(bool enable)
415{
416 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
417}
418
419// Enable or disable kernel tracing.
420static bool setTracingEnabled(bool enable)
421{
422 return setKernelOptionEnable(k_tracingOnPath, enable);
423}
424
425// Clear the contents of the kernel trace.
426static bool clearTrace()
427{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700428 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800429}
430
431// Set the size of the kernel's trace buffer in kilobytes.
432static bool setTraceBufferSizeKB(int size)
433{
434 char str[32] = "1";
435 int len;
436 if (size < 1) {
437 size = 1;
438 }
439 snprintf(str, 32, "%d", size);
440 return writeStr(k_traceBufferSizePath, str);
441}
442
Joel Fernandesefb73a92017-06-02 10:19:28 -0700443// Set the default size of cmdline hashtable
444static bool setCmdlineSize()
445{
446 return writeStr(k_traceCmdlineSizePath, "8192");
447}
448
Carmen Jacksonea826792017-05-05 11:42:32 -0700449// Set the clock to the best available option while tracing. Use 'boot' if it's
450// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700451// Any write to the trace_clock sysfs file will reset the buffer, so only
452// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700453static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800454{
Carmen Jacksonea826792017-05-05 11:42:32 -0700455 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
456 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
457 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700458
Carmen Jacksonea826792017-05-05 11:42:32 -0700459 std::string newClock;
460 if (clockStr.find("boot") != std::string::npos) {
461 newClock = "boot";
462 } else if (clockStr.find("mono") != std::string::npos) {
463 newClock = "mono";
464 } else {
465 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700466 }
467
Carmen Jacksonea826792017-05-05 11:42:32 -0700468 size_t begin = clockStr.find("[") + 1;
469 size_t end = clockStr.find("]");
470 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
471 return true;
472 }
473 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800474}
475
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700476static bool setPrintTgidEnableIfPresent(bool enable)
477{
478 if (fileExists(k_printTgidPath)) {
479 return setKernelOptionEnable(k_printTgidPath, enable);
480 }
481 return true;
482}
483
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800484// Poke all the binder-enabled processes in the system to get them to re-read
485// their system properties.
486static bool pokeBinderServices()
487{
488 sp<IServiceManager> sm = defaultServiceManager();
489 Vector<String16> services = sm->listServices();
490 for (size_t i = 0; i < services.size(); i++) {
491 sp<IBinder> obj = sm->checkService(services[i]);
492 if (obj != NULL) {
493 Parcel data;
494 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
495 NULL, 0) != OK) {
496 if (false) {
497 // XXX: For some reason this fails on tablets trying to
498 // poke the "phone" service. It's not clear whether some
499 // are expected to fail.
500 String8 svc(services[i]);
501 fprintf(stderr, "error poking binder service %s\n",
502 svc.string());
503 return false;
504 }
505 }
506 }
507 }
508 return true;
509}
510
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100511// Poke all the HAL processes in the system to get them to re-read
512// their system properties.
513static void pokeHalServices()
514{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100515 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100516 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100517 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100518 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100519
520 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800521
522 if (sm == nullptr) {
523 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
524 return;
525 }
526
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800527 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100528 for (size_t i = 0; i < interfaces.size(); i++) {
529 string fqInstanceName = interfaces[i];
530 string::size_type n = fqInstanceName.find("/");
531 if (n == std::string::npos || interfaces[i].size() == n+1)
532 continue;
533 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
534 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100535 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
536 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100537 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100538 continue;
539 }
Carmen Jackson73206122017-04-18 15:37:57 -0700540
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100541 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700542 if (interface == nullptr) {
543 // ignore
544 continue;
545 }
546
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100547 auto notifyRet = interface->notifySyspropsChanged();
548 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100549 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800550 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100551 }
552 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800553 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100554 // TODO(b/34242478) fix this when we determine the correct ACL
555 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800556 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100557}
558
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800559// Set the trace tags that userland tracing uses, and poke the running
560// processes to pick up the new value.
561static bool setTagsProperty(uint64_t tags)
562{
sergeyv4144eff2016-04-28 11:40:04 -0700563 char buf[PROPERTY_VALUE_MAX];
564 snprintf(buf, sizeof(buf), "%#" PRIx64, tags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800565 if (property_set(k_traceTagsProperty, buf) < 0) {
566 fprintf(stderr, "error setting trace tags system property\n");
567 return false;
568 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700569 return true;
570}
571
sergeyv4144eff2016-04-28 11:40:04 -0700572static void clearAppProperties()
573{
574 char buf[PROPERTY_KEY_MAX];
575 for (int i = 0; i < MAX_PACKAGES; i++) {
576 snprintf(buf, sizeof(buf), k_traceAppsPropertyTemplate, i);
577 if (property_set(buf, "") < 0) {
578 fprintf(stderr, "failed to clear system property: %s\n", buf);
579 }
580 }
581 if (property_set(k_traceAppsNumberProperty, "") < 0) {
582 fprintf(stderr, "failed to clear system property: %s",
583 k_traceAppsNumberProperty);
584 }
585}
586
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700587// Set the system property that indicates which apps should perform
588// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700589static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700590{
sergeyv4144eff2016-04-28 11:40:04 -0700591 char buf[PROPERTY_KEY_MAX];
592 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700593 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700594 while (start != NULL) {
595 if (i == MAX_PACKAGES) {
596 fprintf(stderr, "error: only 16 packages could be traced at once\n");
597 clearAppProperties();
598 return false;
599 }
600 char* end = strchr(start, ',');
601 if (end != NULL) {
602 *end = '\0';
603 end++;
604 }
605 snprintf(buf, sizeof(buf), k_traceAppsPropertyTemplate, i);
606 if (property_set(buf, start) < 0) {
607 fprintf(stderr, "error setting trace app %d property to %s\n", i, buf);
608 clearAppProperties();
609 return false;
610 }
611 start = end;
612 i++;
613 }
614
615 snprintf(buf, sizeof(buf), "%d", i);
616 if (property_set(k_traceAppsNumberProperty, buf) < 0) {
617 fprintf(stderr, "error setting trace app number property to %s\n", buf);
618 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700619 return false;
620 }
621 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800622}
623
624// Disable all /sys/ enable files.
625static bool disableKernelTraceEvents() {
626 bool ok = true;
627 for (int i = 0; i < NELEM(k_categories); i++) {
628 const TracingCategory &c = k_categories[i];
629 for (int j = 0; j < MAX_SYS_FILES; j++) {
630 const char* path = c.sysfiles[j].path;
631 if (path != NULL && fileIsWritable(path)) {
632 ok &= setKernelOptionEnable(path, false);
633 }
634 }
635 }
636 return ok;
637}
638
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700639// Verify that the comma separated list of functions are being traced by the
640// kernel.
641static bool verifyKernelTraceFuncs(const char* funcs)
642{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100643 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800644 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100645 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700646 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100647 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700648 }
649
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100650 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700651
652 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100653 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700654 bool ok = true;
655 char* myFuncs = strdup(funcs);
656 char* func = strtok(myFuncs, ",");
657 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100658 if (!strchr(func, '*')) {
659 String8 fancyFunc = String8::format("\n%s\n", func);
660 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
661 if (!found || func[0] == '\0') {
662 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
663 "to trace.\n", func);
664 ok = false;
665 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700666 }
667 func = strtok(NULL, ",");
668 }
669 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700670 return ok;
671}
672
673// Set the comma separated list of functions that the kernel is to trace.
674static bool setKernelTraceFuncs(const char* funcs)
675{
676 bool ok = true;
677
678 if (funcs == NULL || funcs[0] == '\0') {
679 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700680 if (fileIsWritable(k_currentTracerPath)) {
681 ok &= writeStr(k_currentTracerPath, "nop");
682 }
683 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700684 ok &= truncateFile(k_ftraceFilterPath);
685 }
686 } else {
687 // Enable kernel function tracing.
688 ok &= writeStr(k_currentTracerPath, "function_graph");
689 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
690 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
691 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
692 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
693
694 // Set the requested filter functions.
695 ok &= truncateFile(k_ftraceFilterPath);
696 char* myFuncs = strdup(funcs);
697 char* func = strtok(myFuncs, ",");
698 while (func) {
699 ok &= appendStr(k_ftraceFilterPath, func);
700 func = strtok(NULL, ",");
701 }
702 free(myFuncs);
703
704 // Verify that the set functions are being traced.
705 if (ok) {
706 ok &= verifyKernelTraceFuncs(funcs);
707 }
708 }
709
710 return ok;
711}
712
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900713static bool setCategoryEnable(const char* name, bool enable)
714{
715 for (int i = 0; i < NELEM(k_categories); i++) {
716 const TracingCategory& c = k_categories[i];
717 if (strcmp(name, c.name) == 0) {
718 if (isCategorySupported(c)) {
719 g_categoryEnables[i] = enable;
720 return true;
721 } else {
722 if (isCategorySupportedForRoot(c)) {
723 fprintf(stderr, "error: category \"%s\" requires root "
724 "privileges.\n", name);
725 } else {
726 fprintf(stderr, "error: category \"%s\" is not supported "
727 "on this device.\n", name);
728 }
729 return false;
730 }
731 }
732 }
733 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
734 return false;
735}
736
737static bool setCategoriesEnableFromFile(const char* categories_file)
738{
739 if (!categories_file) {
740 return true;
741 }
742 Tokenizer* tokenizer = NULL;
743 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
744 return false;
745 }
746 bool ok = true;
747 while (!tokenizer->isEol()) {
748 String8 token = tokenizer->nextToken(" ");
749 if (token.isEmpty()) {
750 tokenizer->skipDelimiters(" ");
751 continue;
752 }
753 ok &= setCategoryEnable(token.string(), true);
754 }
755 delete tokenizer;
756 return ok;
757}
758
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700759// Set all the kernel tracing settings to the desired state for this trace
760// capture.
761static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800762{
763 bool ok = true;
764
765 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900766 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800767 ok &= setTraceOverwriteEnable(g_traceOverwrite);
768 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
Joel Fernandesefb73a92017-06-02 10:19:28 -0700769 ok &= setCmdlineSize();
Carmen Jacksonea826792017-05-05 11:42:32 -0700770 ok &= setClock();
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700771 ok &= setPrintTgidEnableIfPresent(true);
772 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800773
774 // Set up the tags property.
775 uint64_t tags = 0;
776 for (int i = 0; i < NELEM(k_categories); i++) {
777 if (g_categoryEnables[i]) {
778 const TracingCategory &c = k_categories[i];
779 tags |= c.tags;
780 }
781 }
782 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700783
784 bool coreServicesTagEnabled = false;
785 for (int i = 0; i < NELEM(k_categories); i++) {
786 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
787 coreServicesTagEnabled = g_categoryEnables[i];
788 }
789 }
790
791 std::string packageList(g_debugAppCmdLine);
792 if (coreServicesTagEnabled) {
793 char value[PROPERTY_VALUE_MAX];
794 property_get(k_coreServicesProp, value, "");
795 if (!packageList.empty()) {
796 packageList += ",";
797 }
798 packageList += value;
799 }
Dan Austin09a79872016-05-31 13:27:03 -0700800 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700801 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100802 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800803
804 // Disable all the sysfs enables. This is done as a separate loop from
805 // the enables to allow the same enable to exist in multiple categories.
806 ok &= disableKernelTraceEvents();
807
808 // Enable all the sysfs enables that are in an enabled category.
809 for (int i = 0; i < NELEM(k_categories); i++) {
810 if (g_categoryEnables[i]) {
811 const TracingCategory &c = k_categories[i];
812 for (int j = 0; j < MAX_SYS_FILES; j++) {
813 const char* path = c.sysfiles[j].path;
814 bool required = c.sysfiles[j].required == REQ;
815 if (path != NULL) {
816 if (fileIsWritable(path)) {
817 ok &= setKernelOptionEnable(path, true);
818 } else if (required) {
819 fprintf(stderr, "error writing file %s\n", path);
820 ok = false;
821 }
822 }
823 }
824 }
825 }
826
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800827 return ok;
828}
829
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700830// Reset all the kernel tracing settings to their default state.
831static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800832{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800833 // Disable all tracing that we're able to.
834 disableKernelTraceEvents();
835
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700836 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800837 setTagsProperty(0);
sergeyv4144eff2016-04-28 11:40:04 -0700838 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700839 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800840
841 // Set the options back to their defaults.
842 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700843 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700844 setPrintTgidEnableIfPresent(false);
845 setKernelTraceFuncs(NULL);
846}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800847
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700848
849// Enable tracing in the kernel.
850static bool startTrace()
851{
852 return setTracingEnabled(true);
853}
854
855// Disable tracing in the kernel.
856static void stopTrace()
857{
858 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800859}
860
Martijn Coenend9535872015-11-26 10:00:55 +0100861// Read data from the tracing pipe and forward to stdout
862static void streamTrace()
863{
864 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800865 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100866 if (traceFD == -1) {
867 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
868 strerror(errno), errno);
869 return;
870 }
871 while (!g_traceAborted) {
872 ssize_t bytes_read = read(traceFD, trace_data, 4096);
873 if (bytes_read > 0) {
874 write(STDOUT_FILENO, trace_data, bytes_read);
875 fflush(stdout);
876 } else {
877 if (!g_traceAborted) {
878 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
879 bytes_read, errno, strerror(errno));
880 }
881 break;
882 }
883 }
884}
885
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800886// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700887static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800888{
John Reck6c8ac922016-03-28 11:25:30 -0700889 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800890 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800891 if (traceFD == -1) {
892 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
893 strerror(errno), errno);
894 return;
895 }
896
897 if (g_compress) {
898 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800899 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700900
901 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800902 if (result != Z_OK) {
903 fprintf(stderr, "error initializing zlib: %d\n", result);
904 close(traceFD);
905 return;
906 }
907
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700908 constexpr size_t bufSize = 64*1024;
909 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
910 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
911 if (!in || !out) {
912 fprintf(stderr, "couldn't allocate buffers\n");
913 close(traceFD);
914 return;
915 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800916
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700917 int flush = Z_NO_FLUSH;
918
919 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800920 zs.avail_out = bufSize;
921
922 do {
923
924 if (zs.avail_in == 0) {
925 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700926 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800927 if (result < 0) {
928 fprintf(stderr, "error reading trace: %s (%d)\n",
929 strerror(errno), errno);
930 result = Z_STREAM_END;
931 break;
932 } else if (result == 0) {
933 flush = Z_FINISH;
934 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700935 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800936 zs.avail_in = result;
937 }
938 }
939
940 if (zs.avail_out == 0) {
941 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700942 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800943 if ((size_t)result < bufSize) {
944 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
945 strerror(errno), errno);
946 result = Z_STREAM_END; // skip deflate error message
947 zs.avail_out = bufSize; // skip the final write
948 break;
949 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700950 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800951 zs.avail_out = bufSize;
952 }
953
954 } while ((result = deflate(&zs, flush)) == Z_OK);
955
956 if (result != Z_STREAM_END) {
957 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
958 }
959
960 if (zs.avail_out < bufSize) {
961 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -0700962 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800963 if ((size_t)result < bytes) {
964 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
965 strerror(errno), errno);
966 }
967 }
968
969 result = deflateEnd(&zs);
970 if (result != Z_OK) {
971 fprintf(stderr, "error cleaning up zlib: %d\n", result);
972 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800973 } else {
974 ssize_t sent = 0;
John Reck40b26b42016-03-30 09:44:36 -0700975 while ((sent = sendfile(outFd, traceFD, NULL, 64*1024*1024)) > 0);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800976 if (sent == -1) {
977 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
978 errno);
979 }
980 }
981
982 close(traceFD);
983}
984
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700985static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800986{
987 if (!g_nohup) {
988 g_traceAborted = true;
989 }
990}
991
992static void registerSigHandler()
993{
994 struct sigaction sa;
995 sigemptyset(&sa.sa_mask);
996 sa.sa_flags = 0;
997 sa.sa_handler = handleSignal;
998 sigaction(SIGHUP, &sa, NULL);
999 sigaction(SIGINT, &sa, NULL);
1000 sigaction(SIGQUIT, &sa, NULL);
1001 sigaction(SIGTERM, &sa, NULL);
1002}
1003
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001004static void listSupportedCategories()
1005{
1006 for (int i = 0; i < NELEM(k_categories); i++) {
1007 const TracingCategory& c = k_categories[i];
1008 if (isCategorySupported(c)) {
1009 printf(" %10s - %s\n", c.name, c.longname);
1010 }
1011 }
1012}
1013
1014// Print the command usage help to stderr.
1015static void showHelp(const char *cmd)
1016{
1017 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1018 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001019 " -a appname enable app-level tracing for a comma "
1020 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001021 " -b N use a trace buffer size of N KB\n"
1022 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001023 " -f filename use the categories written in a file as space-separated\n"
1024 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001025 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001026 " -n ignore signals\n"
1027 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001028 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001029 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001030 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001031 " --async_dump dump the current contents of circular trace buffer\n"
1032 " --async_stop stop tracing and dump the current contents of circular\n"
1033 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001034 " --stream stream trace to stdout as it enters the trace buffer\n"
1035 " Note: this can take significant CPU time, and is best\n"
1036 " used for measuring things that are not affected by\n"
1037 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001038 " --list_categories\n"
1039 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001040 " -o filename write the trace to the specified file instead\n"
1041 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001042 );
1043}
1044
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001045bool findTraceFiles()
1046{
1047 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1048 static const std::string tracefs_path = "/sys/kernel/tracing/";
1049 static const std::string trace_file = "trace_marker";
1050
1051 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1052 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1053
1054 if (!tracefs && !debugfs) {
1055 fprintf(stderr, "Error: Did not find trace folder\n");
1056 return false;
1057 }
1058
1059 if (tracefs) {
1060 g_traceFolder = tracefs_path;
1061 } else {
1062 g_traceFolder = debugfs_path;
1063 }
1064
1065 return true;
1066}
1067
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001068int main(int argc, char **argv)
1069{
1070 bool async = false;
1071 bool traceStart = true;
1072 bool traceStop = true;
1073 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001074 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001075
1076 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1077 showHelp(argv[0]);
1078 exit(0);
1079 }
1080
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001081 if (!findTraceFiles()) {
1082 fprintf(stderr, "No trace folder found\n");
1083 exit(-1);
1084 }
1085
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001086 for (;;) {
1087 int ret;
1088 int option_index = 0;
1089 static struct option long_options[] = {
1090 {"async_start", no_argument, 0, 0 },
1091 {"async_stop", no_argument, 0, 0 },
1092 {"async_dump", no_argument, 0, 0 },
1093 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +01001094 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001095 { 0, 0, 0, 0 }
1096 };
1097
John Reck40b26b42016-03-30 09:44:36 -07001098 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001099 long_options, &option_index);
1100
1101 if (ret < 0) {
1102 for (int i = optind; i < argc; i++) {
1103 if (!setCategoryEnable(argv[i], true)) {
1104 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1105 exit(1);
1106 }
1107 }
1108 break;
1109 }
1110
1111 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001112 case 'a':
1113 g_debugAppCmdLine = optarg;
1114 break;
1115
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001116 case 'b':
1117 g_traceBufferSizeKB = atoi(optarg);
1118 break;
1119
1120 case 'c':
1121 g_traceOverwrite = true;
1122 break;
1123
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001124 case 'f':
1125 g_categoriesFile = optarg;
1126 break;
1127
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001128 case 'k':
1129 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001130 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001131
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001132 case 'n':
1133 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001134 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001135
1136 case 's':
1137 g_initialSleepSecs = atoi(optarg);
1138 break;
1139
1140 case 't':
1141 g_traceDurationSeconds = atoi(optarg);
1142 break;
1143
1144 case 'z':
1145 g_compress = true;
1146 break;
1147
John Reck40b26b42016-03-30 09:44:36 -07001148 case 'o':
1149 g_outputFile = optarg;
1150 break;
1151
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001152 case 0:
1153 if (!strcmp(long_options[option_index].name, "async_start")) {
1154 async = true;
1155 traceStop = false;
1156 traceDump = false;
1157 g_traceOverwrite = true;
1158 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1159 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001160 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001161 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1162 async = true;
1163 traceStart = false;
1164 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001165 } else if (!strcmp(long_options[option_index].name, "stream")) {
1166 traceStream = true;
1167 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001168 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1169 listSupportedCategories();
1170 exit(0);
1171 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001172 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001173
1174 default:
1175 fprintf(stderr, "\n");
1176 showHelp(argv[0]);
1177 exit(-1);
1178 break;
1179 }
1180 }
1181
1182 registerSigHandler();
1183
1184 if (g_initialSleepSecs > 0) {
1185 sleep(g_initialSleepSecs);
1186 }
1187
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001188 bool ok = true;
1189 ok &= setUpTrace();
1190 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001191
1192 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001193 if (!traceStream) {
1194 printf("capturing trace...");
1195 fflush(stdout);
1196 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001197
1198 // We clear the trace after starting it because tracing gets enabled for
1199 // each CPU individually in the kernel. Having the beginning of the trace
1200 // contain entries from only one CPU can cause "begin" entries without a
1201 // matching "end" entry to show up if a task gets migrated from one CPU to
1202 // another.
1203 ok = clearTrace();
1204
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001205 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001206 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001207 // Sleep to allow the trace to be captured.
1208 struct timespec timeLeft;
1209 timeLeft.tv_sec = g_traceDurationSeconds;
1210 timeLeft.tv_nsec = 0;
1211 do {
1212 if (g_traceAborted) {
1213 break;
1214 }
1215 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1216 }
Martijn Coenend9535872015-11-26 10:00:55 +01001217
1218 if (traceStream) {
1219 streamTrace();
1220 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001221 }
1222
1223 // Stop the trace and restore the default settings.
1224 if (traceStop)
1225 stopTrace();
1226
1227 if (ok && traceDump) {
1228 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001229 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001230 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001231 int outFd = STDOUT_FILENO;
1232 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001233 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001234 }
1235 if (outFd == -1) {
1236 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1237 } else {
1238 dprintf(outFd, "TRACE:\n");
1239 dumpTrace(outFd);
1240 if (g_outputFile) {
1241 close(outFd);
1242 }
1243 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001244 } else {
1245 printf("\ntrace aborted.\n");
1246 fflush(stdout);
1247 }
1248 clearTrace();
1249 } else if (!ok) {
1250 fprintf(stderr, "unable to start tracing\n");
1251 }
1252
1253 // Reset the trace buffer size to 1.
1254 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001255 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001256
1257 return g_traceAborted ? 1 : 0;
1258}