blob: be2f1bcd7c399f501957dc4aa18d6e85e31b0809 [file] [log] [blame]
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Paul Lawrence2cd93cc2017-01-17 09:50:18 -080017#define LOG_TAG "atrace"
John Reck40b26b42016-03-30 09:44:36 -070018
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080019#include <errno.h>
20#include <fcntl.h>
21#include <getopt.h>
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070022#include <inttypes.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080023#include <signal.h>
24#include <stdarg.h>
25#include <stdbool.h>
26#include <stdio.h>
27#include <stdlib.h>
Elliott Hughes3da5d232015-01-25 08:35:20 -080028#include <string.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080029#include <time.h>
Martijn Coenend9535872015-11-26 10:00:55 +010030#include <unistd.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080031#include <zlib.h>
32
Carmen Jacksonea826792017-05-05 11:42:32 -070033#include <fstream>
Elliott Hughesa252f4d2016-07-21 17:12:15 -070034#include <memory>
35
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080036#include <binder/IBinder.h>
37#include <binder/IServiceManager.h>
38#include <binder/Parcel.h>
39
Martijn Coenenee9b97e2016-11-16 16:00:26 +010040#include <android/hidl/manager/1.0/IServiceManager.h>
41#include <hidl/ServiceManagement.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080042
43#include <utils/String8.h>
John Reck469a1942015-03-26 15:31:35 -070044#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +090045#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080046#include <utils/Trace.h>
Stephane Gasparinid8419c22016-03-02 13:45:15 +010047#include <android-base/file.h>
Elliott Hughes5fd6ff62017-03-28 14:55:31 -070048#include <android-base/macros.h>
49#include <android-base/properties.h>
50#include <android-base/stringprintf.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080051
52using namespace android;
53
Martijn Coenenee9b97e2016-11-16 16:00:26 +010054using std::string;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080055
sergeyv4144eff2016-04-28 11:40:04 -070056#define MAX_SYS_FILES 10
57#define MAX_PACKAGES 16
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080058
59const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
sergeyv4144eff2016-04-28 11:40:04 -070060
61const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
62const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070063const char* k_coreServiceCategory = "core_services";
64const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080065
66typedef enum { OPT, REQ } requiredness ;
67
68struct TracingCategory {
69 // The name identifying the category.
70 const char* name;
71
72 // A longer description of the category.
73 const char* longname;
74
75 // The userland tracing tags that the category enables.
76 uint64_t tags;
77
78 // The fname==NULL terminated list of /sys/ files that the category
79 // enables.
80 struct {
81 // Whether the file must be writable in order to enable the tracing
82 // category.
83 requiredness required;
84
85 // The path to the enable file.
86 const char* path;
87 } sysfiles[MAX_SYS_FILES];
88};
89
90/* Tracing categories */
91static const TracingCategory k_categories[] = {
Jamie Gennisb2a89e32013-03-11 19:37:53 -070092 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, { } },
93 { "input", "Input", ATRACE_TAG_INPUT, { } },
94 { "view", "View System", ATRACE_TAG_VIEW, { } },
95 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
96 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
97 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -050098 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070099 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
100 { "video", "Video", ATRACE_TAG_VIDEO, { } },
101 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
102 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700103 { "app", "Application", ATRACE_TAG_APP, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -0700104 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -0700105 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -0700106 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -0700107 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700108 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 14:36:20 -0700109 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-07-01 01:46:25 +0900110 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Greg Hackmannbbd7d992014-12-01 14:43:34 -0800111 { "database", "Database", ATRACE_TAG_DATABASE, { } },
Felipe Leme0f97c1d2016-09-07 11:33:26 -0700112 { "network", "Network", ATRACE_TAG_NETWORK, { } },
Josh Gao468b4cb2016-11-29 10:55:21 -0800113 { "adb", "ADB", ATRACE_TAG_ADB, { } },
sergeyvdb404152016-05-02 19:26:07 -0700114 { k_coreServiceCategory, "Core services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700115 { "sched", "CPU Scheduling", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800116 { REQ, "events/sched/sched_switch/enable" },
117 { REQ, "events/sched/sched_wakeup/enable" },
Joel Fernandes237c3632017-06-04 13:05:59 -0700118 { OPT, "events/sched/sched_waking/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800119 { OPT, "events/sched/sched_blocked_reason/enable" },
120 { OPT, "events/sched/sched_cpu_hotplug/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800121 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700122 { "irq", "IRQ Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800123 { REQ, "events/irq/enable" },
124 { OPT, "events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700125 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100126 { "i2c", "I2C Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800127 { REQ, "events/i2c/enable" },
128 { REQ, "events/i2c/i2c_read/enable" },
129 { REQ, "events/i2c/i2c_write/enable" },
130 { REQ, "events/i2c/i2c_result/enable" },
131 { REQ, "events/i2c/i2c_reply/enable" },
132 { OPT, "events/i2c/smbus_read/enable" },
133 { OPT, "events/i2c/smbus_write/enable" },
134 { OPT, "events/i2c/smbus_result/enable" },
135 { OPT, "events/i2c/smbus_reply/enable" },
Michael Wright43fb6782016-08-18 19:56:43 +0100136 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700137 { "freq", "CPU Frequency", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800138 { REQ, "events/power/cpu_frequency/enable" },
139 { OPT, "events/power/clock_set_rate/enable" },
140 { OPT, "events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800141 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700142 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800143 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800144 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700145 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800146 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800147 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700148 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800149 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
150 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
151 { OPT, "events/f2fs/f2fs_write_begin/enable" },
152 { OPT, "events/f2fs/f2fs_write_end/enable" },
153 { OPT, "events/ext4/ext4_da_write_begin/enable" },
154 { OPT, "events/ext4/ext4_da_write_end/enable" },
155 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
156 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
157 { REQ, "events/block/block_rq_issue/enable" },
158 { REQ, "events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800159 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700160 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800161 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700162 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700163 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800164 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800165 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700166 { "sync", "Synchronization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800167 { REQ, "events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800168 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700169 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800170 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800171 } },
Colin Cross580407f2014-08-18 15:22:13 -0700172 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800173 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
174 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
175 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
176 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700177 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800178 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800179 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800180 } },
Scott Bauerae473362015-06-08 16:32:36 -0700181 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800182 { REQ, "events/binder/binder_transaction/enable" },
183 { REQ, "events/binder/binder_transaction_received/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700184 } },
185 { "binder_lock", "Binder global lock trace", 0, {
Howard Chen4a9dda12017-05-10 16:32:11 +0800186 { OPT, "events/binder/binder_lock/enable" },
187 { OPT, "events/binder/binder_locked/enable" },
188 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700189 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200190 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800191 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200192 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800193};
194
195/* Command line options */
196static int g_traceDurationSeconds = 5;
197static bool g_traceOverwrite = false;
198static int g_traceBufferSizeKB = 2048;
199static bool g_compress = false;
200static bool g_nohup = false;
201static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900202static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700203static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700204static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700205static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800206
207/* Global state */
208static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700209static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800210static std::string g_traceFolder;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800211
212/* Sys file paths */
213static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800214 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800215
216static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800217 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800218
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700219#if 0
220// TODO: Re-enable after stabilization
Joel Fernandesefb73a92017-06-02 10:19:28 -0700221static const char* k_traceCmdlineSizePath =
222 "saved_cmdlines_size";
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700223#endif
Joel Fernandesefb73a92017-06-02 10:19:28 -0700224
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800225static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800226 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800227
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700228static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800229 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700230
231static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800232 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700233
234static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800235 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700236
237static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800238 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700239
240static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800241 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700242
243static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800244 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700245
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700246static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800247 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700248
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800249static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800250 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800251
252static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800253 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800254
Martijn Coenend9535872015-11-26 10:00:55 +0100255static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800256 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100257
John Reck469a1942015-03-26 15:31:35 -0700258static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800259 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700260
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800261// Check whether a file exists.
262static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800263 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800264}
265
266// Check whether a file is writable.
267static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800268 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800269}
270
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700271// Truncate a file.
272static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800273{
Jamie Gennis43122e72013-03-21 14:06:31 -0700274 // This uses creat rather than truncate because some of the debug kernel
275 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
276 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800277 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700278 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800279 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700280 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700281 return false;
282 }
283
Jamie Gennis43122e72013-03-21 14:06:31 -0700284 close(traceFD);
285
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700286 return true;
287}
288
289static bool _writeStr(const char* filename, const char* str, int flags)
290{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800291 std::string fullFilename = g_traceFolder + filename;
292 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800293 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800294 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800295 strerror(errno), errno);
296 return false;
297 }
298
299 bool ok = true;
300 ssize_t len = strlen(str);
301 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800302 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800303 strerror(errno), errno);
304 ok = false;
305 }
306
307 close(fd);
308
309 return ok;
310}
311
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700312// Write a string to a file, returning true if the write was successful.
313static bool writeStr(const char* filename, const char* str)
314{
315 return _writeStr(filename, str, O_WRONLY);
316}
317
318// Append a string to a file, returning true if the write was successful.
319static bool appendStr(const char* filename, const char* str)
320{
321 return _writeStr(filename, str, O_APPEND|O_WRONLY);
322}
323
John Reck469a1942015-03-26 15:31:35 -0700324static void writeClockSyncMarker()
325{
326 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200327 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800328 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200329 if (fd == -1) {
330 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
331 strerror(errno), errno);
332 return;
333 }
John Reck469a1942015-03-26 15:31:35 -0700334 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200335
336 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
337 if (write(fd, buffer, len) != len) {
338 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
339 }
340
341 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
342 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
343 if (write(fd, buffer, len) != len) {
344 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
345 }
346
347 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700348}
349
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800350// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
351// file.
352static bool setKernelOptionEnable(const char* filename, bool enable)
353{
354 return writeStr(filename, enable ? "1" : "0");
355}
356
357// Check whether the category is supported on the device with the current
358// rootness. A category is supported only if all its required /sys/ files are
359// writable and if enabling the category will enable one or more tracing tags
360// or /sys/ files.
361static bool isCategorySupported(const TracingCategory& category)
362{
sergeyvdb404152016-05-02 19:26:07 -0700363 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700364 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700365 }
366
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800367 bool ok = category.tags != 0;
368 for (int i = 0; i < MAX_SYS_FILES; i++) {
369 const char* path = category.sysfiles[i].path;
370 bool req = category.sysfiles[i].required == REQ;
371 if (path != NULL) {
372 if (req) {
373 if (!fileIsWritable(path)) {
374 return false;
375 } else {
376 ok = true;
377 }
378 } else {
Howard Chen4a9dda12017-05-10 16:32:11 +0800379 ok = true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800380 }
381 }
382 }
383 return ok;
384}
385
386// Check whether the category would be supported on the device if the user
387// were root. This function assumes that root is able to write to any file
388// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700389// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800390static bool isCategorySupportedForRoot(const TracingCategory& category)
391{
392 bool ok = category.tags != 0;
393 for (int i = 0; i < MAX_SYS_FILES; i++) {
394 const char* path = category.sysfiles[i].path;
395 bool req = category.sysfiles[i].required == REQ;
396 if (path != NULL) {
397 if (req) {
398 if (!fileExists(path)) {
399 return false;
400 } else {
401 ok = true;
402 }
403 } else {
404 ok |= fileExists(path);
405 }
406 }
407 }
408 return ok;
409}
410
411// Enable or disable overwriting of the kernel trace buffers. Disabling this
412// will cause tracing to stop once the trace buffers have filled up.
413static bool setTraceOverwriteEnable(bool enable)
414{
415 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
416}
417
418// Enable or disable kernel tracing.
419static bool setTracingEnabled(bool enable)
420{
421 return setKernelOptionEnable(k_tracingOnPath, enable);
422}
423
424// Clear the contents of the kernel trace.
425static bool clearTrace()
426{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700427 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800428}
429
430// Set the size of the kernel's trace buffer in kilobytes.
431static bool setTraceBufferSizeKB(int size)
432{
433 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800434 if (size < 1) {
435 size = 1;
436 }
437 snprintf(str, 32, "%d", size);
438 return writeStr(k_traceBufferSizePath, str);
439}
440
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700441#if 0
442// TODO: Re-enable after stabilization
Joel Fernandesefb73a92017-06-02 10:19:28 -0700443// Set the default size of cmdline hashtable
444static bool setCmdlineSize()
445{
Joel Fernandes9351f722017-06-06 12:20:29 -0700446 if (fileExists(k_traceCmdlineSizePath)) {
447 return writeStr(k_traceCmdlineSizePath, "8192");
448 }
449 return true;
Joel Fernandesefb73a92017-06-02 10:19:28 -0700450}
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700451#endif
Joel Fernandesefb73a92017-06-02 10:19:28 -0700452
Carmen Jacksonea826792017-05-05 11:42:32 -0700453// Set the clock to the best available option while tracing. Use 'boot' if it's
454// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700455// Any write to the trace_clock sysfs file will reset the buffer, so only
456// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700457static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800458{
Carmen Jacksonea826792017-05-05 11:42:32 -0700459 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
460 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
461 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700462
Carmen Jacksonea826792017-05-05 11:42:32 -0700463 std::string newClock;
464 if (clockStr.find("boot") != std::string::npos) {
465 newClock = "boot";
466 } else if (clockStr.find("mono") != std::string::npos) {
467 newClock = "mono";
468 } else {
469 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700470 }
471
Carmen Jacksonea826792017-05-05 11:42:32 -0700472 size_t begin = clockStr.find("[") + 1;
473 size_t end = clockStr.find("]");
474 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
475 return true;
476 }
477 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800478}
479
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700480static bool setPrintTgidEnableIfPresent(bool enable)
481{
482 if (fileExists(k_printTgidPath)) {
483 return setKernelOptionEnable(k_printTgidPath, enable);
484 }
485 return true;
486}
487
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800488// Poke all the binder-enabled processes in the system to get them to re-read
489// their system properties.
490static bool pokeBinderServices()
491{
492 sp<IServiceManager> sm = defaultServiceManager();
493 Vector<String16> services = sm->listServices();
494 for (size_t i = 0; i < services.size(); i++) {
495 sp<IBinder> obj = sm->checkService(services[i]);
496 if (obj != NULL) {
497 Parcel data;
498 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
499 NULL, 0) != OK) {
500 if (false) {
501 // XXX: For some reason this fails on tablets trying to
502 // poke the "phone" service. It's not clear whether some
503 // are expected to fail.
504 String8 svc(services[i]);
505 fprintf(stderr, "error poking binder service %s\n",
506 svc.string());
507 return false;
508 }
509 }
510 }
511 }
512 return true;
513}
514
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100515// Poke all the HAL processes in the system to get them to re-read
516// their system properties.
517static void pokeHalServices()
518{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100519 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100520 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100521 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100522 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100523
524 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800525
526 if (sm == nullptr) {
527 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
528 return;
529 }
530
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800531 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100532 for (size_t i = 0; i < interfaces.size(); i++) {
533 string fqInstanceName = interfaces[i];
534 string::size_type n = fqInstanceName.find("/");
535 if (n == std::string::npos || interfaces[i].size() == n+1)
536 continue;
537 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
538 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100539 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
540 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100541 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100542 continue;
543 }
Carmen Jackson73206122017-04-18 15:37:57 -0700544
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100545 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700546 if (interface == nullptr) {
547 // ignore
548 continue;
549 }
550
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100551 auto notifyRet = interface->notifySyspropsChanged();
552 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100553 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800554 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100555 }
556 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800557 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100558 // TODO(b/34242478) fix this when we determine the correct ACL
559 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800560 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100561}
562
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800563// Set the trace tags that userland tracing uses, and poke the running
564// processes to pick up the new value.
565static bool setTagsProperty(uint64_t tags)
566{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700567 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
568 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800569 fprintf(stderr, "error setting trace tags system property\n");
570 return false;
571 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700572 return true;
573}
574
sergeyv4144eff2016-04-28 11:40:04 -0700575static void clearAppProperties()
576{
sergeyv4144eff2016-04-28 11:40:04 -0700577 for (int i = 0; i < MAX_PACKAGES; i++) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700578 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
579 if (!android::base::SetProperty(key, "")) {
580 fprintf(stderr, "failed to clear system property: %s\n", key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700581 }
582 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700583 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700584 fprintf(stderr, "failed to clear system property: %s",
585 k_traceAppsNumberProperty);
586 }
587}
588
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700589// Set the system property that indicates which apps should perform
590// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700591static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700592{
sergeyv4144eff2016-04-28 11:40:04 -0700593 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700594 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700595 while (start != NULL) {
596 if (i == MAX_PACKAGES) {
597 fprintf(stderr, "error: only 16 packages could be traced at once\n");
598 clearAppProperties();
599 return false;
600 }
601 char* end = strchr(start, ',');
602 if (end != NULL) {
603 *end = '\0';
604 end++;
605 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700606 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
607 if (!android::base::SetProperty(key, start)) {
608 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700609 clearAppProperties();
610 return false;
611 }
612 start = end;
613 i++;
614 }
615
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700616 std::string value = android::base::StringPrintf("%d", i);
617 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
618 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700619 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700620 return false;
621 }
622 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800623}
624
625// Disable all /sys/ enable files.
626static bool disableKernelTraceEvents() {
627 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700628 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800629 const TracingCategory &c = k_categories[i];
630 for (int j = 0; j < MAX_SYS_FILES; j++) {
631 const char* path = c.sysfiles[j].path;
632 if (path != NULL && fileIsWritable(path)) {
633 ok &= setKernelOptionEnable(path, false);
634 }
635 }
636 }
637 return ok;
638}
639
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700640// Verify that the comma separated list of functions are being traced by the
641// kernel.
642static bool verifyKernelTraceFuncs(const char* funcs)
643{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100644 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800645 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100646 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700647 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100648 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700649 }
650
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100651 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700652
653 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100654 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700655 bool ok = true;
656 char* myFuncs = strdup(funcs);
657 char* func = strtok(myFuncs, ",");
658 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100659 if (!strchr(func, '*')) {
660 String8 fancyFunc = String8::format("\n%s\n", func);
661 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
662 if (!found || func[0] == '\0') {
663 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
664 "to trace.\n", func);
665 ok = false;
666 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700667 }
668 func = strtok(NULL, ",");
669 }
670 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700671 return ok;
672}
673
674// Set the comma separated list of functions that the kernel is to trace.
675static bool setKernelTraceFuncs(const char* funcs)
676{
677 bool ok = true;
678
679 if (funcs == NULL || funcs[0] == '\0') {
680 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700681 if (fileIsWritable(k_currentTracerPath)) {
682 ok &= writeStr(k_currentTracerPath, "nop");
683 }
684 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700685 ok &= truncateFile(k_ftraceFilterPath);
686 }
687 } else {
688 // Enable kernel function tracing.
689 ok &= writeStr(k_currentTracerPath, "function_graph");
690 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
691 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
692 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
693 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
694
695 // Set the requested filter functions.
696 ok &= truncateFile(k_ftraceFilterPath);
697 char* myFuncs = strdup(funcs);
698 char* func = strtok(myFuncs, ",");
699 while (func) {
700 ok &= appendStr(k_ftraceFilterPath, func);
701 func = strtok(NULL, ",");
702 }
703 free(myFuncs);
704
705 // Verify that the set functions are being traced.
706 if (ok) {
707 ok &= verifyKernelTraceFuncs(funcs);
708 }
709 }
710
711 return ok;
712}
713
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900714static bool setCategoryEnable(const char* name, bool enable)
715{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700716 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900717 const TracingCategory& c = k_categories[i];
718 if (strcmp(name, c.name) == 0) {
719 if (isCategorySupported(c)) {
720 g_categoryEnables[i] = enable;
721 return true;
722 } else {
723 if (isCategorySupportedForRoot(c)) {
724 fprintf(stderr, "error: category \"%s\" requires root "
725 "privileges.\n", name);
726 } else {
727 fprintf(stderr, "error: category \"%s\" is not supported "
728 "on this device.\n", name);
729 }
730 return false;
731 }
732 }
733 }
734 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
735 return false;
736}
737
738static bool setCategoriesEnableFromFile(const char* categories_file)
739{
740 if (!categories_file) {
741 return true;
742 }
743 Tokenizer* tokenizer = NULL;
744 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
745 return false;
746 }
747 bool ok = true;
748 while (!tokenizer->isEol()) {
749 String8 token = tokenizer->nextToken(" ");
750 if (token.isEmpty()) {
751 tokenizer->skipDelimiters(" ");
752 continue;
753 }
754 ok &= setCategoryEnable(token.string(), true);
755 }
756 delete tokenizer;
757 return ok;
758}
759
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700760// Set all the kernel tracing settings to the desired state for this trace
761// capture.
762static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800763{
764 bool ok = true;
765
766 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900767 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800768 ok &= setTraceOverwriteEnable(g_traceOverwrite);
769 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
John Reckba54d5b2017-06-23 09:44:08 -0700770 // TODO: Re-enable after stabilization
771 //ok &= setCmdlineSize();
Carmen Jacksonea826792017-05-05 11:42:32 -0700772 ok &= setClock();
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700773 ok &= setPrintTgidEnableIfPresent(true);
774 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800775
776 // Set up the tags property.
777 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700778 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800779 if (g_categoryEnables[i]) {
780 const TracingCategory &c = k_categories[i];
781 tags |= c.tags;
782 }
783 }
784 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700785
786 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700787 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700788 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
789 coreServicesTagEnabled = g_categoryEnables[i];
790 }
791 }
792
793 std::string packageList(g_debugAppCmdLine);
794 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700795 if (!packageList.empty()) {
796 packageList += ",";
797 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700798 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700799 }
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.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700809 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800810 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 {
Josh Gaod3d36e72017-04-11 15:21:13 -0700974 char buf[4096];
975 ssize_t rc;
976 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
977 if (!android::base::WriteFully(outFd, buf, rc)) {
978 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
979 break;
980 }
981 }
982 if (rc == -1) {
983 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800984 }
985 }
986
987 close(traceFD);
988}
989
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700990static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800991{
992 if (!g_nohup) {
993 g_traceAborted = true;
994 }
995}
996
997static void registerSigHandler()
998{
999 struct sigaction sa;
1000 sigemptyset(&sa.sa_mask);
1001 sa.sa_flags = 0;
1002 sa.sa_handler = handleSignal;
1003 sigaction(SIGHUP, &sa, NULL);
1004 sigaction(SIGINT, &sa, NULL);
1005 sigaction(SIGQUIT, &sa, NULL);
1006 sigaction(SIGTERM, &sa, NULL);
1007}
1008
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001009static void listSupportedCategories()
1010{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001011 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001012 const TracingCategory& c = k_categories[i];
1013 if (isCategorySupported(c)) {
1014 printf(" %10s - %s\n", c.name, c.longname);
1015 }
1016 }
1017}
1018
1019// Print the command usage help to stderr.
1020static void showHelp(const char *cmd)
1021{
1022 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1023 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001024 " -a appname enable app-level tracing for a comma "
1025 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001026 " -b N use a trace buffer size of N KB\n"
1027 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001028 " -f filename use the categories written in a file as space-separated\n"
1029 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001030 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001031 " -n ignore signals\n"
1032 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001033 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001034 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001035 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001036 " --async_dump dump the current contents of circular trace buffer\n"
1037 " --async_stop stop tracing and dump the current contents of circular\n"
1038 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001039 " --stream stream trace to stdout as it enters the trace buffer\n"
1040 " Note: this can take significant CPU time, and is best\n"
1041 " used for measuring things that are not affected by\n"
1042 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001043 " --list_categories\n"
1044 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001045 " -o filename write the trace to the specified file instead\n"
1046 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001047 );
1048}
1049
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001050bool findTraceFiles()
1051{
1052 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1053 static const std::string tracefs_path = "/sys/kernel/tracing/";
1054 static const std::string trace_file = "trace_marker";
1055
1056 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1057 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1058
1059 if (!tracefs && !debugfs) {
1060 fprintf(stderr, "Error: Did not find trace folder\n");
1061 return false;
1062 }
1063
1064 if (tracefs) {
1065 g_traceFolder = tracefs_path;
1066 } else {
1067 g_traceFolder = debugfs_path;
1068 }
1069
1070 return true;
1071}
1072
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001073int main(int argc, char **argv)
1074{
1075 bool async = false;
1076 bool traceStart = true;
1077 bool traceStop = true;
1078 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001079 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001080
1081 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1082 showHelp(argv[0]);
1083 exit(0);
1084 }
1085
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001086 if (!findTraceFiles()) {
1087 fprintf(stderr, "No trace folder found\n");
1088 exit(-1);
1089 }
1090
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001091 for (;;) {
1092 int ret;
1093 int option_index = 0;
1094 static struct option long_options[] = {
1095 {"async_start", no_argument, 0, 0 },
1096 {"async_stop", no_argument, 0, 0 },
1097 {"async_dump", no_argument, 0, 0 },
1098 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +01001099 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001100 { 0, 0, 0, 0 }
1101 };
1102
John Reck40b26b42016-03-30 09:44:36 -07001103 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001104 long_options, &option_index);
1105
1106 if (ret < 0) {
1107 for (int i = optind; i < argc; i++) {
1108 if (!setCategoryEnable(argv[i], true)) {
1109 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1110 exit(1);
1111 }
1112 }
1113 break;
1114 }
1115
1116 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001117 case 'a':
1118 g_debugAppCmdLine = optarg;
1119 break;
1120
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001121 case 'b':
1122 g_traceBufferSizeKB = atoi(optarg);
1123 break;
1124
1125 case 'c':
1126 g_traceOverwrite = true;
1127 break;
1128
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001129 case 'f':
1130 g_categoriesFile = optarg;
1131 break;
1132
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001133 case 'k':
1134 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001135 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001136
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001137 case 'n':
1138 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001139 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001140
1141 case 's':
1142 g_initialSleepSecs = atoi(optarg);
1143 break;
1144
1145 case 't':
1146 g_traceDurationSeconds = atoi(optarg);
1147 break;
1148
1149 case 'z':
1150 g_compress = true;
1151 break;
1152
John Reck40b26b42016-03-30 09:44:36 -07001153 case 'o':
1154 g_outputFile = optarg;
1155 break;
1156
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001157 case 0:
1158 if (!strcmp(long_options[option_index].name, "async_start")) {
1159 async = true;
1160 traceStop = false;
1161 traceDump = false;
1162 g_traceOverwrite = true;
1163 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1164 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001165 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001166 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1167 async = true;
1168 traceStart = false;
1169 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001170 } else if (!strcmp(long_options[option_index].name, "stream")) {
1171 traceStream = true;
1172 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001173 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1174 listSupportedCategories();
1175 exit(0);
1176 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001177 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001178
1179 default:
1180 fprintf(stderr, "\n");
1181 showHelp(argv[0]);
1182 exit(-1);
1183 break;
1184 }
1185 }
1186
1187 registerSigHandler();
1188
1189 if (g_initialSleepSecs > 0) {
1190 sleep(g_initialSleepSecs);
1191 }
1192
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001193 bool ok = true;
1194 ok &= setUpTrace();
1195 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001196
1197 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001198 if (!traceStream) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001199 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001200 fflush(stdout);
1201 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001202
1203 // We clear the trace after starting it because tracing gets enabled for
1204 // each CPU individually in the kernel. Having the beginning of the trace
1205 // contain entries from only one CPU can cause "begin" entries without a
1206 // matching "end" entry to show up if a task gets migrated from one CPU to
1207 // another.
1208 ok = clearTrace();
1209
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001210 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001211 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001212 // Sleep to allow the trace to be captured.
1213 struct timespec timeLeft;
1214 timeLeft.tv_sec = g_traceDurationSeconds;
1215 timeLeft.tv_nsec = 0;
1216 do {
1217 if (g_traceAborted) {
1218 break;
1219 }
1220 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1221 }
Martijn Coenend9535872015-11-26 10:00:55 +01001222
1223 if (traceStream) {
1224 streamTrace();
1225 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001226 }
1227
1228 // Stop the trace and restore the default settings.
1229 if (traceStop)
1230 stopTrace();
1231
1232 if (ok && traceDump) {
1233 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001234 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001235 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001236 int outFd = STDOUT_FILENO;
1237 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001238 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001239 }
1240 if (outFd == -1) {
1241 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1242 } else {
1243 dprintf(outFd, "TRACE:\n");
1244 dumpTrace(outFd);
1245 if (g_outputFile) {
1246 close(outFd);
1247 }
1248 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001249 } else {
1250 printf("\ntrace aborted.\n");
1251 fflush(stdout);
1252 }
1253 clearTrace();
1254 } else if (!ok) {
1255 fprintf(stderr, "unable to start tracing\n");
1256 }
1257
1258 // Reset the trace buffer size to 1.
1259 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001260 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001261
1262 return g_traceAborted ? 1 : 0;
1263}