blob: 1b9057977c1966523818b0a53dd4304a264f5b65 [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" },
Kevin DuBoisafc2f972017-11-03 15:44:08 -0700155 { OPT, "events/power/clock_disable/enable" },
156 { OPT, "events/power/clock_enable/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800157 { OPT, "events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800158 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700159 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800160 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800161 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700162 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800163 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800164 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700165 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800166 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
167 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
168 { OPT, "events/f2fs/f2fs_write_begin/enable" },
169 { OPT, "events/f2fs/f2fs_write_end/enable" },
170 { OPT, "events/ext4/ext4_da_write_begin/enable" },
171 { OPT, "events/ext4/ext4_da_write_end/enable" },
172 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
173 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
174 { REQ, "events/block/block_rq_issue/enable" },
175 { REQ, "events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800176 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700177 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800178 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700179 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700180 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800181 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800182 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700183 { "sync", "Synchronization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800184 { REQ, "events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800185 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700186 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800187 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800188 } },
Colin Cross580407f2014-08-18 15:22:13 -0700189 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800190 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
191 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
192 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
193 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Marc Hittingerf1f62e32017-05-17 15:57:43 -0700194 { REQ, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700195 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800196 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800197 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800198 } },
Scott Bauerae473362015-06-08 16:32:36 -0700199 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800200 { REQ, "events/binder/binder_transaction/enable" },
201 { REQ, "events/binder/binder_transaction_received/enable" },
Martijn Coenen7f3d7a22017-05-26 09:50:55 -0700202 { OPT, "events/binder/binder_set_priority/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700203 } },
204 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800205 { OPT, "events/binder/binder_lock/enable" },
206 { OPT, "events/binder/binder_locked/enable" },
207 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700208 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200209 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800210 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200211 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800212};
213
214/* Command line options */
215static int g_traceDurationSeconds = 5;
216static bool g_traceOverwrite = false;
217static int g_traceBufferSizeKB = 2048;
218static bool g_compress = false;
219static bool g_nohup = false;
220static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900221static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700222static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700223static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700224static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800225
226/* Global state */
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700227static bool g_tracePdx = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800228static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700229static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800230static std::string g_traceFolder;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800231
232/* Sys file paths */
233static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800234 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800235
236static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800237 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800238
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700239#if 0
240// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700241static const char* k_traceCmdlineSizePath =
242 "saved_cmdlines_size";
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700243#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700244
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800245static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800246 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800247
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700248static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800249 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700250
251static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800252 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700253
254static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800255 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700256
257static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800258 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700259
260static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800261 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700262
263static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800264 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700265
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700266static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800267 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700268
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800269static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800270 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800271
272static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800273 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800274
Martijn Coenend9535872015-11-26 10:00:55 +0100275static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800276 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100277
John Reck469a1942015-03-26 15:31:35 -0700278static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800279 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700280
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800281// Check whether a file exists.
282static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800283 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800284}
285
286// Check whether a file is writable.
287static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800288 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800289}
290
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700291// Truncate a file.
292static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800293{
Jamie Gennis43122e72013-03-21 14:06:31 -0700294 // This uses creat rather than truncate because some of the debug kernel
295 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
296 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800297 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700298 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800299 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700300 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700301 return false;
302 }
303
Jamie Gennis43122e72013-03-21 14:06:31 -0700304 close(traceFD);
305
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700306 return true;
307}
308
309static bool _writeStr(const char* filename, const char* str, int flags)
310{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800311 std::string fullFilename = g_traceFolder + filename;
312 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800313 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800314 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800315 strerror(errno), errno);
316 return false;
317 }
318
319 bool ok = true;
320 ssize_t len = strlen(str);
321 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800322 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800323 strerror(errno), errno);
324 ok = false;
325 }
326
327 close(fd);
328
329 return ok;
330}
331
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700332// Write a string to a file, returning true if the write was successful.
333static bool writeStr(const char* filename, const char* str)
334{
335 return _writeStr(filename, str, O_WRONLY);
336}
337
338// Append a string to a file, returning true if the write was successful.
339static bool appendStr(const char* filename, const char* str)
340{
341 return _writeStr(filename, str, O_APPEND|O_WRONLY);
342}
343
John Reck469a1942015-03-26 15:31:35 -0700344static void writeClockSyncMarker()
345{
346 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200347 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800348 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200349 if (fd == -1) {
350 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
351 strerror(errno), errno);
352 return;
353 }
John Reck469a1942015-03-26 15:31:35 -0700354 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200355
356 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
357 if (write(fd, buffer, len) != len) {
358 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
359 }
360
361 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
362 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
363 if (write(fd, buffer, len) != len) {
364 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
365 }
366
367 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700368}
369
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800370// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
371// file.
372static bool setKernelOptionEnable(const char* filename, bool enable)
373{
374 return writeStr(filename, enable ? "1" : "0");
375}
376
377// Check whether the category is supported on the device with the current
378// rootness. A category is supported only if all its required /sys/ files are
379// writable and if enabling the category will enable one or more tracing tags
380// or /sys/ files.
381static bool isCategorySupported(const TracingCategory& category)
382{
sergeyvdb404152016-05-02 19:26:07 -0700383 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700384 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700385 }
386
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700387 if (strcmp(category.name, k_pdxServiceCategory) == 0) {
388 return true;
389 }
390
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800391 bool ok = category.tags != 0;
392 for (int i = 0; i < MAX_SYS_FILES; i++) {
393 const char* path = category.sysfiles[i].path;
394 bool req = category.sysfiles[i].required == REQ;
395 if (path != NULL) {
396 if (req) {
397 if (!fileIsWritable(path)) {
398 return false;
399 } else {
400 ok = true;
401 }
402 } else {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800403 ok = true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800404 }
405 }
406 }
407 return ok;
408}
409
410// Check whether the category would be supported on the device if the user
411// were root. This function assumes that root is able to write to any file
412// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700413// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800414static bool isCategorySupportedForRoot(const TracingCategory& category)
415{
416 bool ok = category.tags != 0;
417 for (int i = 0; i < MAX_SYS_FILES; i++) {
418 const char* path = category.sysfiles[i].path;
419 bool req = category.sysfiles[i].required == REQ;
420 if (path != NULL) {
421 if (req) {
422 if (!fileExists(path)) {
423 return false;
424 } else {
425 ok = true;
426 }
427 } else {
428 ok |= fileExists(path);
429 }
430 }
431 }
432 return ok;
433}
434
435// Enable or disable overwriting of the kernel trace buffers. Disabling this
436// will cause tracing to stop once the trace buffers have filled up.
437static bool setTraceOverwriteEnable(bool enable)
438{
439 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
440}
441
442// Enable or disable kernel tracing.
443static bool setTracingEnabled(bool enable)
444{
445 return setKernelOptionEnable(k_tracingOnPath, enable);
446}
447
448// Clear the contents of the kernel trace.
449static bool clearTrace()
450{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700451 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800452}
453
454// Set the size of the kernel's trace buffer in kilobytes.
455static bool setTraceBufferSizeKB(int size)
456{
457 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800458 if (size < 1) {
459 size = 1;
460 }
461 snprintf(str, 32, "%d", size);
462 return writeStr(k_traceBufferSizePath, str);
463}
464
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700465#if 0
466// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700467// Set the default size of cmdline hashtable
468static bool setCmdlineSize()
469{
Joel Fernandesce964f22017-06-06 12:20:29 -0700470 if (fileExists(k_traceCmdlineSizePath)) {
471 return writeStr(k_traceCmdlineSizePath, "8192");
472 }
473 return true;
Joel Fernandesed80bd02017-06-02 10:19:28 -0700474}
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700475#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700476
Carmen Jacksonea826792017-05-05 11:42:32 -0700477// Set the clock to the best available option while tracing. Use 'boot' if it's
478// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700479// Any write to the trace_clock sysfs file will reset the buffer, so only
480// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700481static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800482{
Carmen Jacksonea826792017-05-05 11:42:32 -0700483 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
484 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
485 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700486
Carmen Jacksonea826792017-05-05 11:42:32 -0700487 std::string newClock;
488 if (clockStr.find("boot") != std::string::npos) {
489 newClock = "boot";
490 } else if (clockStr.find("mono") != std::string::npos) {
491 newClock = "mono";
492 } else {
493 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700494 }
495
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700496 size_t begin = clockStr.find('[') + 1;
497 size_t end = clockStr.find(']');
Carmen Jacksonea826792017-05-05 11:42:32 -0700498 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
499 return true;
500 }
501 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800502}
503
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700504static bool setPrintTgidEnableIfPresent(bool enable)
505{
506 if (fileExists(k_printTgidPath)) {
507 return setKernelOptionEnable(k_printTgidPath, enable);
508 }
509 return true;
510}
511
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800512// Poke all the binder-enabled processes in the system to get them to re-read
513// their system properties.
514static bool pokeBinderServices()
515{
516 sp<IServiceManager> sm = defaultServiceManager();
517 Vector<String16> services = sm->listServices();
518 for (size_t i = 0; i < services.size(); i++) {
519 sp<IBinder> obj = sm->checkService(services[i]);
520 if (obj != NULL) {
521 Parcel data;
522 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
523 NULL, 0) != OK) {
524 if (false) {
525 // XXX: For some reason this fails on tablets trying to
526 // poke the "phone" service. It's not clear whether some
527 // are expected to fail.
528 String8 svc(services[i]);
529 fprintf(stderr, "error poking binder service %s\n",
530 svc.string());
531 return false;
532 }
533 }
534 }
535 }
536 return true;
537}
538
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100539// Poke all the HAL processes in the system to get them to re-read
540// their system properties.
541static void pokeHalServices()
542{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100543 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100544 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100545 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100546 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100547
548 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800549
550 if (sm == nullptr) {
551 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
552 return;
553 }
554
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800555 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100556 for (size_t i = 0; i < interfaces.size(); i++) {
557 string fqInstanceName = interfaces[i];
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700558 string::size_type n = fqInstanceName.find('/');
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100559 if (n == std::string::npos || interfaces[i].size() == n+1)
560 continue;
561 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
562 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100563 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
564 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100565 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100566 continue;
567 }
Carmen Jackson73206122017-04-18 15:37:57 -0700568
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100569 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700570 if (interface == nullptr) {
571 // ignore
572 continue;
573 }
574
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100575 auto notifyRet = interface->notifySyspropsChanged();
576 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100577 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800578 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100579 }
580 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800581 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100582 // TODO(b/34242478) fix this when we determine the correct ACL
583 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800584 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100585}
586
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800587// Set the trace tags that userland tracing uses, and poke the running
588// processes to pick up the new value.
589static bool setTagsProperty(uint64_t tags)
590{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700591 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
592 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800593 fprintf(stderr, "error setting trace tags system property\n");
594 return false;
595 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700596 return true;
597}
598
sergeyv4144eff2016-04-28 11:40:04 -0700599static void clearAppProperties()
600{
sergeyv4144eff2016-04-28 11:40:04 -0700601 for (int i = 0; i < MAX_PACKAGES; i++) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700602 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
603 if (!android::base::SetProperty(key, "")) {
604 fprintf(stderr, "failed to clear system property: %s\n", key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700605 }
606 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700607 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700608 fprintf(stderr, "failed to clear system property: %s",
609 k_traceAppsNumberProperty);
610 }
611}
612
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700613// Set the system property that indicates which apps should perform
614// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700615static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700616{
sergeyv4144eff2016-04-28 11:40:04 -0700617 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700618 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700619 while (start != NULL) {
620 if (i == MAX_PACKAGES) {
621 fprintf(stderr, "error: only 16 packages could be traced at once\n");
622 clearAppProperties();
623 return false;
624 }
625 char* end = strchr(start, ',');
626 if (end != NULL) {
627 *end = '\0';
628 end++;
629 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700630 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
631 if (!android::base::SetProperty(key, start)) {
632 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700633 clearAppProperties();
634 return false;
635 }
636 start = end;
637 i++;
638 }
639
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700640 std::string value = android::base::StringPrintf("%d", i);
641 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
642 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700643 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700644 return false;
645 }
646 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800647}
648
649// Disable all /sys/ enable files.
650static bool disableKernelTraceEvents() {
651 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700652 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800653 const TracingCategory &c = k_categories[i];
654 for (int j = 0; j < MAX_SYS_FILES; j++) {
655 const char* path = c.sysfiles[j].path;
656 if (path != NULL && fileIsWritable(path)) {
657 ok &= setKernelOptionEnable(path, false);
658 }
659 }
660 }
661 return ok;
662}
663
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700664// Verify that the comma separated list of functions are being traced by the
665// kernel.
666static bool verifyKernelTraceFuncs(const char* funcs)
667{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100668 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800669 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100670 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700671 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100672 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700673 }
674
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100675 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700676
677 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100678 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700679 bool ok = true;
680 char* myFuncs = strdup(funcs);
681 char* func = strtok(myFuncs, ",");
682 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100683 if (!strchr(func, '*')) {
684 String8 fancyFunc = String8::format("\n%s\n", func);
685 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
686 if (!found || func[0] == '\0') {
687 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
688 "to trace.\n", func);
689 ok = false;
690 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700691 }
692 func = strtok(NULL, ",");
693 }
694 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700695 return ok;
696}
697
698// Set the comma separated list of functions that the kernel is to trace.
699static bool setKernelTraceFuncs(const char* funcs)
700{
701 bool ok = true;
702
703 if (funcs == NULL || funcs[0] == '\0') {
704 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700705 if (fileIsWritable(k_currentTracerPath)) {
706 ok &= writeStr(k_currentTracerPath, "nop");
707 }
708 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700709 ok &= truncateFile(k_ftraceFilterPath);
710 }
711 } else {
712 // Enable kernel function tracing.
713 ok &= writeStr(k_currentTracerPath, "function_graph");
714 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
715 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
716 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
717 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
718
719 // Set the requested filter functions.
720 ok &= truncateFile(k_ftraceFilterPath);
721 char* myFuncs = strdup(funcs);
722 char* func = strtok(myFuncs, ",");
723 while (func) {
724 ok &= appendStr(k_ftraceFilterPath, func);
725 func = strtok(NULL, ",");
726 }
727 free(myFuncs);
728
729 // Verify that the set functions are being traced.
730 if (ok) {
731 ok &= verifyKernelTraceFuncs(funcs);
732 }
733 }
734
735 return ok;
736}
737
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900738static bool setCategoryEnable(const char* name, bool enable)
739{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700740 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900741 const TracingCategory& c = k_categories[i];
742 if (strcmp(name, c.name) == 0) {
743 if (isCategorySupported(c)) {
744 g_categoryEnables[i] = enable;
745 return true;
746 } else {
747 if (isCategorySupportedForRoot(c)) {
748 fprintf(stderr, "error: category \"%s\" requires root "
749 "privileges.\n", name);
750 } else {
751 fprintf(stderr, "error: category \"%s\" is not supported "
752 "on this device.\n", name);
753 }
754 return false;
755 }
756 }
757 }
758 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
759 return false;
760}
761
762static bool setCategoriesEnableFromFile(const char* categories_file)
763{
764 if (!categories_file) {
765 return true;
766 }
767 Tokenizer* tokenizer = NULL;
768 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
769 return false;
770 }
771 bool ok = true;
772 while (!tokenizer->isEol()) {
773 String8 token = tokenizer->nextToken(" ");
774 if (token.isEmpty()) {
775 tokenizer->skipDelimiters(" ");
776 continue;
777 }
778 ok &= setCategoryEnable(token.string(), true);
779 }
780 delete tokenizer;
781 return ok;
782}
783
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700784// Set all the kernel tracing settings to the desired state for this trace
785// capture.
786static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800787{
788 bool ok = true;
789
790 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900791 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800792 ok &= setTraceOverwriteEnable(g_traceOverwrite);
793 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
John Reckba54d5b2017-06-23 09:44:08 -0700794 // TODO: Re-enable after stabilization
795 //ok &= setCmdlineSize();
Carmen Jacksonea826792017-05-05 11:42:32 -0700796 ok &= setClock();
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700797 ok &= setPrintTgidEnableIfPresent(true);
798 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800799
800 // Set up the tags property.
801 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700802 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800803 if (g_categoryEnables[i]) {
804 const TracingCategory &c = k_categories[i];
805 tags |= c.tags;
806 }
807 }
808 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700809
810 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700811 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700812 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
813 coreServicesTagEnabled = g_categoryEnables[i];
814 }
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700815
816 // Set whether to poke PDX services in this session.
817 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
818 g_tracePdx = g_categoryEnables[i];
819 }
sergeyvdb404152016-05-02 19:26:07 -0700820 }
821
822 std::string packageList(g_debugAppCmdLine);
823 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700824 if (!packageList.empty()) {
825 packageList += ",";
826 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700827 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700828 }
Dan Austin09a79872016-05-31 13:27:03 -0700829 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700830 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100831 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800832
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700833 if (g_tracePdx) {
834 ok &= ServiceUtility::PokeServices();
835 }
836
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800837 // Disable all the sysfs enables. This is done as a separate loop from
838 // the enables to allow the same enable to exist in multiple categories.
839 ok &= disableKernelTraceEvents();
840
841 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700842 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800843 if (g_categoryEnables[i]) {
844 const TracingCategory &c = k_categories[i];
845 for (int j = 0; j < MAX_SYS_FILES; j++) {
846 const char* path = c.sysfiles[j].path;
847 bool required = c.sysfiles[j].required == REQ;
848 if (path != NULL) {
849 if (fileIsWritable(path)) {
850 ok &= setKernelOptionEnable(path, true);
851 } else if (required) {
852 fprintf(stderr, "error writing file %s\n", path);
853 ok = false;
854 }
855 }
856 }
857 }
858 }
859
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800860 return ok;
861}
862
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700863// Reset all the kernel tracing settings to their default state.
864static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800865{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800866 // Disable all tracing that we're able to.
867 disableKernelTraceEvents();
868
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700869 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800870 setTagsProperty(0);
sergeyv4144eff2016-04-28 11:40:04 -0700871 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700872 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800873
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700874 if (g_tracePdx) {
875 ServiceUtility::PokeServices();
876 }
877
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800878 // Set the options back to their defaults.
879 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700880 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700881 setPrintTgidEnableIfPresent(false);
882 setKernelTraceFuncs(NULL);
883}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800884
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700885
886// Enable tracing in the kernel.
887static bool startTrace()
888{
889 return setTracingEnabled(true);
890}
891
892// Disable tracing in the kernel.
893static void stopTrace()
894{
895 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800896}
897
Martijn Coenend9535872015-11-26 10:00:55 +0100898// Read data from the tracing pipe and forward to stdout
899static void streamTrace()
900{
901 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800902 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100903 if (traceFD == -1) {
904 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
905 strerror(errno), errno);
906 return;
907 }
908 while (!g_traceAborted) {
909 ssize_t bytes_read = read(traceFD, trace_data, 4096);
910 if (bytes_read > 0) {
911 write(STDOUT_FILENO, trace_data, bytes_read);
912 fflush(stdout);
913 } else {
914 if (!g_traceAborted) {
915 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
916 bytes_read, errno, strerror(errno));
917 }
918 break;
919 }
920 }
921}
922
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800923// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700924static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800925{
John Reck6c8ac922016-03-28 11:25:30 -0700926 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800927 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800928 if (traceFD == -1) {
929 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
930 strerror(errno), errno);
931 return;
932 }
933
934 if (g_compress) {
935 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800936 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700937
938 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800939 if (result != Z_OK) {
940 fprintf(stderr, "error initializing zlib: %d\n", result);
941 close(traceFD);
942 return;
943 }
944
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700945 constexpr size_t bufSize = 64*1024;
946 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
947 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
948 if (!in || !out) {
949 fprintf(stderr, "couldn't allocate buffers\n");
950 close(traceFD);
951 return;
952 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800953
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700954 int flush = Z_NO_FLUSH;
955
956 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800957 zs.avail_out = bufSize;
958
959 do {
960
961 if (zs.avail_in == 0) {
962 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700963 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800964 if (result < 0) {
965 fprintf(stderr, "error reading trace: %s (%d)\n",
966 strerror(errno), errno);
967 result = Z_STREAM_END;
968 break;
969 } else if (result == 0) {
970 flush = Z_FINISH;
971 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700972 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800973 zs.avail_in = result;
974 }
975 }
976
977 if (zs.avail_out == 0) {
978 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700979 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800980 if ((size_t)result < bufSize) {
981 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
982 strerror(errno), errno);
983 result = Z_STREAM_END; // skip deflate error message
984 zs.avail_out = bufSize; // skip the final write
985 break;
986 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700987 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800988 zs.avail_out = bufSize;
989 }
990
991 } while ((result = deflate(&zs, flush)) == Z_OK);
992
993 if (result != Z_STREAM_END) {
994 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
995 }
996
997 if (zs.avail_out < bufSize) {
998 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -0700999 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001000 if ((size_t)result < bytes) {
1001 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1002 strerror(errno), errno);
1003 }
1004 }
1005
1006 result = deflateEnd(&zs);
1007 if (result != Z_OK) {
1008 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1009 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001010 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001011 char buf[4096];
1012 ssize_t rc;
1013 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1014 if (!android::base::WriteFully(outFd, buf, rc)) {
1015 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1016 break;
1017 }
1018 }
1019 if (rc == -1) {
1020 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001021 }
1022 }
1023
1024 close(traceFD);
1025}
1026
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001027static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001028{
1029 if (!g_nohup) {
1030 g_traceAborted = true;
1031 }
1032}
1033
1034static void registerSigHandler()
1035{
1036 struct sigaction sa;
1037 sigemptyset(&sa.sa_mask);
1038 sa.sa_flags = 0;
1039 sa.sa_handler = handleSignal;
1040 sigaction(SIGHUP, &sa, NULL);
1041 sigaction(SIGINT, &sa, NULL);
1042 sigaction(SIGQUIT, &sa, NULL);
1043 sigaction(SIGTERM, &sa, NULL);
1044}
1045
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001046static void listSupportedCategories()
1047{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001048 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001049 const TracingCategory& c = k_categories[i];
1050 if (isCategorySupported(c)) {
1051 printf(" %10s - %s\n", c.name, c.longname);
1052 }
1053 }
1054}
1055
1056// Print the command usage help to stderr.
1057static void showHelp(const char *cmd)
1058{
1059 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1060 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001061 " -a appname enable app-level tracing for a comma "
1062 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001063 " -b N use a trace buffer size of N KB\n"
1064 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001065 " -f filename use the categories written in a file as space-separated\n"
1066 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001067 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001068 " -n ignore signals\n"
1069 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001070 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001071 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001072 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001073 " --async_dump dump the current contents of circular trace buffer\n"
1074 " --async_stop stop tracing and dump the current contents of circular\n"
1075 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001076 " --stream stream trace to stdout as it enters the trace buffer\n"
1077 " Note: this can take significant CPU time, and is best\n"
1078 " used for measuring things that are not affected by\n"
1079 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001080 " --list_categories\n"
1081 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001082 " -o filename write the trace to the specified file instead\n"
1083 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001084 );
1085}
1086
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001087bool findTraceFiles()
1088{
1089 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1090 static const std::string tracefs_path = "/sys/kernel/tracing/";
1091 static const std::string trace_file = "trace_marker";
1092
1093 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1094 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1095
1096 if (!tracefs && !debugfs) {
1097 fprintf(stderr, "Error: Did not find trace folder\n");
1098 return false;
1099 }
1100
1101 if (tracefs) {
1102 g_traceFolder = tracefs_path;
1103 } else {
1104 g_traceFolder = debugfs_path;
1105 }
1106
1107 return true;
1108}
1109
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001110int main(int argc, char **argv)
1111{
1112 bool async = false;
1113 bool traceStart = true;
1114 bool traceStop = true;
1115 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001116 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001117
1118 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1119 showHelp(argv[0]);
1120 exit(0);
1121 }
1122
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001123 if (!findTraceFiles()) {
1124 fprintf(stderr, "No trace folder found\n");
1125 exit(-1);
1126 }
1127
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001128 for (;;) {
1129 int ret;
1130 int option_index = 0;
1131 static struct option long_options[] = {
1132 {"async_start", no_argument, 0, 0 },
1133 {"async_stop", no_argument, 0, 0 },
1134 {"async_dump", no_argument, 0, 0 },
1135 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +01001136 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001137 { 0, 0, 0, 0 }
1138 };
1139
John Reck40b26b42016-03-30 09:44:36 -07001140 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001141 long_options, &option_index);
1142
1143 if (ret < 0) {
1144 for (int i = optind; i < argc; i++) {
1145 if (!setCategoryEnable(argv[i], true)) {
1146 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1147 exit(1);
1148 }
1149 }
1150 break;
1151 }
1152
1153 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001154 case 'a':
1155 g_debugAppCmdLine = optarg;
1156 break;
1157
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001158 case 'b':
1159 g_traceBufferSizeKB = atoi(optarg);
1160 break;
1161
1162 case 'c':
1163 g_traceOverwrite = true;
1164 break;
1165
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001166 case 'f':
1167 g_categoriesFile = optarg;
1168 break;
1169
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001170 case 'k':
1171 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001172 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001173
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001174 case 'n':
1175 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001176 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001177
1178 case 's':
1179 g_initialSleepSecs = atoi(optarg);
1180 break;
1181
1182 case 't':
1183 g_traceDurationSeconds = atoi(optarg);
1184 break;
1185
1186 case 'z':
1187 g_compress = true;
1188 break;
1189
John Reck40b26b42016-03-30 09:44:36 -07001190 case 'o':
1191 g_outputFile = optarg;
1192 break;
1193
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001194 case 0:
1195 if (!strcmp(long_options[option_index].name, "async_start")) {
1196 async = true;
1197 traceStop = false;
1198 traceDump = false;
1199 g_traceOverwrite = true;
1200 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1201 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001202 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001203 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1204 async = true;
1205 traceStart = false;
1206 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001207 } else if (!strcmp(long_options[option_index].name, "stream")) {
1208 traceStream = true;
1209 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001210 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1211 listSupportedCategories();
1212 exit(0);
1213 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001214 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001215
1216 default:
1217 fprintf(stderr, "\n");
1218 showHelp(argv[0]);
1219 exit(-1);
1220 break;
1221 }
1222 }
1223
1224 registerSigHandler();
1225
1226 if (g_initialSleepSecs > 0) {
1227 sleep(g_initialSleepSecs);
1228 }
1229
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001230 bool ok = true;
1231 ok &= setUpTrace();
1232 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001233
1234 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001235 if (!traceStream) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001236 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001237 fflush(stdout);
1238 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001239
1240 // We clear the trace after starting it because tracing gets enabled for
1241 // each CPU individually in the kernel. Having the beginning of the trace
1242 // contain entries from only one CPU can cause "begin" entries without a
1243 // matching "end" entry to show up if a task gets migrated from one CPU to
1244 // another.
1245 ok = clearTrace();
1246
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001247 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001248 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001249 // Sleep to allow the trace to be captured.
1250 struct timespec timeLeft;
1251 timeLeft.tv_sec = g_traceDurationSeconds;
1252 timeLeft.tv_nsec = 0;
1253 do {
1254 if (g_traceAborted) {
1255 break;
1256 }
1257 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1258 }
Martijn Coenend9535872015-11-26 10:00:55 +01001259
1260 if (traceStream) {
1261 streamTrace();
1262 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001263 }
1264
1265 // Stop the trace and restore the default settings.
1266 if (traceStop)
1267 stopTrace();
1268
1269 if (ok && traceDump) {
1270 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001271 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001272 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001273 int outFd = STDOUT_FILENO;
1274 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001275 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001276 }
1277 if (outFd == -1) {
1278 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1279 } else {
1280 dprintf(outFd, "TRACE:\n");
1281 dumpTrace(outFd);
1282 if (g_outputFile) {
1283 close(outFd);
1284 }
1285 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001286 } else {
1287 printf("\ntrace aborted.\n");
1288 fflush(stdout);
1289 }
1290 clearTrace();
1291 } else if (!ok) {
1292 fprintf(stderr, "unable to start tracing\n");
1293 }
1294
1295 // Reset the trace buffer size to 1.
1296 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001297 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001298
1299 return g_traceAborted ? 1 : 0;
1300}