blob: f625250085bc6c668ed76fce3c96af9e0a5e665b [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
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080059
60const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
sergeyv4144eff2016-04-28 11:40:04 -070061
62const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
63const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070064const char* k_coreServiceCategory = "core_services";
Corey Tabakaa6c0a722017-05-31 16:37:40 -070065const char* k_pdxServiceCategory = "pdx";
sergeyvdb404152016-05-02 19:26:07 -070066const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080067
68typedef enum { OPT, REQ } requiredness ;
69
70struct TracingCategory {
71 // The name identifying the category.
72 const char* name;
73
74 // A longer description of the category.
75 const char* longname;
76
77 // The userland tracing tags that the category enables.
78 uint64_t tags;
79
80 // The fname==NULL terminated list of /sys/ files that the category
81 // enables.
82 struct {
83 // Whether the file must be writable in order to enable the tracing
84 // category.
85 requiredness required;
86
87 // The path to the enable file.
88 const char* path;
89 } sysfiles[MAX_SYS_FILES];
90};
91
92/* Tracing categories */
93static const TracingCategory k_categories[] = {
John Reck732a29a2017-05-24 16:09:21 -070094 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, {
95 { OPT, "events/mdss/enable" },
96 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070097 { "input", "Input", ATRACE_TAG_INPUT, { } },
98 { "view", "View System", ATRACE_TAG_VIEW, { } },
99 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
100 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
101 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -0500102 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700103 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
104 { "video", "Video", ATRACE_TAG_VIDEO, { } },
105 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
106 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700107 { "app", "Application", ATRACE_TAG_APP, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -0700108 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -0700109 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -0700110 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -0700111 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700112 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 14:36:20 -0700113 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-07-01 01:46:25 +0900114 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Greg Hackmannbbd7d992014-12-01 14:43:34 -0800115 { "database", "Database", ATRACE_TAG_DATABASE, { } },
Felipe Leme0f97c1d2016-09-07 11:33:26 -0700116 { "network", "Network", ATRACE_TAG_NETWORK, { } },
Josh Gao468b4cb2016-11-29 10:55:21 -0800117 { "adb", "ADB", ATRACE_TAG_ADB, { } },
Alexey Kuzmind4ed9962018-02-10 15:17:57 +0000118 { "vibrator", "Vibrator", ATRACE_TAG_VIBRATOR, {}},
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 Fernandes6ccad102017-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 DuBois062e0b92017-11-03 15:44:08 -0700155 { OPT, "events/power/clock_disable/enable" },
156 { OPT, "events/power/clock_enable/enable" },
Wei Wang53305dd2018-02-22 11:40:07 -0800157 { OPT, "events/clk/clk_set_rate/enable" },
158 { OPT, "events/clk/clk_disable/enable" },
159 { OPT, "events/clk/clk_enable/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800160 { OPT, "events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800161 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700162 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800163 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800164 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700165 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800166 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800167 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700168 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800169 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
170 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
171 { OPT, "events/f2fs/f2fs_write_begin/enable" },
172 { OPT, "events/f2fs/f2fs_write_end/enable" },
173 { OPT, "events/ext4/ext4_da_write_begin/enable" },
174 { OPT, "events/ext4/ext4_da_write_end/enable" },
175 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
176 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
177 { REQ, "events/block/block_rq_issue/enable" },
178 { REQ, "events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800179 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700180 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800181 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700182 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700183 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800184 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800185 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700186 { "sync", "Synchronization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800187 { REQ, "events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800188 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700189 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800190 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800191 } },
Colin Cross580407f2014-08-18 15:22:13 -0700192 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800193 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
194 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
195 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
196 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Marc Hittingerf1f62e32017-05-17 15:57:43 -0700197 { REQ, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700198 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800199 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800200 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800201 } },
Scott Bauerae473362015-06-08 16:32:36 -0700202 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800203 { REQ, "events/binder/binder_transaction/enable" },
204 { REQ, "events/binder/binder_transaction_received/enable" },
Martijn Coenen7f3d7a22017-05-26 09:50:55 -0700205 { OPT, "events/binder/binder_set_priority/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700206 } },
207 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800208 { OPT, "events/binder/binder_lock/enable" },
209 { OPT, "events/binder/binder_locked/enable" },
210 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700211 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200212 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800213 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200214 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800215};
216
217/* Command line options */
218static int g_traceDurationSeconds = 5;
219static bool g_traceOverwrite = false;
220static int g_traceBufferSizeKB = 2048;
221static bool g_compress = false;
222static bool g_nohup = false;
223static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900224static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700225static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700226static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700227static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800228
229/* Global state */
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700230static bool g_tracePdx = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800231static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700232static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800233static std::string g_traceFolder;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800234
235/* Sys file paths */
236static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800237 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800238
239static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800240 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800241
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700242#if 0
243// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700244static const char* k_traceCmdlineSizePath =
245 "saved_cmdlines_size";
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700246#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700247
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800248static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800249 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800250
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700251static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800252 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700253
254static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800255 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700256
257static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800258 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700259
260static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800261 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700262
263static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800264 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700265
266static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800267 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700268
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700269static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800270 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700271
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800272static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800273 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800274
275static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800276 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800277
Martijn Coenend9535872015-11-26 10:00:55 +0100278static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800279 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100280
John Reck469a1942015-03-26 15:31:35 -0700281static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800282 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700283
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800284// Check whether a file exists.
285static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800286 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800287}
288
289// Check whether a file is writable.
290static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800291 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800292}
293
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700294// Truncate a file.
295static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800296{
Jamie Gennis43122e72013-03-21 14:06:31 -0700297 // This uses creat rather than truncate because some of the debug kernel
298 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
299 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800300 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700301 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800302 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700303 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700304 return false;
305 }
306
Jamie Gennis43122e72013-03-21 14:06:31 -0700307 close(traceFD);
308
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700309 return true;
310}
311
312static bool _writeStr(const char* filename, const char* str, int flags)
313{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800314 std::string fullFilename = g_traceFolder + filename;
315 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800316 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800317 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800318 strerror(errno), errno);
319 return false;
320 }
321
322 bool ok = true;
323 ssize_t len = strlen(str);
324 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800325 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800326 strerror(errno), errno);
327 ok = false;
328 }
329
330 close(fd);
331
332 return ok;
333}
334
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700335// Write a string to a file, returning true if the write was successful.
336static bool writeStr(const char* filename, const char* str)
337{
338 return _writeStr(filename, str, O_WRONLY);
339}
340
341// Append a string to a file, returning true if the write was successful.
342static bool appendStr(const char* filename, const char* str)
343{
344 return _writeStr(filename, str, O_APPEND|O_WRONLY);
345}
346
John Reck469a1942015-03-26 15:31:35 -0700347static void writeClockSyncMarker()
348{
349 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200350 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800351 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200352 if (fd == -1) {
353 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
354 strerror(errno), errno);
355 return;
356 }
John Reck469a1942015-03-26 15:31:35 -0700357 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200358
359 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
360 if (write(fd, buffer, len) != len) {
361 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
362 }
363
364 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
365 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
366 if (write(fd, buffer, len) != len) {
367 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
368 }
369
370 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700371}
372
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800373// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
374// file.
375static bool setKernelOptionEnable(const char* filename, bool enable)
376{
377 return writeStr(filename, enable ? "1" : "0");
378}
379
380// Check whether the category is supported on the device with the current
381// rootness. A category is supported only if all its required /sys/ files are
382// writable and if enabling the category will enable one or more tracing tags
383// or /sys/ files.
384static bool isCategorySupported(const TracingCategory& category)
385{
sergeyvdb404152016-05-02 19:26:07 -0700386 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700387 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700388 }
389
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700390 if (strcmp(category.name, k_pdxServiceCategory) == 0) {
391 return true;
392 }
393
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800394 bool ok = category.tags != 0;
395 for (int i = 0; i < MAX_SYS_FILES; i++) {
396 const char* path = category.sysfiles[i].path;
397 bool req = category.sysfiles[i].required == REQ;
398 if (path != NULL) {
399 if (req) {
400 if (!fileIsWritable(path)) {
401 return false;
402 } else {
403 ok = true;
404 }
405 } else {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800406 ok = true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800407 }
408 }
409 }
410 return ok;
411}
412
413// Check whether the category would be supported on the device if the user
414// were root. This function assumes that root is able to write to any file
415// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700416// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800417static bool isCategorySupportedForRoot(const TracingCategory& category)
418{
419 bool ok = category.tags != 0;
420 for (int i = 0; i < MAX_SYS_FILES; i++) {
421 const char* path = category.sysfiles[i].path;
422 bool req = category.sysfiles[i].required == REQ;
423 if (path != NULL) {
424 if (req) {
425 if (!fileExists(path)) {
426 return false;
427 } else {
428 ok = true;
429 }
430 } else {
431 ok |= fileExists(path);
432 }
433 }
434 }
435 return ok;
436}
437
438// Enable or disable overwriting of the kernel trace buffers. Disabling this
439// will cause tracing to stop once the trace buffers have filled up.
440static bool setTraceOverwriteEnable(bool enable)
441{
442 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
443}
444
445// Enable or disable kernel tracing.
446static bool setTracingEnabled(bool enable)
447{
448 return setKernelOptionEnable(k_tracingOnPath, enable);
449}
450
451// Clear the contents of the kernel trace.
452static bool clearTrace()
453{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700454 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800455}
456
457// Set the size of the kernel's trace buffer in kilobytes.
458static bool setTraceBufferSizeKB(int size)
459{
460 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800461 if (size < 1) {
462 size = 1;
463 }
464 snprintf(str, 32, "%d", size);
465 return writeStr(k_traceBufferSizePath, str);
466}
467
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700468#if 0
469// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700470// Set the default size of cmdline hashtable
471static bool setCmdlineSize()
472{
Joel Fernandesce964f22017-06-06 12:20:29 -0700473 if (fileExists(k_traceCmdlineSizePath)) {
474 return writeStr(k_traceCmdlineSizePath, "8192");
475 }
476 return true;
Joel Fernandesed80bd02017-06-02 10:19:28 -0700477}
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700478#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700479
Carmen Jacksonea826792017-05-05 11:42:32 -0700480// Set the clock to the best available option while tracing. Use 'boot' if it's
481// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700482// Any write to the trace_clock sysfs file will reset the buffer, so only
483// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700484static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800485{
Carmen Jacksonea826792017-05-05 11:42:32 -0700486 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
487 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
488 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700489
Carmen Jacksonea826792017-05-05 11:42:32 -0700490 std::string newClock;
491 if (clockStr.find("boot") != std::string::npos) {
492 newClock = "boot";
493 } else if (clockStr.find("mono") != std::string::npos) {
494 newClock = "mono";
495 } else {
496 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700497 }
498
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700499 size_t begin = clockStr.find('[') + 1;
500 size_t end = clockStr.find(']');
Carmen Jacksonea826792017-05-05 11:42:32 -0700501 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
502 return true;
503 }
504 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800505}
506
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700507static bool setPrintTgidEnableIfPresent(bool enable)
508{
509 if (fileExists(k_printTgidPath)) {
510 return setKernelOptionEnable(k_printTgidPath, enable);
511 }
512 return true;
513}
514
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800515// Poke all the binder-enabled processes in the system to get them to re-read
516// their system properties.
517static bool pokeBinderServices()
518{
519 sp<IServiceManager> sm = defaultServiceManager();
520 Vector<String16> services = sm->listServices();
521 for (size_t i = 0; i < services.size(); i++) {
522 sp<IBinder> obj = sm->checkService(services[i]);
523 if (obj != NULL) {
524 Parcel data;
525 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
526 NULL, 0) != OK) {
527 if (false) {
528 // XXX: For some reason this fails on tablets trying to
529 // poke the "phone" service. It's not clear whether some
530 // are expected to fail.
531 String8 svc(services[i]);
532 fprintf(stderr, "error poking binder service %s\n",
533 svc.string());
534 return false;
535 }
536 }
537 }
538 }
539 return true;
540}
541
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100542// Poke all the HAL processes in the system to get them to re-read
543// their system properties.
544static void pokeHalServices()
545{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100546 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100547 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100548 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100549 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100550
551 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800552
553 if (sm == nullptr) {
554 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
555 return;
556 }
557
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800558 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100559 for (size_t i = 0; i < interfaces.size(); i++) {
560 string fqInstanceName = interfaces[i];
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700561 string::size_type n = fqInstanceName.find('/');
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100562 if (n == std::string::npos || interfaces[i].size() == n+1)
563 continue;
564 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
565 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100566 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
567 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100568 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100569 continue;
570 }
Carmen Jackson73206122017-04-18 15:37:57 -0700571
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100572 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700573 if (interface == nullptr) {
574 // ignore
575 continue;
576 }
577
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100578 auto notifyRet = interface->notifySyspropsChanged();
579 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100580 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800581 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100582 }
583 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800584 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100585 // TODO(b/34242478) fix this when we determine the correct ACL
586 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800587 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100588}
589
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800590// Set the trace tags that userland tracing uses, and poke the running
591// processes to pick up the new value.
592static bool setTagsProperty(uint64_t tags)
593{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700594 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
595 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800596 fprintf(stderr, "error setting trace tags system property\n");
597 return false;
598 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700599 return true;
600}
601
sergeyv4144eff2016-04-28 11:40:04 -0700602static void clearAppProperties()
603{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700604 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700605 fprintf(stderr, "failed to clear system property: %s",
606 k_traceAppsNumberProperty);
607 }
608}
609
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700610// Set the system property that indicates which apps should perform
611// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700612static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700613{
sergeyv4144eff2016-04-28 11:40:04 -0700614 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700615 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700616 while (start != NULL) {
sergeyv4144eff2016-04-28 11:40:04 -0700617 char* end = strchr(start, ',');
618 if (end != NULL) {
619 *end = '\0';
620 end++;
621 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700622 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
623 if (!android::base::SetProperty(key, start)) {
624 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700625 clearAppProperties();
626 return false;
627 }
628 start = end;
629 i++;
630 }
631
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700632 std::string value = android::base::StringPrintf("%d", i);
633 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
634 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700635 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700636 return false;
637 }
638 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800639}
640
641// Disable all /sys/ enable files.
642static bool disableKernelTraceEvents() {
643 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700644 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800645 const TracingCategory &c = k_categories[i];
646 for (int j = 0; j < MAX_SYS_FILES; j++) {
647 const char* path = c.sysfiles[j].path;
648 if (path != NULL && fileIsWritable(path)) {
649 ok &= setKernelOptionEnable(path, false);
650 }
651 }
652 }
653 return ok;
654}
655
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700656// Verify that the comma separated list of functions are being traced by the
657// kernel.
658static bool verifyKernelTraceFuncs(const char* funcs)
659{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100660 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800661 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100662 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700663 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100664 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700665 }
666
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100667 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700668
669 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100670 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700671 bool ok = true;
672 char* myFuncs = strdup(funcs);
673 char* func = strtok(myFuncs, ",");
674 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100675 if (!strchr(func, '*')) {
676 String8 fancyFunc = String8::format("\n%s\n", func);
677 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
678 if (!found || func[0] == '\0') {
679 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
680 "to trace.\n", func);
681 ok = false;
682 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700683 }
684 func = strtok(NULL, ",");
685 }
686 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700687 return ok;
688}
689
690// Set the comma separated list of functions that the kernel is to trace.
691static bool setKernelTraceFuncs(const char* funcs)
692{
693 bool ok = true;
694
695 if (funcs == NULL || funcs[0] == '\0') {
696 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700697 if (fileIsWritable(k_currentTracerPath)) {
698 ok &= writeStr(k_currentTracerPath, "nop");
699 }
700 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700701 ok &= truncateFile(k_ftraceFilterPath);
702 }
703 } else {
704 // Enable kernel function tracing.
705 ok &= writeStr(k_currentTracerPath, "function_graph");
706 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
707 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
708 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
709 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
710
711 // Set the requested filter functions.
712 ok &= truncateFile(k_ftraceFilterPath);
713 char* myFuncs = strdup(funcs);
714 char* func = strtok(myFuncs, ",");
715 while (func) {
716 ok &= appendStr(k_ftraceFilterPath, func);
717 func = strtok(NULL, ",");
718 }
719 free(myFuncs);
720
721 // Verify that the set functions are being traced.
722 if (ok) {
723 ok &= verifyKernelTraceFuncs(funcs);
724 }
725 }
726
727 return ok;
728}
729
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900730static bool setCategoryEnable(const char* name, bool enable)
731{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700732 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900733 const TracingCategory& c = k_categories[i];
734 if (strcmp(name, c.name) == 0) {
735 if (isCategorySupported(c)) {
736 g_categoryEnables[i] = enable;
737 return true;
738 } else {
739 if (isCategorySupportedForRoot(c)) {
740 fprintf(stderr, "error: category \"%s\" requires root "
741 "privileges.\n", name);
742 } else {
743 fprintf(stderr, "error: category \"%s\" is not supported "
744 "on this device.\n", name);
745 }
746 return false;
747 }
748 }
749 }
750 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
751 return false;
752}
753
754static bool setCategoriesEnableFromFile(const char* categories_file)
755{
756 if (!categories_file) {
757 return true;
758 }
759 Tokenizer* tokenizer = NULL;
760 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
761 return false;
762 }
763 bool ok = true;
764 while (!tokenizer->isEol()) {
765 String8 token = tokenizer->nextToken(" ");
766 if (token.isEmpty()) {
767 tokenizer->skipDelimiters(" ");
768 continue;
769 }
770 ok &= setCategoryEnable(token.string(), true);
771 }
772 delete tokenizer;
773 return ok;
774}
775
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700776// Set all the kernel tracing settings to the desired state for this trace
777// capture.
778static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800779{
780 bool ok = true;
781
782 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900783 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800784 ok &= setTraceOverwriteEnable(g_traceOverwrite);
785 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
John Reckba54d5b2017-06-23 09:44:08 -0700786 // TODO: Re-enable after stabilization
787 //ok &= setCmdlineSize();
Carmen Jacksonea826792017-05-05 11:42:32 -0700788 ok &= setClock();
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700789 ok &= setPrintTgidEnableIfPresent(true);
790 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800791
792 // Set up the tags property.
793 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700794 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800795 if (g_categoryEnables[i]) {
796 const TracingCategory &c = k_categories[i];
797 tags |= c.tags;
798 }
799 }
800 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700801
802 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700803 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700804 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
805 coreServicesTagEnabled = g_categoryEnables[i];
806 }
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700807
808 // Set whether to poke PDX services in this session.
809 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
810 g_tracePdx = g_categoryEnables[i];
811 }
sergeyvdb404152016-05-02 19:26:07 -0700812 }
813
814 std::string packageList(g_debugAppCmdLine);
815 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700816 if (!packageList.empty()) {
817 packageList += ",";
818 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700819 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700820 }
Dan Austin09a79872016-05-31 13:27:03 -0700821 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700822 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100823 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800824
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700825 if (g_tracePdx) {
826 ok &= ServiceUtility::PokeServices();
827 }
828
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800829 // Disable all the sysfs enables. This is done as a separate loop from
830 // the enables to allow the same enable to exist in multiple categories.
831 ok &= disableKernelTraceEvents();
832
833 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700834 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800835 if (g_categoryEnables[i]) {
836 const TracingCategory &c = k_categories[i];
837 for (int j = 0; j < MAX_SYS_FILES; j++) {
838 const char* path = c.sysfiles[j].path;
839 bool required = c.sysfiles[j].required == REQ;
840 if (path != NULL) {
841 if (fileIsWritable(path)) {
842 ok &= setKernelOptionEnable(path, true);
843 } else if (required) {
844 fprintf(stderr, "error writing file %s\n", path);
845 ok = false;
846 }
847 }
848 }
849 }
850 }
851
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800852 return ok;
853}
854
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700855// Reset all the kernel tracing settings to their default state.
856static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800857{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800858 // Disable all tracing that we're able to.
859 disableKernelTraceEvents();
860
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700861 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800862 setTagsProperty(0);
sergeyv4144eff2016-04-28 11:40:04 -0700863 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700864 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800865
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700866 if (g_tracePdx) {
867 ServiceUtility::PokeServices();
868 }
869
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800870 // Set the options back to their defaults.
871 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700872 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700873 setPrintTgidEnableIfPresent(false);
874 setKernelTraceFuncs(NULL);
875}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800876
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700877
878// Enable tracing in the kernel.
879static bool startTrace()
880{
881 return setTracingEnabled(true);
882}
883
884// Disable tracing in the kernel.
885static void stopTrace()
886{
887 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800888}
889
Martijn Coenend9535872015-11-26 10:00:55 +0100890// Read data from the tracing pipe and forward to stdout
891static void streamTrace()
892{
893 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800894 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100895 if (traceFD == -1) {
896 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
897 strerror(errno), errno);
898 return;
899 }
900 while (!g_traceAborted) {
901 ssize_t bytes_read = read(traceFD, trace_data, 4096);
902 if (bytes_read > 0) {
903 write(STDOUT_FILENO, trace_data, bytes_read);
904 fflush(stdout);
905 } else {
906 if (!g_traceAborted) {
907 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
908 bytes_read, errno, strerror(errno));
909 }
910 break;
911 }
912 }
913}
914
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800915// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700916static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800917{
John Reck6c8ac922016-03-28 11:25:30 -0700918 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800919 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800920 if (traceFD == -1) {
921 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
922 strerror(errno), errno);
923 return;
924 }
925
926 if (g_compress) {
927 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800928 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700929
930 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800931 if (result != Z_OK) {
932 fprintf(stderr, "error initializing zlib: %d\n", result);
933 close(traceFD);
934 return;
935 }
936
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700937 constexpr size_t bufSize = 64*1024;
938 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
939 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
940 if (!in || !out) {
941 fprintf(stderr, "couldn't allocate buffers\n");
942 close(traceFD);
943 return;
944 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800945
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700946 int flush = Z_NO_FLUSH;
947
948 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800949 zs.avail_out = bufSize;
950
951 do {
952
953 if (zs.avail_in == 0) {
954 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700955 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800956 if (result < 0) {
957 fprintf(stderr, "error reading trace: %s (%d)\n",
958 strerror(errno), errno);
959 result = Z_STREAM_END;
960 break;
961 } else if (result == 0) {
962 flush = Z_FINISH;
963 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700964 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800965 zs.avail_in = result;
966 }
967 }
968
969 if (zs.avail_out == 0) {
970 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700971 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800972 if ((size_t)result < bufSize) {
973 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
974 strerror(errno), errno);
975 result = Z_STREAM_END; // skip deflate error message
976 zs.avail_out = bufSize; // skip the final write
977 break;
978 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700979 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800980 zs.avail_out = bufSize;
981 }
982
983 } while ((result = deflate(&zs, flush)) == Z_OK);
984
985 if (result != Z_STREAM_END) {
986 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
987 }
988
989 if (zs.avail_out < bufSize) {
990 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -0700991 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800992 if ((size_t)result < bytes) {
993 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
994 strerror(errno), errno);
995 }
996 }
997
998 result = deflateEnd(&zs);
999 if (result != Z_OK) {
1000 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1001 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001002 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001003 char buf[4096];
1004 ssize_t rc;
1005 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1006 if (!android::base::WriteFully(outFd, buf, rc)) {
1007 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1008 break;
1009 }
1010 }
1011 if (rc == -1) {
1012 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001013 }
1014 }
1015
1016 close(traceFD);
1017}
1018
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001019static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001020{
1021 if (!g_nohup) {
1022 g_traceAborted = true;
1023 }
1024}
1025
1026static void registerSigHandler()
1027{
1028 struct sigaction sa;
1029 sigemptyset(&sa.sa_mask);
1030 sa.sa_flags = 0;
1031 sa.sa_handler = handleSignal;
1032 sigaction(SIGHUP, &sa, NULL);
1033 sigaction(SIGINT, &sa, NULL);
1034 sigaction(SIGQUIT, &sa, NULL);
1035 sigaction(SIGTERM, &sa, NULL);
1036}
1037
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001038static void listSupportedCategories()
1039{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001040 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001041 const TracingCategory& c = k_categories[i];
1042 if (isCategorySupported(c)) {
1043 printf(" %10s - %s\n", c.name, c.longname);
1044 }
1045 }
1046}
1047
1048// Print the command usage help to stderr.
1049static void showHelp(const char *cmd)
1050{
1051 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1052 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001053 " -a appname enable app-level tracing for a comma "
Daniel Colascione519a0792018-02-09 20:05:39 -08001054 "separated list of cmdlines; * is a wildcard matching any process\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001055 " -b N use a trace buffer size of N KB\n"
1056 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001057 " -f filename use the categories written in a file as space-separated\n"
1058 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001059 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001060 " -n ignore signals\n"
1061 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001062 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001063 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001064 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001065 " --async_dump dump the current contents of circular trace buffer\n"
1066 " --async_stop stop tracing and dump the current contents of circular\n"
1067 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001068 " --stream stream trace to stdout as it enters the trace buffer\n"
1069 " Note: this can take significant CPU time, and is best\n"
1070 " used for measuring things that are not affected by\n"
1071 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001072 " --list_categories\n"
1073 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001074 " -o filename write the trace to the specified file instead\n"
1075 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001076 );
1077}
1078
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001079bool findTraceFiles()
1080{
1081 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1082 static const std::string tracefs_path = "/sys/kernel/tracing/";
1083 static const std::string trace_file = "trace_marker";
1084
1085 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1086 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1087
1088 if (!tracefs && !debugfs) {
1089 fprintf(stderr, "Error: Did not find trace folder\n");
1090 return false;
1091 }
1092
1093 if (tracefs) {
1094 g_traceFolder = tracefs_path;
1095 } else {
1096 g_traceFolder = debugfs_path;
1097 }
1098
1099 return true;
1100}
1101
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001102int main(int argc, char **argv)
1103{
1104 bool async = false;
1105 bool traceStart = true;
1106 bool traceStop = true;
1107 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001108 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001109
1110 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1111 showHelp(argv[0]);
1112 exit(0);
1113 }
1114
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001115 if (!findTraceFiles()) {
1116 fprintf(stderr, "No trace folder found\n");
1117 exit(-1);
1118 }
1119
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001120 for (;;) {
1121 int ret;
1122 int option_index = 0;
1123 static struct option long_options[] = {
1124 {"async_start", no_argument, 0, 0 },
1125 {"async_stop", no_argument, 0, 0 },
1126 {"async_dump", no_argument, 0, 0 },
1127 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +01001128 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001129 { 0, 0, 0, 0 }
1130 };
1131
John Reck40b26b42016-03-30 09:44:36 -07001132 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001133 long_options, &option_index);
1134
1135 if (ret < 0) {
1136 for (int i = optind; i < argc; i++) {
1137 if (!setCategoryEnable(argv[i], true)) {
1138 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1139 exit(1);
1140 }
1141 }
1142 break;
1143 }
1144
1145 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001146 case 'a':
1147 g_debugAppCmdLine = optarg;
1148 break;
1149
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001150 case 'b':
1151 g_traceBufferSizeKB = atoi(optarg);
1152 break;
1153
1154 case 'c':
1155 g_traceOverwrite = true;
1156 break;
1157
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001158 case 'f':
1159 g_categoriesFile = optarg;
1160 break;
1161
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001162 case 'k':
1163 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001164 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001165
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001166 case 'n':
1167 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001168 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001169
1170 case 's':
1171 g_initialSleepSecs = atoi(optarg);
1172 break;
1173
1174 case 't':
1175 g_traceDurationSeconds = atoi(optarg);
1176 break;
1177
1178 case 'z':
1179 g_compress = true;
1180 break;
1181
John Reck40b26b42016-03-30 09:44:36 -07001182 case 'o':
1183 g_outputFile = optarg;
1184 break;
1185
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001186 case 0:
1187 if (!strcmp(long_options[option_index].name, "async_start")) {
1188 async = true;
1189 traceStop = false;
1190 traceDump = false;
1191 g_traceOverwrite = true;
1192 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1193 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001194 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001195 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1196 async = true;
1197 traceStart = false;
1198 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001199 } else if (!strcmp(long_options[option_index].name, "stream")) {
1200 traceStream = true;
1201 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001202 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1203 listSupportedCategories();
1204 exit(0);
1205 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001206 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001207
1208 default:
1209 fprintf(stderr, "\n");
1210 showHelp(argv[0]);
1211 exit(-1);
1212 break;
1213 }
1214 }
1215
1216 registerSigHandler();
1217
1218 if (g_initialSleepSecs > 0) {
1219 sleep(g_initialSleepSecs);
1220 }
1221
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001222 bool ok = true;
1223 ok &= setUpTrace();
1224 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001225
1226 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001227 if (!traceStream) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001228 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001229 fflush(stdout);
1230 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001231
1232 // We clear the trace after starting it because tracing gets enabled for
1233 // each CPU individually in the kernel. Having the beginning of the trace
1234 // contain entries from only one CPU can cause "begin" entries without a
1235 // matching "end" entry to show up if a task gets migrated from one CPU to
1236 // another.
1237 ok = clearTrace();
1238
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001239 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001240 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001241 // Sleep to allow the trace to be captured.
1242 struct timespec timeLeft;
1243 timeLeft.tv_sec = g_traceDurationSeconds;
1244 timeLeft.tv_nsec = 0;
1245 do {
1246 if (g_traceAborted) {
1247 break;
1248 }
1249 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1250 }
Martijn Coenend9535872015-11-26 10:00:55 +01001251
1252 if (traceStream) {
1253 streamTrace();
1254 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001255 }
1256
1257 // Stop the trace and restore the default settings.
1258 if (traceStop)
1259 stopTrace();
1260
1261 if (ok && traceDump) {
1262 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001263 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001264 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001265 int outFd = STDOUT_FILENO;
1266 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001267 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001268 }
1269 if (outFd == -1) {
1270 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1271 } else {
1272 dprintf(outFd, "TRACE:\n");
1273 dumpTrace(outFd);
1274 if (g_outputFile) {
1275 close(outFd);
1276 }
1277 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001278 } else {
1279 printf("\ntrace aborted.\n");
1280 fflush(stdout);
1281 }
1282 clearTrace();
1283 } else if (!ok) {
1284 fprintf(stderr, "unable to start tracing\n");
1285 }
1286
1287 // Reset the trace buffer size to 1.
1288 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001289 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001290
1291 return g_traceAborted ? 1 : 0;
1292}