blob: 9dbbb7757cd006fa15e7358385d830f508f9820e [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
Corey Tabakaa6c0a722017-05-31 16:37:40 -070043#include <pdx/default_transport/service_utility.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080044#include <utils/String8.h>
John Reck469a1942015-03-26 15:31:35 -070045#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +090046#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080047#include <utils/Trace.h>
Stephane Gasparinid8419c22016-03-02 13:45:15 +010048#include <android-base/file.h>
Elliott Hughes5fd6ff62017-03-28 14:55:31 -070049#include <android-base/macros.h>
50#include <android-base/properties.h>
51#include <android-base/stringprintf.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080052
53using namespace android;
Corey Tabakaa6c0a722017-05-31 16:37:40 -070054using pdx::default_transport::ServiceUtility;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080055
Martijn Coenenee9b97e2016-11-16 16:00:26 +010056using std::string;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080057
sergeyv4144eff2016-04-28 11:40:04 -070058#define MAX_SYS_FILES 10
59#define MAX_PACKAGES 16
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080060
61const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
sergeyv4144eff2016-04-28 11:40:04 -070062
63const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
64const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070065const char* k_coreServiceCategory = "core_services";
Corey Tabakaa6c0a722017-05-31 16:37:40 -070066const char* k_pdxServiceCategory = "pdx";
sergeyvdb404152016-05-02 19:26:07 -070067const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080068
69typedef enum { OPT, REQ } requiredness ;
70
71struct TracingCategory {
72 // The name identifying the category.
73 const char* name;
74
75 // A longer description of the category.
76 const char* longname;
77
78 // The userland tracing tags that the category enables.
79 uint64_t tags;
80
81 // The fname==NULL terminated list of /sys/ files that the category
82 // enables.
83 struct {
84 // Whether the file must be writable in order to enable the tracing
85 // category.
86 requiredness required;
87
88 // The path to the enable file.
89 const char* path;
90 } sysfiles[MAX_SYS_FILES];
91};
92
93/* Tracing categories */
94static const TracingCategory k_categories[] = {
John Reck732a29a2017-05-24 16:09:21 -070095 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, {
96 { OPT, "events/mdss/enable" },
97 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070098 { "input", "Input", ATRACE_TAG_INPUT, { } },
99 { "view", "View System", ATRACE_TAG_VIEW, { } },
100 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
101 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
102 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -0500103 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700104 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
105 { "video", "Video", ATRACE_TAG_VIDEO, { } },
106 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
107 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700108 { "app", "Application", ATRACE_TAG_APP, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -0700109 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -0700110 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -0700111 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -0700112 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700113 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 14:36:20 -0700114 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-07-01 01:46:25 +0900115 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Greg Hackmannbbd7d992014-12-01 14:43:34 -0800116 { "database", "Database", ATRACE_TAG_DATABASE, { } },
Felipe Leme0f97c1d2016-09-07 11:33:26 -0700117 { "network", "Network", ATRACE_TAG_NETWORK, { } },
Josh Gao468b4cb2016-11-29 10:55:21 -0800118 { "adb", "ADB", ATRACE_TAG_ADB, { } },
sergeyvdb404152016-05-02 19:26:07 -0700119 { k_coreServiceCategory, "Core services", 0, { } },
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700120 { k_pdxServiceCategory, "PDX services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700121 { "sched", "CPU Scheduling", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800122 { REQ, "events/sched/sched_switch/enable" },
123 { REQ, "events/sched/sched_wakeup/enable" },
Joel Fernandesee593e22017-06-04 13:05:59 -0700124 { OPT, "events/sched/sched_waking/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800125 { OPT, "events/sched/sched_blocked_reason/enable" },
126 { OPT, "events/sched/sched_cpu_hotplug/enable" },
Joel Fernandes4dfca7c2017-06-15 16:53:52 -0700127 { OPT, "events/cgroup/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800128 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700129 { "irq", "IRQ Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800130 { REQ, "events/irq/enable" },
131 { OPT, "events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700132 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100133 { "i2c", "I2C Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800134 { REQ, "events/i2c/enable" },
135 { REQ, "events/i2c/i2c_read/enable" },
136 { REQ, "events/i2c/i2c_write/enable" },
137 { REQ, "events/i2c/i2c_result/enable" },
138 { REQ, "events/i2c/i2c_reply/enable" },
139 { OPT, "events/i2c/smbus_read/enable" },
140 { OPT, "events/i2c/smbus_write/enable" },
141 { OPT, "events/i2c/smbus_result/enable" },
142 { OPT, "events/i2c/smbus_reply/enable" },
Michael Wright43fb6782016-08-18 19:56:43 +0100143 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700144 { "freq", "CPU Frequency", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800145 { REQ, "events/power/cpu_frequency/enable" },
146 { OPT, "events/power/clock_set_rate/enable" },
147 { OPT, "events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800148 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700149 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800150 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800151 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700152 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800153 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800154 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700155 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800156 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
157 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
158 { OPT, "events/f2fs/f2fs_write_begin/enable" },
159 { OPT, "events/f2fs/f2fs_write_end/enable" },
160 { OPT, "events/ext4/ext4_da_write_begin/enable" },
161 { OPT, "events/ext4/ext4_da_write_end/enable" },
162 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
163 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
164 { REQ, "events/block/block_rq_issue/enable" },
165 { REQ, "events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800166 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700167 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800168 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700169 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700170 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800171 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800172 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700173 { "sync", "Synchronization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800174 { REQ, "events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800175 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700176 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800177 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800178 } },
Colin Cross580407f2014-08-18 15:22:13 -0700179 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800180 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
181 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
182 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
183 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Marc Hittingerf1f62e32017-05-17 15:57:43 -0700184 { REQ, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700185 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800186 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800187 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800188 } },
Scott Bauerae473362015-06-08 16:32:36 -0700189 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800190 { REQ, "events/binder/binder_transaction/enable" },
191 { REQ, "events/binder/binder_transaction_received/enable" },
Martijn Coenen7f3d7a22017-05-26 09:50:55 -0700192 { OPT, "events/binder/binder_set_priority/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700193 } },
194 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800195 { OPT, "events/binder/binder_lock/enable" },
196 { OPT, "events/binder/binder_locked/enable" },
197 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700198 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200199 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800200 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200201 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800202};
203
204/* Command line options */
205static int g_traceDurationSeconds = 5;
206static bool g_traceOverwrite = false;
207static int g_traceBufferSizeKB = 2048;
208static bool g_compress = false;
209static bool g_nohup = false;
210static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900211static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700212static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700213static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700214static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800215
216/* Global state */
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700217static bool g_tracePdx = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800218static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700219static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800220static std::string g_traceFolder;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800221
222/* Sys file paths */
223static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800224 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800225
226static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800227 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800228
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700229#if 0
230// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700231static const char* k_traceCmdlineSizePath =
232 "saved_cmdlines_size";
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700233#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700234
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800235static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800236 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800237
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700238static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800239 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700240
241static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800242 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700243
244static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800245 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700246
247static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800248 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700249
250static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800251 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700252
253static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800254 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700255
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700256static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800257 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700258
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800259static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800260 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800261
262static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800263 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800264
Martijn Coenend9535872015-11-26 10:00:55 +0100265static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800266 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100267
John Reck469a1942015-03-26 15:31:35 -0700268static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800269 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700270
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800271// Check whether a file exists.
272static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800273 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800274}
275
276// Check whether a file is writable.
277static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800278 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800279}
280
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700281// Truncate a file.
282static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800283{
Jamie Gennis43122e72013-03-21 14:06:31 -0700284 // This uses creat rather than truncate because some of the debug kernel
285 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
286 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800287 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700288 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800289 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700290 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700291 return false;
292 }
293
Jamie Gennis43122e72013-03-21 14:06:31 -0700294 close(traceFD);
295
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700296 return true;
297}
298
299static bool _writeStr(const char* filename, const char* str, int flags)
300{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800301 std::string fullFilename = g_traceFolder + filename;
302 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800303 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800304 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800305 strerror(errno), errno);
306 return false;
307 }
308
309 bool ok = true;
310 ssize_t len = strlen(str);
311 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800312 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800313 strerror(errno), errno);
314 ok = false;
315 }
316
317 close(fd);
318
319 return ok;
320}
321
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700322// Write a string to a file, returning true if the write was successful.
323static bool writeStr(const char* filename, const char* str)
324{
325 return _writeStr(filename, str, O_WRONLY);
326}
327
328// Append a string to a file, returning true if the write was successful.
329static bool appendStr(const char* filename, const char* str)
330{
331 return _writeStr(filename, str, O_APPEND|O_WRONLY);
332}
333
John Reck469a1942015-03-26 15:31:35 -0700334static void writeClockSyncMarker()
335{
336 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200337 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800338 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200339 if (fd == -1) {
340 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
341 strerror(errno), errno);
342 return;
343 }
John Reck469a1942015-03-26 15:31:35 -0700344 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200345
346 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
347 if (write(fd, buffer, len) != len) {
348 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
349 }
350
351 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
352 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
353 if (write(fd, buffer, len) != len) {
354 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
355 }
356
357 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700358}
359
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800360// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
361// file.
362static bool setKernelOptionEnable(const char* filename, bool enable)
363{
364 return writeStr(filename, enable ? "1" : "0");
365}
366
367// Check whether the category is supported on the device with the current
368// rootness. A category is supported only if all its required /sys/ files are
369// writable and if enabling the category will enable one or more tracing tags
370// or /sys/ files.
371static bool isCategorySupported(const TracingCategory& category)
372{
sergeyvdb404152016-05-02 19:26:07 -0700373 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700374 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700375 }
376
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700377 if (strcmp(category.name, k_pdxServiceCategory) == 0) {
378 return true;
379 }
380
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800381 bool ok = category.tags != 0;
382 for (int i = 0; i < MAX_SYS_FILES; i++) {
383 const char* path = category.sysfiles[i].path;
384 bool req = category.sysfiles[i].required == REQ;
385 if (path != NULL) {
386 if (req) {
387 if (!fileIsWritable(path)) {
388 return false;
389 } else {
390 ok = true;
391 }
392 } else {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800393 ok = true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800394 }
395 }
396 }
397 return ok;
398}
399
400// Check whether the category would be supported on the device if the user
401// were root. This function assumes that root is able to write to any file
402// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700403// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800404static bool isCategorySupportedForRoot(const TracingCategory& category)
405{
406 bool ok = category.tags != 0;
407 for (int i = 0; i < MAX_SYS_FILES; i++) {
408 const char* path = category.sysfiles[i].path;
409 bool req = category.sysfiles[i].required == REQ;
410 if (path != NULL) {
411 if (req) {
412 if (!fileExists(path)) {
413 return false;
414 } else {
415 ok = true;
416 }
417 } else {
418 ok |= fileExists(path);
419 }
420 }
421 }
422 return ok;
423}
424
425// Enable or disable overwriting of the kernel trace buffers. Disabling this
426// will cause tracing to stop once the trace buffers have filled up.
427static bool setTraceOverwriteEnable(bool enable)
428{
429 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
430}
431
432// Enable or disable kernel tracing.
433static bool setTracingEnabled(bool enable)
434{
435 return setKernelOptionEnable(k_tracingOnPath, enable);
436}
437
438// Clear the contents of the kernel trace.
439static bool clearTrace()
440{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700441 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800442}
443
444// Set the size of the kernel's trace buffer in kilobytes.
445static bool setTraceBufferSizeKB(int size)
446{
447 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800448 if (size < 1) {
449 size = 1;
450 }
451 snprintf(str, 32, "%d", size);
452 return writeStr(k_traceBufferSizePath, str);
453}
454
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700455#if 0
456// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700457// Set the default size of cmdline hashtable
458static bool setCmdlineSize()
459{
Joel Fernandesce964f22017-06-06 12:20:29 -0700460 if (fileExists(k_traceCmdlineSizePath)) {
461 return writeStr(k_traceCmdlineSizePath, "8192");
462 }
463 return true;
Joel Fernandesed80bd02017-06-02 10:19:28 -0700464}
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700465#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700466
Carmen Jacksonea826792017-05-05 11:42:32 -0700467// Set the clock to the best available option while tracing. Use 'boot' if it's
468// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700469// Any write to the trace_clock sysfs file will reset the buffer, so only
470// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700471static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800472{
Carmen Jacksonea826792017-05-05 11:42:32 -0700473 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
474 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
475 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700476
Carmen Jacksonea826792017-05-05 11:42:32 -0700477 std::string newClock;
478 if (clockStr.find("boot") != std::string::npos) {
479 newClock = "boot";
480 } else if (clockStr.find("mono") != std::string::npos) {
481 newClock = "mono";
482 } else {
483 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700484 }
485
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700486 size_t begin = clockStr.find('[') + 1;
487 size_t end = clockStr.find(']');
Carmen Jacksonea826792017-05-05 11:42:32 -0700488 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
489 return true;
490 }
491 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800492}
493
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700494static bool setPrintTgidEnableIfPresent(bool enable)
495{
496 if (fileExists(k_printTgidPath)) {
497 return setKernelOptionEnable(k_printTgidPath, enable);
498 }
499 return true;
500}
501
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800502// Poke all the binder-enabled processes in the system to get them to re-read
503// their system properties.
504static bool pokeBinderServices()
505{
506 sp<IServiceManager> sm = defaultServiceManager();
507 Vector<String16> services = sm->listServices();
508 for (size_t i = 0; i < services.size(); i++) {
509 sp<IBinder> obj = sm->checkService(services[i]);
510 if (obj != NULL) {
511 Parcel data;
512 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
513 NULL, 0) != OK) {
514 if (false) {
515 // XXX: For some reason this fails on tablets trying to
516 // poke the "phone" service. It's not clear whether some
517 // are expected to fail.
518 String8 svc(services[i]);
519 fprintf(stderr, "error poking binder service %s\n",
520 svc.string());
521 return false;
522 }
523 }
524 }
525 }
526 return true;
527}
528
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100529// Poke all the HAL processes in the system to get them to re-read
530// their system properties.
531static void pokeHalServices()
532{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100533 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100534 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100535 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100536 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100537
538 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800539
540 if (sm == nullptr) {
541 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
542 return;
543 }
544
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800545 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100546 for (size_t i = 0; i < interfaces.size(); i++) {
547 string fqInstanceName = interfaces[i];
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700548 string::size_type n = fqInstanceName.find('/');
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100549 if (n == std::string::npos || interfaces[i].size() == n+1)
550 continue;
551 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
552 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100553 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
554 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100555 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100556 continue;
557 }
Carmen Jackson73206122017-04-18 15:37:57 -0700558
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100559 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700560 if (interface == nullptr) {
561 // ignore
562 continue;
563 }
564
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100565 auto notifyRet = interface->notifySyspropsChanged();
566 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100567 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800568 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100569 }
570 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800571 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100572 // TODO(b/34242478) fix this when we determine the correct ACL
573 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800574 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100575}
576
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800577// Set the trace tags that userland tracing uses, and poke the running
578// processes to pick up the new value.
579static bool setTagsProperty(uint64_t tags)
580{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700581 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
582 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800583 fprintf(stderr, "error setting trace tags system property\n");
584 return false;
585 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700586 return true;
587}
588
sergeyv4144eff2016-04-28 11:40:04 -0700589static void clearAppProperties()
590{
sergeyv4144eff2016-04-28 11:40:04 -0700591 for (int i = 0; i < MAX_PACKAGES; i++) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700592 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
593 if (!android::base::SetProperty(key, "")) {
594 fprintf(stderr, "failed to clear system property: %s\n", key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700595 }
596 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700597 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700598 fprintf(stderr, "failed to clear system property: %s",
599 k_traceAppsNumberProperty);
600 }
601}
602
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700603// Set the system property that indicates which apps should perform
604// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700605static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700606{
sergeyv4144eff2016-04-28 11:40:04 -0700607 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700608 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700609 while (start != NULL) {
610 if (i == MAX_PACKAGES) {
611 fprintf(stderr, "error: only 16 packages could be traced at once\n");
612 clearAppProperties();
613 return false;
614 }
615 char* end = strchr(start, ',');
616 if (end != NULL) {
617 *end = '\0';
618 end++;
619 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700620 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
621 if (!android::base::SetProperty(key, start)) {
622 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700623 clearAppProperties();
624 return false;
625 }
626 start = end;
627 i++;
628 }
629
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700630 std::string value = android::base::StringPrintf("%d", i);
631 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
632 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700633 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700634 return false;
635 }
636 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800637}
638
639// Disable all /sys/ enable files.
640static bool disableKernelTraceEvents() {
641 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700642 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800643 const TracingCategory &c = k_categories[i];
644 for (int j = 0; j < MAX_SYS_FILES; j++) {
645 const char* path = c.sysfiles[j].path;
646 if (path != NULL && fileIsWritable(path)) {
647 ok &= setKernelOptionEnable(path, false);
648 }
649 }
650 }
651 return ok;
652}
653
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700654// Verify that the comma separated list of functions are being traced by the
655// kernel.
656static bool verifyKernelTraceFuncs(const char* funcs)
657{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100658 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800659 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100660 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700661 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100662 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700663 }
664
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100665 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700666
667 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100668 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700669 bool ok = true;
670 char* myFuncs = strdup(funcs);
671 char* func = strtok(myFuncs, ",");
672 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100673 if (!strchr(func, '*')) {
674 String8 fancyFunc = String8::format("\n%s\n", func);
675 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
676 if (!found || func[0] == '\0') {
677 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
678 "to trace.\n", func);
679 ok = false;
680 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700681 }
682 func = strtok(NULL, ",");
683 }
684 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700685 return ok;
686}
687
688// Set the comma separated list of functions that the kernel is to trace.
689static bool setKernelTraceFuncs(const char* funcs)
690{
691 bool ok = true;
692
693 if (funcs == NULL || funcs[0] == '\0') {
694 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700695 if (fileIsWritable(k_currentTracerPath)) {
696 ok &= writeStr(k_currentTracerPath, "nop");
697 }
698 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700699 ok &= truncateFile(k_ftraceFilterPath);
700 }
701 } else {
702 // Enable kernel function tracing.
703 ok &= writeStr(k_currentTracerPath, "function_graph");
704 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
705 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
706 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
707 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
708
709 // Set the requested filter functions.
710 ok &= truncateFile(k_ftraceFilterPath);
711 char* myFuncs = strdup(funcs);
712 char* func = strtok(myFuncs, ",");
713 while (func) {
714 ok &= appendStr(k_ftraceFilterPath, func);
715 func = strtok(NULL, ",");
716 }
717 free(myFuncs);
718
719 // Verify that the set functions are being traced.
720 if (ok) {
721 ok &= verifyKernelTraceFuncs(funcs);
722 }
723 }
724
725 return ok;
726}
727
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900728static bool setCategoryEnable(const char* name, bool enable)
729{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700730 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900731 const TracingCategory& c = k_categories[i];
732 if (strcmp(name, c.name) == 0) {
733 if (isCategorySupported(c)) {
734 g_categoryEnables[i] = enable;
735 return true;
736 } else {
737 if (isCategorySupportedForRoot(c)) {
738 fprintf(stderr, "error: category \"%s\" requires root "
739 "privileges.\n", name);
740 } else {
741 fprintf(stderr, "error: category \"%s\" is not supported "
742 "on this device.\n", name);
743 }
744 return false;
745 }
746 }
747 }
748 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
749 return false;
750}
751
752static bool setCategoriesEnableFromFile(const char* categories_file)
753{
754 if (!categories_file) {
755 return true;
756 }
757 Tokenizer* tokenizer = NULL;
758 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
759 return false;
760 }
761 bool ok = true;
762 while (!tokenizer->isEol()) {
763 String8 token = tokenizer->nextToken(" ");
764 if (token.isEmpty()) {
765 tokenizer->skipDelimiters(" ");
766 continue;
767 }
768 ok &= setCategoryEnable(token.string(), true);
769 }
770 delete tokenizer;
771 return ok;
772}
773
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700774// Set all the kernel tracing settings to the desired state for this trace
775// capture.
776static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800777{
778 bool ok = true;
779
780 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900781 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800782 ok &= setTraceOverwriteEnable(g_traceOverwrite);
783 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
John Reckba54d5b2017-06-23 09:44:08 -0700784 // TODO: Re-enable after stabilization
785 //ok &= setCmdlineSize();
Carmen Jacksonea826792017-05-05 11:42:32 -0700786 ok &= setClock();
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700787 ok &= setPrintTgidEnableIfPresent(true);
788 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800789
790 // Set up the tags property.
791 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700792 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800793 if (g_categoryEnables[i]) {
794 const TracingCategory &c = k_categories[i];
795 tags |= c.tags;
796 }
797 }
798 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700799
800 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700801 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700802 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
803 coreServicesTagEnabled = g_categoryEnables[i];
804 }
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700805
806 // Set whether to poke PDX services in this session.
807 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
808 g_tracePdx = g_categoryEnables[i];
809 }
sergeyvdb404152016-05-02 19:26:07 -0700810 }
811
812 std::string packageList(g_debugAppCmdLine);
813 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700814 if (!packageList.empty()) {
815 packageList += ",";
816 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700817 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700818 }
Dan Austin09a79872016-05-31 13:27:03 -0700819 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700820 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100821 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800822
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700823 if (g_tracePdx) {
824 ok &= ServiceUtility::PokeServices();
825 }
826
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800827 // Disable all the sysfs enables. This is done as a separate loop from
828 // the enables to allow the same enable to exist in multiple categories.
829 ok &= disableKernelTraceEvents();
830
831 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700832 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800833 if (g_categoryEnables[i]) {
834 const TracingCategory &c = k_categories[i];
835 for (int j = 0; j < MAX_SYS_FILES; j++) {
836 const char* path = c.sysfiles[j].path;
837 bool required = c.sysfiles[j].required == REQ;
838 if (path != NULL) {
839 if (fileIsWritable(path)) {
840 ok &= setKernelOptionEnable(path, true);
841 } else if (required) {
842 fprintf(stderr, "error writing file %s\n", path);
843 ok = false;
844 }
845 }
846 }
847 }
848 }
849
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800850 return ok;
851}
852
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700853// Reset all the kernel tracing settings to their default state.
854static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800855{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800856 // Disable all tracing that we're able to.
857 disableKernelTraceEvents();
858
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700859 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800860 setTagsProperty(0);
sergeyv4144eff2016-04-28 11:40:04 -0700861 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700862 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800863
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700864 if (g_tracePdx) {
865 ServiceUtility::PokeServices();
866 }
867
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800868 // Set the options back to their defaults.
869 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700870 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700871 setPrintTgidEnableIfPresent(false);
872 setKernelTraceFuncs(NULL);
873}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800874
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700875
876// Enable tracing in the kernel.
877static bool startTrace()
878{
879 return setTracingEnabled(true);
880}
881
882// Disable tracing in the kernel.
883static void stopTrace()
884{
885 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800886}
887
Martijn Coenend9535872015-11-26 10:00:55 +0100888// Read data from the tracing pipe and forward to stdout
889static void streamTrace()
890{
891 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800892 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100893 if (traceFD == -1) {
894 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
895 strerror(errno), errno);
896 return;
897 }
898 while (!g_traceAborted) {
899 ssize_t bytes_read = read(traceFD, trace_data, 4096);
900 if (bytes_read > 0) {
901 write(STDOUT_FILENO, trace_data, bytes_read);
902 fflush(stdout);
903 } else {
904 if (!g_traceAborted) {
905 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
906 bytes_read, errno, strerror(errno));
907 }
908 break;
909 }
910 }
911}
912
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800913// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700914static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800915{
John Reck6c8ac922016-03-28 11:25:30 -0700916 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800917 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800918 if (traceFD == -1) {
919 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
920 strerror(errno), errno);
921 return;
922 }
923
924 if (g_compress) {
925 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800926 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700927
928 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800929 if (result != Z_OK) {
930 fprintf(stderr, "error initializing zlib: %d\n", result);
931 close(traceFD);
932 return;
933 }
934
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700935 constexpr size_t bufSize = 64*1024;
936 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
937 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
938 if (!in || !out) {
939 fprintf(stderr, "couldn't allocate buffers\n");
940 close(traceFD);
941 return;
942 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800943
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700944 int flush = Z_NO_FLUSH;
945
946 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800947 zs.avail_out = bufSize;
948
949 do {
950
951 if (zs.avail_in == 0) {
952 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700953 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800954 if (result < 0) {
955 fprintf(stderr, "error reading trace: %s (%d)\n",
956 strerror(errno), errno);
957 result = Z_STREAM_END;
958 break;
959 } else if (result == 0) {
960 flush = Z_FINISH;
961 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700962 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800963 zs.avail_in = result;
964 }
965 }
966
967 if (zs.avail_out == 0) {
968 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700969 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800970 if ((size_t)result < bufSize) {
971 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
972 strerror(errno), errno);
973 result = Z_STREAM_END; // skip deflate error message
974 zs.avail_out = bufSize; // skip the final write
975 break;
976 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700977 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800978 zs.avail_out = bufSize;
979 }
980
981 } while ((result = deflate(&zs, flush)) == Z_OK);
982
983 if (result != Z_STREAM_END) {
984 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
985 }
986
987 if (zs.avail_out < bufSize) {
988 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -0700989 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800990 if ((size_t)result < bytes) {
991 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
992 strerror(errno), errno);
993 }
994 }
995
996 result = deflateEnd(&zs);
997 if (result != Z_OK) {
998 fprintf(stderr, "error cleaning up zlib: %d\n", result);
999 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001000 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001001 char buf[4096];
1002 ssize_t rc;
1003 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1004 if (!android::base::WriteFully(outFd, buf, rc)) {
1005 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1006 break;
1007 }
1008 }
1009 if (rc == -1) {
1010 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001011 }
1012 }
1013
1014 close(traceFD);
1015}
1016
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001017static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001018{
1019 if (!g_nohup) {
1020 g_traceAborted = true;
1021 }
1022}
1023
1024static void registerSigHandler()
1025{
1026 struct sigaction sa;
1027 sigemptyset(&sa.sa_mask);
1028 sa.sa_flags = 0;
1029 sa.sa_handler = handleSignal;
1030 sigaction(SIGHUP, &sa, NULL);
1031 sigaction(SIGINT, &sa, NULL);
1032 sigaction(SIGQUIT, &sa, NULL);
1033 sigaction(SIGTERM, &sa, NULL);
1034}
1035
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001036static void listSupportedCategories()
1037{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001038 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001039 const TracingCategory& c = k_categories[i];
1040 if (isCategorySupported(c)) {
1041 printf(" %10s - %s\n", c.name, c.longname);
1042 }
1043 }
1044}
1045
1046// Print the command usage help to stderr.
1047static void showHelp(const char *cmd)
1048{
1049 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1050 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001051 " -a appname enable app-level tracing for a comma "
1052 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001053 " -b N use a trace buffer size of N KB\n"
1054 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001055 " -f filename use the categories written in a file as space-separated\n"
1056 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001057 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001058 " -n ignore signals\n"
1059 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001060 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001061 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001062 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001063 " --async_dump dump the current contents of circular trace buffer\n"
1064 " --async_stop stop tracing and dump the current contents of circular\n"
1065 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001066 " --stream stream trace to stdout as it enters the trace buffer\n"
1067 " Note: this can take significant CPU time, and is best\n"
1068 " used for measuring things that are not affected by\n"
1069 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001070 " --list_categories\n"
1071 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001072 " -o filename write the trace to the specified file instead\n"
1073 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001074 );
1075}
1076
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001077bool findTraceFiles()
1078{
1079 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1080 static const std::string tracefs_path = "/sys/kernel/tracing/";
1081 static const std::string trace_file = "trace_marker";
1082
1083 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1084 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1085
1086 if (!tracefs && !debugfs) {
1087 fprintf(stderr, "Error: Did not find trace folder\n");
1088 return false;
1089 }
1090
1091 if (tracefs) {
1092 g_traceFolder = tracefs_path;
1093 } else {
1094 g_traceFolder = debugfs_path;
1095 }
1096
1097 return true;
1098}
1099
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001100int main(int argc, char **argv)
1101{
1102 bool async = false;
1103 bool traceStart = true;
1104 bool traceStop = true;
1105 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001106 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001107
1108 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1109 showHelp(argv[0]);
1110 exit(0);
1111 }
1112
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001113 if (!findTraceFiles()) {
1114 fprintf(stderr, "No trace folder found\n");
1115 exit(-1);
1116 }
1117
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001118 for (;;) {
1119 int ret;
1120 int option_index = 0;
1121 static struct option long_options[] = {
1122 {"async_start", no_argument, 0, 0 },
1123 {"async_stop", no_argument, 0, 0 },
1124 {"async_dump", no_argument, 0, 0 },
1125 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +01001126 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001127 { 0, 0, 0, 0 }
1128 };
1129
John Reck40b26b42016-03-30 09:44:36 -07001130 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001131 long_options, &option_index);
1132
1133 if (ret < 0) {
1134 for (int i = optind; i < argc; i++) {
1135 if (!setCategoryEnable(argv[i], true)) {
1136 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1137 exit(1);
1138 }
1139 }
1140 break;
1141 }
1142
1143 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001144 case 'a':
1145 g_debugAppCmdLine = optarg;
1146 break;
1147
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001148 case 'b':
1149 g_traceBufferSizeKB = atoi(optarg);
1150 break;
1151
1152 case 'c':
1153 g_traceOverwrite = true;
1154 break;
1155
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001156 case 'f':
1157 g_categoriesFile = optarg;
1158 break;
1159
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001160 case 'k':
1161 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001162 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001163
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001164 case 'n':
1165 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001166 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001167
1168 case 's':
1169 g_initialSleepSecs = atoi(optarg);
1170 break;
1171
1172 case 't':
1173 g_traceDurationSeconds = atoi(optarg);
1174 break;
1175
1176 case 'z':
1177 g_compress = true;
1178 break;
1179
John Reck40b26b42016-03-30 09:44:36 -07001180 case 'o':
1181 g_outputFile = optarg;
1182 break;
1183
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001184 case 0:
1185 if (!strcmp(long_options[option_index].name, "async_start")) {
1186 async = true;
1187 traceStop = false;
1188 traceDump = false;
1189 g_traceOverwrite = true;
1190 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1191 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001192 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001193 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1194 async = true;
1195 traceStart = false;
1196 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001197 } else if (!strcmp(long_options[option_index].name, "stream")) {
1198 traceStream = true;
1199 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001200 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1201 listSupportedCategories();
1202 exit(0);
1203 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001204 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001205
1206 default:
1207 fprintf(stderr, "\n");
1208 showHelp(argv[0]);
1209 exit(-1);
1210 break;
1211 }
1212 }
1213
1214 registerSigHandler();
1215
1216 if (g_initialSleepSecs > 0) {
1217 sleep(g_initialSleepSecs);
1218 }
1219
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001220 bool ok = true;
1221 ok &= setUpTrace();
1222 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001223
1224 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001225 if (!traceStream) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001226 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001227 fflush(stdout);
1228 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001229
1230 // We clear the trace after starting it because tracing gets enabled for
1231 // each CPU individually in the kernel. Having the beginning of the trace
1232 // contain entries from only one CPU can cause "begin" entries without a
1233 // matching "end" entry to show up if a task gets migrated from one CPU to
1234 // another.
1235 ok = clearTrace();
1236
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001237 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001238 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001239 // Sleep to allow the trace to be captured.
1240 struct timespec timeLeft;
1241 timeLeft.tv_sec = g_traceDurationSeconds;
1242 timeLeft.tv_nsec = 0;
1243 do {
1244 if (g_traceAborted) {
1245 break;
1246 }
1247 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1248 }
Martijn Coenend9535872015-11-26 10:00:55 +01001249
1250 if (traceStream) {
1251 streamTrace();
1252 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001253 }
1254
1255 // Stop the trace and restore the default settings.
1256 if (traceStop)
1257 stopTrace();
1258
1259 if (ok && traceDump) {
1260 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001261 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001262 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001263 int outFd = STDOUT_FILENO;
1264 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001265 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001266 }
1267 if (outFd == -1) {
1268 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1269 } else {
1270 dprintf(outFd, "TRACE:\n");
1271 dumpTrace(outFd);
1272 if (g_outputFile) {
1273 close(outFd);
1274 }
1275 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001276 } else {
1277 printf("\ntrace aborted.\n");
1278 fflush(stdout);
1279 }
1280 clearTrace();
1281 } else if (!ok) {
1282 fprintf(stderr, "unable to start tracing\n");
1283 }
1284
1285 // Reset the trace buffer size to 1.
1286 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001287 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001288
1289 return g_traceAborted ? 1 : 0;
1290}