blob: 0bdca2d81d7861bd907f1d588ee45952cd9aafd1 [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 } },
Joel Fernandes0ad0f302017-08-31 08:35:05 -0700133 { "irqoff", "IRQ-disabled code section tracing", 0, {
134 { REQ, "events/preemptirq/irq_enable/enable" },
135 { REQ, "events/preemptirq/irq_disable/enable" },
136 } },
137 { "preemptoff", "Preempt-disabled code section tracing", 0, {
138 { REQ, "events/preemptirq/preempt_enable/enable" },
139 { REQ, "events/preemptirq/preempt_disable/enable" },
140 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100141 { "i2c", "I2C Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800142 { REQ, "events/i2c/enable" },
143 { REQ, "events/i2c/i2c_read/enable" },
144 { REQ, "events/i2c/i2c_write/enable" },
145 { REQ, "events/i2c/i2c_result/enable" },
146 { REQ, "events/i2c/i2c_reply/enable" },
147 { OPT, "events/i2c/smbus_read/enable" },
148 { OPT, "events/i2c/smbus_write/enable" },
149 { OPT, "events/i2c/smbus_result/enable" },
150 { OPT, "events/i2c/smbus_reply/enable" },
Michael Wright43fb6782016-08-18 19:56:43 +0100151 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700152 { "freq", "CPU Frequency", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800153 { REQ, "events/power/cpu_frequency/enable" },
154 { OPT, "events/power/clock_set_rate/enable" },
155 { OPT, "events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800156 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700157 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800158 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800159 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700160 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800161 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800162 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700163 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800164 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
165 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
166 { OPT, "events/f2fs/f2fs_write_begin/enable" },
167 { OPT, "events/f2fs/f2fs_write_end/enable" },
168 { OPT, "events/ext4/ext4_da_write_begin/enable" },
169 { OPT, "events/ext4/ext4_da_write_end/enable" },
170 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
171 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
172 { REQ, "events/block/block_rq_issue/enable" },
173 { REQ, "events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800174 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700175 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800176 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700177 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700178 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800179 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800180 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700181 { "sync", "Synchronization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800182 { REQ, "events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800183 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700184 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800185 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800186 } },
Colin Cross580407f2014-08-18 15:22:13 -0700187 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800188 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
189 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
190 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
191 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Marc Hittingerf1f62e32017-05-17 15:57:43 -0700192 { REQ, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700193 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800194 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800195 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800196 } },
Scott Bauerae473362015-06-08 16:32:36 -0700197 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800198 { REQ, "events/binder/binder_transaction/enable" },
199 { REQ, "events/binder/binder_transaction_received/enable" },
Martijn Coenen7f3d7a22017-05-26 09:50:55 -0700200 { OPT, "events/binder/binder_set_priority/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700201 } },
202 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800203 { OPT, "events/binder/binder_lock/enable" },
204 { OPT, "events/binder/binder_locked/enable" },
205 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700206 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200207 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800208 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200209 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800210};
211
212/* Command line options */
213static int g_traceDurationSeconds = 5;
214static bool g_traceOverwrite = false;
215static int g_traceBufferSizeKB = 2048;
216static bool g_compress = false;
217static bool g_nohup = false;
218static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900219static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700220static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700221static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700222static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800223
224/* Global state */
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700225static bool g_tracePdx = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800226static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700227static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800228static std::string g_traceFolder;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800229
230/* Sys file paths */
231static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800232 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800233
234static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800235 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800236
Joel Fernandesed80bd02017-06-02 10:19:28 -0700237static const char* k_traceCmdlineSizePath =
238 "saved_cmdlines_size";
239
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800240static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800241 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800242
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700243static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800244 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700245
246static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800247 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700248
249static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800250 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700251
252static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800253 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700254
255static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800256 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700257
258static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800259 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700260
261static const char* k_funcgraphDurationPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800262 "options/funcgraph-duration";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700263
264static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800265 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700266
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800267static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800268 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800269
270static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800271 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800272
Martijn Coenend9535872015-11-26 10:00:55 +0100273static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800274 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100275
John Reck469a1942015-03-26 15:31:35 -0700276static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800277 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700278
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800279// Check whether a file exists.
280static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800281 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800282}
283
284// Check whether a file is writable.
285static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800286 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800287}
288
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700289// Truncate a file.
290static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800291{
Jamie Gennis43122e72013-03-21 14:06:31 -0700292 // This uses creat rather than truncate because some of the debug kernel
293 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
294 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800295 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700296 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800297 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700298 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700299 return false;
300 }
301
Jamie Gennis43122e72013-03-21 14:06:31 -0700302 close(traceFD);
303
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700304 return true;
305}
306
307static bool _writeStr(const char* filename, const char* str, int flags)
308{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800309 std::string fullFilename = g_traceFolder + filename;
310 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800311 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800312 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800313 strerror(errno), errno);
314 return false;
315 }
316
317 bool ok = true;
318 ssize_t len = strlen(str);
319 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800320 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800321 strerror(errno), errno);
322 ok = false;
323 }
324
325 close(fd);
326
327 return ok;
328}
329
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700330// Write a string to a file, returning true if the write was successful.
331static bool writeStr(const char* filename, const char* str)
332{
333 return _writeStr(filename, str, O_WRONLY);
334}
335
336// Append a string to a file, returning true if the write was successful.
337static bool appendStr(const char* filename, const char* str)
338{
339 return _writeStr(filename, str, O_APPEND|O_WRONLY);
340}
341
John Reck469a1942015-03-26 15:31:35 -0700342static void writeClockSyncMarker()
343{
344 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200345 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800346 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200347 if (fd == -1) {
348 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
349 strerror(errno), errno);
350 return;
351 }
John Reck469a1942015-03-26 15:31:35 -0700352 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200353
354 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
355 if (write(fd, buffer, len) != len) {
356 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
357 }
358
359 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
360 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
361 if (write(fd, buffer, len) != len) {
362 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
363 }
364
365 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700366}
367
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800368// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
369// file.
370static bool setKernelOptionEnable(const char* filename, bool enable)
371{
372 return writeStr(filename, enable ? "1" : "0");
373}
374
375// Check whether the category is supported on the device with the current
376// rootness. A category is supported only if all its required /sys/ files are
377// writable and if enabling the category will enable one or more tracing tags
378// or /sys/ files.
379static bool isCategorySupported(const TracingCategory& category)
380{
sergeyvdb404152016-05-02 19:26:07 -0700381 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700382 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700383 }
384
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700385 if (strcmp(category.name, k_pdxServiceCategory) == 0) {
386 return true;
387 }
388
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800389 bool ok = category.tags != 0;
390 for (int i = 0; i < MAX_SYS_FILES; i++) {
391 const char* path = category.sysfiles[i].path;
392 bool req = category.sysfiles[i].required == REQ;
393 if (path != NULL) {
394 if (req) {
395 if (!fileIsWritable(path)) {
396 return false;
397 } else {
398 ok = true;
399 }
400 } else {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800401 ok = true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800402 }
403 }
404 }
405 return ok;
406}
407
408// Check whether the category would be supported on the device if the user
409// were root. This function assumes that root is able to write to any file
410// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700411// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800412static bool isCategorySupportedForRoot(const TracingCategory& category)
413{
414 bool ok = category.tags != 0;
415 for (int i = 0; i < MAX_SYS_FILES; i++) {
416 const char* path = category.sysfiles[i].path;
417 bool req = category.sysfiles[i].required == REQ;
418 if (path != NULL) {
419 if (req) {
420 if (!fileExists(path)) {
421 return false;
422 } else {
423 ok = true;
424 }
425 } else {
426 ok |= fileExists(path);
427 }
428 }
429 }
430 return ok;
431}
432
433// Enable or disable overwriting of the kernel trace buffers. Disabling this
434// will cause tracing to stop once the trace buffers have filled up.
435static bool setTraceOverwriteEnable(bool enable)
436{
437 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
438}
439
440// Enable or disable kernel tracing.
441static bool setTracingEnabled(bool enable)
442{
443 return setKernelOptionEnable(k_tracingOnPath, enable);
444}
445
446// Clear the contents of the kernel trace.
447static bool clearTrace()
448{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700449 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800450}
451
452// Set the size of the kernel's trace buffer in kilobytes.
453static bool setTraceBufferSizeKB(int size)
454{
455 char str[32] = "1";
456 int len;
457 if (size < 1) {
458 size = 1;
459 }
460 snprintf(str, 32, "%d", size);
461 return writeStr(k_traceBufferSizePath, str);
462}
463
Joel Fernandesed80bd02017-06-02 10:19:28 -0700464// Set the default size of cmdline hashtable
465static bool setCmdlineSize()
466{
Joel Fernandesce964f22017-06-06 12:20:29 -0700467 if (fileExists(k_traceCmdlineSizePath)) {
468 return writeStr(k_traceCmdlineSizePath, "8192");
469 }
470 return true;
Joel Fernandesed80bd02017-06-02 10:19:28 -0700471}
472
Carmen Jacksonea826792017-05-05 11:42:32 -0700473// Set the clock to the best available option while tracing. Use 'boot' if it's
474// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700475// Any write to the trace_clock sysfs file will reset the buffer, so only
476// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700477static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800478{
Carmen Jacksonea826792017-05-05 11:42:32 -0700479 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
480 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
481 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700482
Carmen Jacksonea826792017-05-05 11:42:32 -0700483 std::string newClock;
484 if (clockStr.find("boot") != std::string::npos) {
485 newClock = "boot";
486 } else if (clockStr.find("mono") != std::string::npos) {
487 newClock = "mono";
488 } else {
489 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700490 }
491
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700492 size_t begin = clockStr.find('[') + 1;
493 size_t end = clockStr.find(']');
Carmen Jacksonea826792017-05-05 11:42:32 -0700494 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
495 return true;
496 }
497 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800498}
499
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700500static bool setPrintTgidEnableIfPresent(bool enable)
501{
502 if (fileExists(k_printTgidPath)) {
503 return setKernelOptionEnable(k_printTgidPath, enable);
504 }
505 return true;
506}
507
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800508// Poke all the binder-enabled processes in the system to get them to re-read
509// their system properties.
510static bool pokeBinderServices()
511{
512 sp<IServiceManager> sm = defaultServiceManager();
513 Vector<String16> services = sm->listServices();
514 for (size_t i = 0; i < services.size(); i++) {
515 sp<IBinder> obj = sm->checkService(services[i]);
516 if (obj != NULL) {
517 Parcel data;
518 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
519 NULL, 0) != OK) {
520 if (false) {
521 // XXX: For some reason this fails on tablets trying to
522 // poke the "phone" service. It's not clear whether some
523 // are expected to fail.
524 String8 svc(services[i]);
525 fprintf(stderr, "error poking binder service %s\n",
526 svc.string());
527 return false;
528 }
529 }
530 }
531 }
532 return true;
533}
534
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100535// Poke all the HAL processes in the system to get them to re-read
536// their system properties.
537static void pokeHalServices()
538{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100539 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100540 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100541 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100542 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100543
544 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800545
546 if (sm == nullptr) {
547 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
548 return;
549 }
550
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800551 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100552 for (size_t i = 0; i < interfaces.size(); i++) {
553 string fqInstanceName = interfaces[i];
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700554 string::size_type n = fqInstanceName.find('/');
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100555 if (n == std::string::npos || interfaces[i].size() == n+1)
556 continue;
557 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
558 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100559 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
560 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100561 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100562 continue;
563 }
Carmen Jackson73206122017-04-18 15:37:57 -0700564
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100565 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700566 if (interface == nullptr) {
567 // ignore
568 continue;
569 }
570
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100571 auto notifyRet = interface->notifySyspropsChanged();
572 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100573 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800574 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100575 }
576 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800577 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100578 // TODO(b/34242478) fix this when we determine the correct ACL
579 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800580 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100581}
582
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800583// Set the trace tags that userland tracing uses, and poke the running
584// processes to pick up the new value.
585static bool setTagsProperty(uint64_t tags)
586{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700587 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
588 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800589 fprintf(stderr, "error setting trace tags system property\n");
590 return false;
591 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700592 return true;
593}
594
sergeyv4144eff2016-04-28 11:40:04 -0700595static void clearAppProperties()
596{
sergeyv4144eff2016-04-28 11:40:04 -0700597 for (int i = 0; i < MAX_PACKAGES; i++) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700598 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
599 if (!android::base::SetProperty(key, "")) {
600 fprintf(stderr, "failed to clear system property: %s\n", key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700601 }
602 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700603 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700604 fprintf(stderr, "failed to clear system property: %s",
605 k_traceAppsNumberProperty);
606 }
607}
608
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700609// Set the system property that indicates which apps should perform
610// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700611static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700612{
sergeyv4144eff2016-04-28 11:40:04 -0700613 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700614 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700615 while (start != NULL) {
616 if (i == MAX_PACKAGES) {
617 fprintf(stderr, "error: only 16 packages could be traced at once\n");
618 clearAppProperties();
619 return false;
620 }
621 char* end = strchr(start, ',');
622 if (end != NULL) {
623 *end = '\0';
624 end++;
625 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700626 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
627 if (!android::base::SetProperty(key, start)) {
628 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700629 clearAppProperties();
630 return false;
631 }
632 start = end;
633 i++;
634 }
635
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700636 std::string value = android::base::StringPrintf("%d", i);
637 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
638 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700639 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700640 return false;
641 }
642 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800643}
644
645// Disable all /sys/ enable files.
646static bool disableKernelTraceEvents() {
647 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700648 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800649 const TracingCategory &c = k_categories[i];
650 for (int j = 0; j < MAX_SYS_FILES; j++) {
651 const char* path = c.sysfiles[j].path;
652 if (path != NULL && fileIsWritable(path)) {
653 ok &= setKernelOptionEnable(path, false);
654 }
655 }
656 }
657 return ok;
658}
659
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700660// Verify that the comma separated list of functions are being traced by the
661// kernel.
662static bool verifyKernelTraceFuncs(const char* funcs)
663{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100664 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800665 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100666 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700667 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100668 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700669 }
670
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100671 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700672
673 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100674 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700675 bool ok = true;
676 char* myFuncs = strdup(funcs);
677 char* func = strtok(myFuncs, ",");
678 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100679 if (!strchr(func, '*')) {
680 String8 fancyFunc = String8::format("\n%s\n", func);
681 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
682 if (!found || func[0] == '\0') {
683 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
684 "to trace.\n", func);
685 ok = false;
686 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700687 }
688 func = strtok(NULL, ",");
689 }
690 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700691 return ok;
692}
693
694// Set the comma separated list of functions that the kernel is to trace.
695static bool setKernelTraceFuncs(const char* funcs)
696{
697 bool ok = true;
698
699 if (funcs == NULL || funcs[0] == '\0') {
700 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700701 if (fileIsWritable(k_currentTracerPath)) {
702 ok &= writeStr(k_currentTracerPath, "nop");
703 }
704 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700705 ok &= truncateFile(k_ftraceFilterPath);
706 }
707 } else {
708 // Enable kernel function tracing.
709 ok &= writeStr(k_currentTracerPath, "function_graph");
710 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
711 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
712 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
713 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
714
715 // Set the requested filter functions.
716 ok &= truncateFile(k_ftraceFilterPath);
717 char* myFuncs = strdup(funcs);
718 char* func = strtok(myFuncs, ",");
719 while (func) {
720 ok &= appendStr(k_ftraceFilterPath, func);
721 func = strtok(NULL, ",");
722 }
723 free(myFuncs);
724
725 // Verify that the set functions are being traced.
726 if (ok) {
727 ok &= verifyKernelTraceFuncs(funcs);
728 }
729 }
730
731 return ok;
732}
733
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900734static bool setCategoryEnable(const char* name, bool enable)
735{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700736 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900737 const TracingCategory& c = k_categories[i];
738 if (strcmp(name, c.name) == 0) {
739 if (isCategorySupported(c)) {
740 g_categoryEnables[i] = enable;
741 return true;
742 } else {
743 if (isCategorySupportedForRoot(c)) {
744 fprintf(stderr, "error: category \"%s\" requires root "
745 "privileges.\n", name);
746 } else {
747 fprintf(stderr, "error: category \"%s\" is not supported "
748 "on this device.\n", name);
749 }
750 return false;
751 }
752 }
753 }
754 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
755 return false;
756}
757
758static bool setCategoriesEnableFromFile(const char* categories_file)
759{
760 if (!categories_file) {
761 return true;
762 }
763 Tokenizer* tokenizer = NULL;
764 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
765 return false;
766 }
767 bool ok = true;
768 while (!tokenizer->isEol()) {
769 String8 token = tokenizer->nextToken(" ");
770 if (token.isEmpty()) {
771 tokenizer->skipDelimiters(" ");
772 continue;
773 }
774 ok &= setCategoryEnable(token.string(), true);
775 }
776 delete tokenizer;
777 return ok;
778}
779
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700780// Set all the kernel tracing settings to the desired state for this trace
781// capture.
782static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800783{
784 bool ok = true;
785
786 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900787 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800788 ok &= setTraceOverwriteEnable(g_traceOverwrite);
789 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
John Reckba54d5b2017-06-23 09:44:08 -0700790 // TODO: Re-enable after stabilization
791 //ok &= setCmdlineSize();
Carmen Jacksonea826792017-05-05 11:42:32 -0700792 ok &= setClock();
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700793 ok &= setPrintTgidEnableIfPresent(true);
794 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800795
796 // Set up the tags property.
797 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700798 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800799 if (g_categoryEnables[i]) {
800 const TracingCategory &c = k_categories[i];
801 tags |= c.tags;
802 }
803 }
804 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700805
806 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700807 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700808 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
809 coreServicesTagEnabled = g_categoryEnables[i];
810 }
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700811
812 // Set whether to poke PDX services in this session.
813 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
814 g_tracePdx = g_categoryEnables[i];
815 }
sergeyvdb404152016-05-02 19:26:07 -0700816 }
817
818 std::string packageList(g_debugAppCmdLine);
819 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700820 if (!packageList.empty()) {
821 packageList += ",";
822 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700823 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700824 }
Dan Austin09a79872016-05-31 13:27:03 -0700825 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700826 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100827 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800828
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700829 if (g_tracePdx) {
830 ok &= ServiceUtility::PokeServices();
831 }
832
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800833 // Disable all the sysfs enables. This is done as a separate loop from
834 // the enables to allow the same enable to exist in multiple categories.
835 ok &= disableKernelTraceEvents();
836
837 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700838 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800839 if (g_categoryEnables[i]) {
840 const TracingCategory &c = k_categories[i];
841 for (int j = 0; j < MAX_SYS_FILES; j++) {
842 const char* path = c.sysfiles[j].path;
843 bool required = c.sysfiles[j].required == REQ;
844 if (path != NULL) {
845 if (fileIsWritable(path)) {
846 ok &= setKernelOptionEnable(path, true);
847 } else if (required) {
848 fprintf(stderr, "error writing file %s\n", path);
849 ok = false;
850 }
851 }
852 }
853 }
854 }
855
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800856 return ok;
857}
858
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700859// Reset all the kernel tracing settings to their default state.
860static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800861{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800862 // Disable all tracing that we're able to.
863 disableKernelTraceEvents();
864
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700865 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800866 setTagsProperty(0);
sergeyv4144eff2016-04-28 11:40:04 -0700867 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700868 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800869
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700870 if (g_tracePdx) {
871 ServiceUtility::PokeServices();
872 }
873
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800874 // Set the options back to their defaults.
875 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700876 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700877 setPrintTgidEnableIfPresent(false);
878 setKernelTraceFuncs(NULL);
879}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800880
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700881
882// Enable tracing in the kernel.
883static bool startTrace()
884{
885 return setTracingEnabled(true);
886}
887
888// Disable tracing in the kernel.
889static void stopTrace()
890{
891 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800892}
893
Martijn Coenend9535872015-11-26 10:00:55 +0100894// Read data from the tracing pipe and forward to stdout
895static void streamTrace()
896{
897 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800898 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100899 if (traceFD == -1) {
900 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
901 strerror(errno), errno);
902 return;
903 }
904 while (!g_traceAborted) {
905 ssize_t bytes_read = read(traceFD, trace_data, 4096);
906 if (bytes_read > 0) {
907 write(STDOUT_FILENO, trace_data, bytes_read);
908 fflush(stdout);
909 } else {
910 if (!g_traceAborted) {
911 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
912 bytes_read, errno, strerror(errno));
913 }
914 break;
915 }
916 }
917}
918
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800919// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700920static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800921{
John Reck6c8ac922016-03-28 11:25:30 -0700922 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800923 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800924 if (traceFD == -1) {
925 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
926 strerror(errno), errno);
927 return;
928 }
929
930 if (g_compress) {
931 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800932 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700933
934 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800935 if (result != Z_OK) {
936 fprintf(stderr, "error initializing zlib: %d\n", result);
937 close(traceFD);
938 return;
939 }
940
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700941 constexpr size_t bufSize = 64*1024;
942 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
943 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
944 if (!in || !out) {
945 fprintf(stderr, "couldn't allocate buffers\n");
946 close(traceFD);
947 return;
948 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800949
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700950 int flush = Z_NO_FLUSH;
951
952 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800953 zs.avail_out = bufSize;
954
955 do {
956
957 if (zs.avail_in == 0) {
958 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700959 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800960 if (result < 0) {
961 fprintf(stderr, "error reading trace: %s (%d)\n",
962 strerror(errno), errno);
963 result = Z_STREAM_END;
964 break;
965 } else if (result == 0) {
966 flush = Z_FINISH;
967 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700968 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800969 zs.avail_in = result;
970 }
971 }
972
973 if (zs.avail_out == 0) {
974 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700975 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800976 if ((size_t)result < bufSize) {
977 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
978 strerror(errno), errno);
979 result = Z_STREAM_END; // skip deflate error message
980 zs.avail_out = bufSize; // skip the final write
981 break;
982 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700983 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800984 zs.avail_out = bufSize;
985 }
986
987 } while ((result = deflate(&zs, flush)) == Z_OK);
988
989 if (result != Z_STREAM_END) {
990 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
991 }
992
993 if (zs.avail_out < bufSize) {
994 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -0700995 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800996 if ((size_t)result < bytes) {
997 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
998 strerror(errno), errno);
999 }
1000 }
1001
1002 result = deflateEnd(&zs);
1003 if (result != Z_OK) {
1004 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1005 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001006 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001007 char buf[4096];
1008 ssize_t rc;
1009 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1010 if (!android::base::WriteFully(outFd, buf, rc)) {
1011 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1012 break;
1013 }
1014 }
1015 if (rc == -1) {
1016 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001017 }
1018 }
1019
1020 close(traceFD);
1021}
1022
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001023static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001024{
1025 if (!g_nohup) {
1026 g_traceAborted = true;
1027 }
1028}
1029
1030static void registerSigHandler()
1031{
1032 struct sigaction sa;
1033 sigemptyset(&sa.sa_mask);
1034 sa.sa_flags = 0;
1035 sa.sa_handler = handleSignal;
1036 sigaction(SIGHUP, &sa, NULL);
1037 sigaction(SIGINT, &sa, NULL);
1038 sigaction(SIGQUIT, &sa, NULL);
1039 sigaction(SIGTERM, &sa, NULL);
1040}
1041
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001042static void listSupportedCategories()
1043{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001044 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001045 const TracingCategory& c = k_categories[i];
1046 if (isCategorySupported(c)) {
1047 printf(" %10s - %s\n", c.name, c.longname);
1048 }
1049 }
1050}
1051
1052// Print the command usage help to stderr.
1053static void showHelp(const char *cmd)
1054{
1055 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1056 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001057 " -a appname enable app-level tracing for a comma "
1058 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001059 " -b N use a trace buffer size of N KB\n"
1060 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001061 " -f filename use the categories written in a file as space-separated\n"
1062 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001063 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001064 " -n ignore signals\n"
1065 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001066 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001067 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001068 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001069 " --async_dump dump the current contents of circular trace buffer\n"
1070 " --async_stop stop tracing and dump the current contents of circular\n"
1071 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001072 " --stream stream trace to stdout as it enters the trace buffer\n"
1073 " Note: this can take significant CPU time, and is best\n"
1074 " used for measuring things that are not affected by\n"
1075 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001076 " --list_categories\n"
1077 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001078 " -o filename write the trace to the specified file instead\n"
1079 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001080 );
1081}
1082
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001083bool findTraceFiles()
1084{
1085 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1086 static const std::string tracefs_path = "/sys/kernel/tracing/";
1087 static const std::string trace_file = "trace_marker";
1088
1089 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1090 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1091
1092 if (!tracefs && !debugfs) {
1093 fprintf(stderr, "Error: Did not find trace folder\n");
1094 return false;
1095 }
1096
1097 if (tracefs) {
1098 g_traceFolder = tracefs_path;
1099 } else {
1100 g_traceFolder = debugfs_path;
1101 }
1102
1103 return true;
1104}
1105
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001106int main(int argc, char **argv)
1107{
1108 bool async = false;
1109 bool traceStart = true;
1110 bool traceStop = true;
1111 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001112 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001113
1114 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1115 showHelp(argv[0]);
1116 exit(0);
1117 }
1118
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001119 if (!findTraceFiles()) {
1120 fprintf(stderr, "No trace folder found\n");
1121 exit(-1);
1122 }
1123
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001124 for (;;) {
1125 int ret;
1126 int option_index = 0;
1127 static struct option long_options[] = {
1128 {"async_start", no_argument, 0, 0 },
1129 {"async_stop", no_argument, 0, 0 },
1130 {"async_dump", no_argument, 0, 0 },
1131 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +01001132 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001133 { 0, 0, 0, 0 }
1134 };
1135
John Reck40b26b42016-03-30 09:44:36 -07001136 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001137 long_options, &option_index);
1138
1139 if (ret < 0) {
1140 for (int i = optind; i < argc; i++) {
1141 if (!setCategoryEnable(argv[i], true)) {
1142 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1143 exit(1);
1144 }
1145 }
1146 break;
1147 }
1148
1149 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001150 case 'a':
1151 g_debugAppCmdLine = optarg;
1152 break;
1153
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001154 case 'b':
1155 g_traceBufferSizeKB = atoi(optarg);
1156 break;
1157
1158 case 'c':
1159 g_traceOverwrite = true;
1160 break;
1161
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001162 case 'f':
1163 g_categoriesFile = optarg;
1164 break;
1165
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001166 case 'k':
1167 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001168 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001169
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001170 case 'n':
1171 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001172 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001173
1174 case 's':
1175 g_initialSleepSecs = atoi(optarg);
1176 break;
1177
1178 case 't':
1179 g_traceDurationSeconds = atoi(optarg);
1180 break;
1181
1182 case 'z':
1183 g_compress = true;
1184 break;
1185
John Reck40b26b42016-03-30 09:44:36 -07001186 case 'o':
1187 g_outputFile = optarg;
1188 break;
1189
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001190 case 0:
1191 if (!strcmp(long_options[option_index].name, "async_start")) {
1192 async = true;
1193 traceStop = false;
1194 traceDump = false;
1195 g_traceOverwrite = true;
1196 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1197 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001198 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001199 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1200 async = true;
1201 traceStart = false;
1202 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001203 } else if (!strcmp(long_options[option_index].name, "stream")) {
1204 traceStream = true;
1205 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001206 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1207 listSupportedCategories();
1208 exit(0);
1209 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001210 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001211
1212 default:
1213 fprintf(stderr, "\n");
1214 showHelp(argv[0]);
1215 exit(-1);
1216 break;
1217 }
1218 }
1219
1220 registerSigHandler();
1221
1222 if (g_initialSleepSecs > 0) {
1223 sleep(g_initialSleepSecs);
1224 }
1225
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001226 bool ok = true;
1227 ok &= setUpTrace();
1228 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001229
1230 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001231 if (!traceStream) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001232 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001233 fflush(stdout);
1234 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001235
1236 // We clear the trace after starting it because tracing gets enabled for
1237 // each CPU individually in the kernel. Having the beginning of the trace
1238 // contain entries from only one CPU can cause "begin" entries without a
1239 // matching "end" entry to show up if a task gets migrated from one CPU to
1240 // another.
1241 ok = clearTrace();
1242
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001243 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001244 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001245 // Sleep to allow the trace to be captured.
1246 struct timespec timeLeft;
1247 timeLeft.tv_sec = g_traceDurationSeconds;
1248 timeLeft.tv_nsec = 0;
1249 do {
1250 if (g_traceAborted) {
1251 break;
1252 }
1253 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1254 }
Martijn Coenend9535872015-11-26 10:00:55 +01001255
1256 if (traceStream) {
1257 streamTrace();
1258 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001259 }
1260
1261 // Stop the trace and restore the default settings.
1262 if (traceStop)
1263 stopTrace();
1264
1265 if (ok && traceDump) {
1266 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001267 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001268 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001269 int outFd = STDOUT_FILENO;
1270 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001271 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001272 }
1273 if (outFd == -1) {
1274 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1275 } else {
1276 dprintf(outFd, "TRACE:\n");
1277 dumpTrace(outFd);
1278 if (g_outputFile) {
1279 close(outFd);
1280 }
1281 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001282 } else {
1283 printf("\ntrace aborted.\n");
1284 fflush(stdout);
1285 }
1286 clearTrace();
1287 } else if (!ok) {
1288 fprintf(stderr, "unable to start tracing\n");
1289 }
1290
1291 // Reset the trace buffer size to 1.
1292 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001293 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001294
1295 return g_traceAborted ? 1 : 0;
1296}