blob: 913090da140f682f45283d8b1fb4a1349c86a6fa [file] [log] [blame]
Jamie Gennis6eea6fb2012-12-07 22:03:071/*
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 17:50:1817#define LOG_TAG "atrace"
John Reck40b26b42016-03-30 16:44:3618
Jamie Gennis6eea6fb2012-12-07 22:03:0719#include <errno.h>
20#include <fcntl.h>
21#include <getopt.h>
Mark Salyzyn92dc3fc2014-03-12 20:12:4422#include <inttypes.h>
Jamie Gennis6eea6fb2012-12-07 22:03:0723#include <signal.h>
24#include <stdarg.h>
25#include <stdbool.h>
26#include <stdio.h>
27#include <stdlib.h>
Elliott Hughes3da5d232015-01-25 16:35:2028#include <string.h>
Jamie Gennis6eea6fb2012-12-07 22:03:0729#include <time.h>
Martijn Coenend9535872015-11-26 09:00:5530#include <unistd.h>
Jamie Gennis6eea6fb2012-12-07 22:03:0731#include <zlib.h>
32
Carmen Jacksonea826792017-05-05 18:42:3233#include <fstream>
Elliott Hughesa252f4d2016-07-22 00:12:1534#include <memory>
35
Jamie Gennis6eea6fb2012-12-07 22:03:0736#include <binder/IBinder.h>
37#include <binder/IServiceManager.h>
38#include <binder/Parcel.h>
39
Martijn Coenenee9b97e2016-11-16 15:00:2640#include <android/hidl/manager/1.0/IServiceManager.h>
41#include <hidl/ServiceManagement.h>
Jamie Gennis6eea6fb2012-12-07 22:03:0742
Corey Tabakaa6c0a722017-05-31 23:37:4043#include <pdx/default_transport/service_utility.h>
Jamie Gennis6eea6fb2012-12-07 22:03:0744#include <utils/String8.h>
John Reck469a1942015-03-26 22:31:3545#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 10:20:3946#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 22:03:0747#include <utils/Trace.h>
Stephane Gasparinid8419c22016-03-02 12:45:1548#include <android-base/file.h>
Elliott Hughes5fd6ff62017-03-28 21:55:3149#include <android-base/macros.h>
50#include <android-base/properties.h>
51#include <android-base/stringprintf.h>
Jamie Gennis6eea6fb2012-12-07 22:03:0752
53using namespace android;
Corey Tabakaa6c0a722017-05-31 23:37:4054using pdx::default_transport::ServiceUtility;
Jamie Gennis6eea6fb2012-12-07 22:03:0755
Martijn Coenenee9b97e2016-11-16 15:00:2656using std::string;
Jamie Gennis6eea6fb2012-12-07 22:03:0757
sergeyv4144eff2016-04-28 18:40:0458#define MAX_SYS_FILES 10
Jamie Gennis6eea6fb2012-12-07 22:03:0759
60const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
Carmen Jacksonab1118e2018-05-22 17:29:4761const char* k_userInitiatedTraceProperty = "debug.atrace.user_initiated";
sergeyv4144eff2016-04-28 18:40:0462
63const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
64const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-03 02:26:0765const char* k_coreServiceCategory = "core_services";
Corey Tabakaa6c0a722017-05-31 23:37:4066const char* k_pdxServiceCategory = "pdx";
sergeyvdb404152016-05-03 02:26:0767const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 22:03:0768
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 23:09:2195 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, {
96 { OPT, "events/mdss/enable" },
Wei Wangbcfb4872018-02-13 18:47:2397 { OPT, "events/sde/enable" },
John Reck732a29a2017-05-24 23:09:2198 } },
Jamie Gennisb2a89e32013-03-12 02:37:5399 { "input", "Input", ATRACE_TAG_INPUT, { } },
100 { "view", "View System", ATRACE_TAG_VIEW, { } },
101 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
102 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
103 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 20:38:30104 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-12 02:37:53105 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
106 { "video", "Video", ATRACE_TAG_VIDEO, { } },
107 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
108 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Dianne Hackborn9380d782013-04-12 21:52:35109 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 22:20:39110 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 21:39:42111 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 21:23:24112 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-15 02:24:47113 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 21:36:20114 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-06-30 16:46:25115 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Greg Hackmannbbd7d992014-12-01 22:43:34116 { "database", "Database", ATRACE_TAG_DATABASE, { } },
Felipe Leme0f97c1d2016-09-07 18:33:26117 { "network", "Network", ATRACE_TAG_NETWORK, { } },
Josh Gao468b4cb2016-11-29 18:55:21118 { "adb", "ADB", ATRACE_TAG_ADB, { } },
Martijn Coenen42f2ab42018-03-09 08:27:32119 { "vibrator", "Vibrator", ATRACE_TAG_VIBRATOR, { } },
120 { "aidl", "AIDL calls", ATRACE_TAG_AIDL, { } },
Mika Raentob363cf52018-04-23 21:09:13121 { "nnapi", "NNAPI", ATRACE_TAG_NNAPI, { } },
sergeyvdb404152016-05-03 02:26:07122 { k_coreServiceCategory, "Core services", 0, { } },
Corey Tabakaa6c0a722017-05-31 23:37:40123 { k_pdxServiceCategory, "PDX services", 0, { } },
Jamie Gennisb2a89e32013-03-12 02:37:53124 { "sched", "CPU Scheduling", 0, {
Paul Lawrence2cd93cc2017-01-17 17:50:18125 { REQ, "events/sched/sched_switch/enable" },
126 { REQ, "events/sched/sched_wakeup/enable" },
Joel Fernandesee593e22017-06-04 20:05:59127 { OPT, "events/sched/sched_waking/enable" },
Paul Lawrence2cd93cc2017-01-17 17:50:18128 { OPT, "events/sched/sched_blocked_reason/enable" },
129 { OPT, "events/sched/sched_cpu_hotplug/enable" },
Joel Fernandes4dfca7c2017-06-15 23:53:52130 { OPT, "events/cgroup/enable" },
Jamie Gennis6eea6fb2012-12-07 22:03:07131 } },
Dan Willemsenf440d392014-04-11 22:44:09132 { "irq", "IRQ Events", 0, {
Paul Lawrence2cd93cc2017-01-17 17:50:18133 { REQ, "events/irq/enable" },
134 { OPT, "events/ipi/enable" },
Dan Willemsenf440d392014-04-11 22:44:09135 } },
Joel Fernandes6ccad102017-08-31 15:35:05136 { "irqoff", "IRQ-disabled code section tracing", 0, {
137 { REQ, "events/preemptirq/irq_enable/enable" },
138 { REQ, "events/preemptirq/irq_disable/enable" },
139 } },
140 { "preemptoff", "Preempt-disabled code section tracing", 0, {
141 { REQ, "events/preemptirq/preempt_enable/enable" },
142 { REQ, "events/preemptirq/preempt_disable/enable" },
143 } },
Michael Wright43fb6782016-08-18 18:56:43144 { "i2c", "I2C Events", 0, {
Paul Lawrence2cd93cc2017-01-17 17:50:18145 { REQ, "events/i2c/enable" },
146 { REQ, "events/i2c/i2c_read/enable" },
147 { REQ, "events/i2c/i2c_write/enable" },
148 { REQ, "events/i2c/i2c_result/enable" },
149 { REQ, "events/i2c/i2c_reply/enable" },
150 { OPT, "events/i2c/smbus_read/enable" },
151 { OPT, "events/i2c/smbus_write/enable" },
152 { OPT, "events/i2c/smbus_result/enable" },
153 { OPT, "events/i2c/smbus_reply/enable" },
Michael Wright43fb6782016-08-18 18:56:43154 } },
Jamie Gennisb2a89e32013-03-12 02:37:53155 { "freq", "CPU Frequency", 0, {
Paul Lawrence2cd93cc2017-01-17 17:50:18156 { REQ, "events/power/cpu_frequency/enable" },
157 { OPT, "events/power/clock_set_rate/enable" },
Kevin DuBois062e0b92017-11-03 22:44:08158 { OPT, "events/power/clock_disable/enable" },
159 { OPT, "events/power/clock_enable/enable" },
Wei Wang53305dd2018-02-22 19:40:07160 { OPT, "events/clk/clk_set_rate/enable" },
161 { OPT, "events/clk/clk_disable/enable" },
162 { OPT, "events/clk/clk_enable/enable" },
Paul Lawrence2cd93cc2017-01-17 17:50:18163 { OPT, "events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 22:03:07164 } },
Jamie Gennisb2a89e32013-03-12 02:37:53165 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 17:50:18166 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 22:03:07167 } },
Jamie Gennisb2a89e32013-03-12 02:37:53168 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 17:50:18169 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 22:03:07170 } },
Jamie Gennisb2a89e32013-03-12 02:37:53171 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 17:50:18172 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
173 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
174 { OPT, "events/f2fs/f2fs_write_begin/enable" },
175 { OPT, "events/f2fs/f2fs_write_end/enable" },
176 { OPT, "events/ext4/ext4_da_write_begin/enable" },
177 { OPT, "events/ext4/ext4_da_write_end/enable" },
178 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
179 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
180 { REQ, "events/block/block_rq_issue/enable" },
181 { REQ, "events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 22:03:07182 } },
Ken Sumralld3fa5612013-07-03 19:32:03183 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 17:50:18184 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 19:32:03185 } },
Jamie Gennisb2a89e32013-03-12 02:37:53186 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 17:50:18187 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 22:03:07188 } },
Jamie Gennisb2a89e32013-03-12 02:37:53189 { "sync", "Synchronization", 0, {
Paul Lawrence2cd93cc2017-01-17 17:50:18190 { REQ, "events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 22:03:07191 } },
Jamie Gennisb2a89e32013-03-12 02:37:53192 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 17:50:18193 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 22:03:07194 } },
Colin Cross580407f2014-08-18 22:22:13195 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 17:50:18196 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
197 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
198 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
199 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Carmen Jackson7a23eb72018-07-02 20:14:56200 { OPT, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 22:22:13201 } },
Aaron Schulmanc2c6ecd2015-02-25 16:37:09202 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 17:50:18203 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 16:37:09204 } },
Scott Bauerae473362015-06-08 23:32:36205 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 17:50:18206 { REQ, "events/binder/binder_transaction/enable" },
207 { REQ, "events/binder/binder_transaction_received/enable" },
Mika Raento80c3e5d2018-06-25 15:47:24208 { REQ, "events/binder/binder_transaction_alloc_buf/enable" },
Martijn Coenen7f3d7a22017-05-26 16:50:55209 { OPT, "events/binder/binder_set_priority/enable" },
Scott Bauerae473362015-06-08 23:32:36210 } },
211 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 08:32:11212 { OPT, "events/binder/binder_lock/enable" },
213 { OPT, "events/binder/binder_locked/enable" },
214 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 23:32:36215 } },
Martijn Coenen70481612015-10-23 11:57:05216 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 17:50:18217 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 11:57:05218 } },
Jamie Gennis6eea6fb2012-12-07 22:03:07219};
220
221/* Command line options */
222static int g_traceDurationSeconds = 5;
223static bool g_traceOverwrite = false;
224static int g_traceBufferSizeKB = 2048;
225static bool g_compress = false;
226static bool g_nohup = false;
227static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 10:20:39228static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 23:00:10229static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 22:50:58230static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 16:44:36231static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 22:03:07232
233/* Global state */
Corey Tabakaa6c0a722017-05-31 23:37:40234static bool g_tracePdx = false;
Jamie Gennis6eea6fb2012-12-07 22:03:07235static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 21:55:31236static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 17:50:18237static std::string g_traceFolder;
Jamie Gennis6eea6fb2012-12-07 22:03:07238
239/* Sys file paths */
240static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 17:50:18241 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 22:03:07242
243static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 17:50:18244 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 22:03:07245
Chih-Hung Hsieh734e3782017-10-05 20:44:13246#if 0
247// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 17:19:28248static const char* k_traceCmdlineSizePath =
249 "saved_cmdlines_size";
Chih-Hung Hsieh734e3782017-10-05 20:44:13250#endif
Joel Fernandesed80bd02017-06-02 17:19:28251
Jamie Gennis6eea6fb2012-12-07 22:03:07252static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 17:50:18253 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 22:03:07254
Jamie Gennise9b8cfb2013-03-12 23:00:10255static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 17:50:18256 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 23:00:10257
258static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 17:50:18259 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 23:00:10260
John Recke757b1c2018-06-28 19:24:33261static const char* k_recordTgidPath =
262 "options/record-tgid";
263
Jamie Gennise9b8cfb2013-03-12 23:00:10264static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 17:50:18265 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 23:00:10266
267static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 17:50:18268 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 23:00:10269
270static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 17:50:18271 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 23:00:10272
273static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 17:50:18274 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 23:00:10275
Jamie Gennise9b8cfb2013-03-12 23:00:10276static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 17:50:18277 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 23:00:10278
Jamie Gennis6eea6fb2012-12-07 22:03:07279static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 17:50:18280 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 22:03:07281
282static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 17:50:18283 "trace";
Jamie Gennis6eea6fb2012-12-07 22:03:07284
Martijn Coenend9535872015-11-26 09:00:55285static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 17:50:18286 "trace_pipe";
Martijn Coenend9535872015-11-26 09:00:55287
John Reck469a1942015-03-26 22:31:35288static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 17:50:18289 "trace_marker";
John Reck469a1942015-03-26 22:31:35290
Jamie Gennis6eea6fb2012-12-07 22:03:07291// Check whether a file exists.
292static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 17:50:18293 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 22:03:07294}
295
296// Check whether a file is writable.
297static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 17:50:18298 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 22:03:07299}
300
Jamie Gennise9b8cfb2013-03-12 23:00:10301// Truncate a file.
302static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 22:03:07303{
Jamie Gennis43122e72013-03-21 21:06:31304 // This uses creat rather than truncate because some of the debug kernel
305 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
306 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 17:50:18307 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 21:06:31308 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 17:50:18309 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 21:06:31310 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 23:00:10311 return false;
312 }
313
Jamie Gennis43122e72013-03-21 21:06:31314 close(traceFD);
315
Jamie Gennise9b8cfb2013-03-12 23:00:10316 return true;
317}
318
319static bool _writeStr(const char* filename, const char* str, int flags)
320{
Paul Lawrence2cd93cc2017-01-17 17:50:18321 std::string fullFilename = g_traceFolder + filename;
322 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 22:03:07323 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 17:50:18324 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 22:03:07325 strerror(errno), errno);
326 return false;
327 }
328
329 bool ok = true;
330 ssize_t len = strlen(str);
331 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 17:50:18332 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 22:03:07333 strerror(errno), errno);
334 ok = false;
335 }
336
337 close(fd);
338
339 return ok;
340}
341
Jamie Gennise9b8cfb2013-03-12 23:00:10342// Write a string to a file, returning true if the write was successful.
343static bool writeStr(const char* filename, const char* str)
344{
345 return _writeStr(filename, str, O_WRONLY);
346}
347
348// Append a string to a file, returning true if the write was successful.
349static bool appendStr(const char* filename, const char* str)
350{
351 return _writeStr(filename, str, O_APPEND|O_WRONLY);
352}
353
John Reck469a1942015-03-26 22:31:35354static void writeClockSyncMarker()
355{
356 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 12:25:23357 int len = 0;
Paul Lawrence2cd93cc2017-01-17 17:50:18358 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 12:25:23359 if (fd == -1) {
360 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
361 strerror(errno), errno);
362 return;
363 }
John Reck469a1942015-03-26 22:31:35364 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 12:25:23365
366 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
367 if (write(fd, buffer, len) != len) {
368 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
369 }
370
371 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
372 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
373 if (write(fd, buffer, len) != len) {
374 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
375 }
376
377 close(fd);
John Reck469a1942015-03-26 22:31:35378}
379
Jamie Gennis6eea6fb2012-12-07 22:03:07380// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
381// file.
382static bool setKernelOptionEnable(const char* filename, bool enable)
383{
384 return writeStr(filename, enable ? "1" : "0");
385}
386
387// Check whether the category is supported on the device with the current
388// rootness. A category is supported only if all its required /sys/ files are
389// writable and if enabling the category will enable one or more tracing tags
390// or /sys/ files.
391static bool isCategorySupported(const TracingCategory& category)
392{
sergeyvdb404152016-05-03 02:26:07393 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 21:55:31394 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-03 02:26:07395 }
396
Corey Tabakaa6c0a722017-05-31 23:37:40397 if (strcmp(category.name, k_pdxServiceCategory) == 0) {
398 return true;
399 }
400
Jamie Gennis6eea6fb2012-12-07 22:03:07401 bool ok = category.tags != 0;
402 for (int i = 0; i < MAX_SYS_FILES; i++) {
403 const char* path = category.sysfiles[i].path;
404 bool req = category.sysfiles[i].required == REQ;
405 if (path != NULL) {
406 if (req) {
407 if (!fileIsWritable(path)) {
408 return false;
409 } else {
410 ok = true;
411 }
412 } else {
Howard Cheneb8acbf2017-05-10 08:32:11413 ok = true;
Jamie Gennis6eea6fb2012-12-07 22:03:07414 }
415 }
416 }
417 return ok;
418}
419
420// Check whether the category would be supported on the device if the user
421// were root. This function assumes that root is able to write to any file
422// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 18:40:12423// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 22:03:07424static bool isCategorySupportedForRoot(const TracingCategory& category)
425{
426 bool ok = category.tags != 0;
427 for (int i = 0; i < MAX_SYS_FILES; i++) {
428 const char* path = category.sysfiles[i].path;
429 bool req = category.sysfiles[i].required == REQ;
430 if (path != NULL) {
431 if (req) {
432 if (!fileExists(path)) {
433 return false;
434 } else {
435 ok = true;
436 }
437 } else {
438 ok |= fileExists(path);
439 }
440 }
441 }
442 return ok;
443}
444
445// Enable or disable overwriting of the kernel trace buffers. Disabling this
446// will cause tracing to stop once the trace buffers have filled up.
447static bool setTraceOverwriteEnable(bool enable)
448{
449 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
450}
451
Carmen Jacksonab1118e2018-05-22 17:29:47452// Set the user initiated trace property
453static bool setUserInitiatedTraceProperty(bool enable)
454{
455 if (!android::base::SetProperty(k_userInitiatedTraceProperty, enable ? "1" : "")) {
456 fprintf(stderr, "error setting user initiated strace system property\n");
457 return false;
458 }
459 return true;
460}
461
Jamie Gennis6eea6fb2012-12-07 22:03:07462// Enable or disable kernel tracing.
463static bool setTracingEnabled(bool enable)
464{
465 return setKernelOptionEnable(k_tracingOnPath, enable);
466}
467
468// Clear the contents of the kernel trace.
469static bool clearTrace()
470{
Jamie Gennise9b8cfb2013-03-12 23:00:10471 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 22:03:07472}
473
474// Set the size of the kernel's trace buffer in kilobytes.
475static bool setTraceBufferSizeKB(int size)
476{
477 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 22:03:07478 if (size < 1) {
479 size = 1;
480 }
481 snprintf(str, 32, "%d", size);
482 return writeStr(k_traceBufferSizePath, str);
483}
484
Chih-Hung Hsieh734e3782017-10-05 20:44:13485#if 0
486// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 17:19:28487// Set the default size of cmdline hashtable
488static bool setCmdlineSize()
489{
Joel Fernandesce964f22017-06-06 19:20:29490 if (fileExists(k_traceCmdlineSizePath)) {
491 return writeStr(k_traceCmdlineSizePath, "8192");
492 }
493 return true;
Joel Fernandesed80bd02017-06-02 17:19:28494}
Chih-Hung Hsieh734e3782017-10-05 20:44:13495#endif
Joel Fernandesed80bd02017-06-02 17:19:28496
Carmen Jacksonea826792017-05-05 18:42:32497// Set the clock to the best available option while tracing. Use 'boot' if it's
498// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 21:28:47499// Any write to the trace_clock sysfs file will reset the buffer, so only
500// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 18:42:32501static bool setClock()
Jamie Gennis6eea6fb2012-12-07 22:03:07502{
Carmen Jacksonea826792017-05-05 18:42:32503 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
504 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
505 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 21:28:47506
Carmen Jacksonea826792017-05-05 18:42:32507 std::string newClock;
508 if (clockStr.find("boot") != std::string::npos) {
509 newClock = "boot";
510 } else if (clockStr.find("mono") != std::string::npos) {
511 newClock = "mono";
512 } else {
513 newClock = "global";
Colin Crossb1ce49b2014-08-20 21:28:47514 }
515
Chih-Hung Hsiehcb057c22017-08-03 22:48:25516 size_t begin = clockStr.find('[') + 1;
517 size_t end = clockStr.find(']');
Carmen Jacksonea826792017-05-05 18:42:32518 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
519 return true;
520 }
521 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 22:03:07522}
523
Jamie Gennise9b8cfb2013-03-12 23:00:10524static bool setPrintTgidEnableIfPresent(bool enable)
525{
John Reckedbf9ec2018-06-29 18:15:17526 // Pre-4.13 this was options/print-tgid as an android-specific option.
527 // In 4.13+ this is an upstream option called options/record-tgid
528 // Both options produce the same ftrace format change
Jamie Gennise9b8cfb2013-03-12 23:00:10529 if (fileExists(k_printTgidPath)) {
530 return setKernelOptionEnable(k_printTgidPath, enable);
531 }
John Recke757b1c2018-06-28 19:24:33532 if (fileExists(k_recordTgidPath)) {
533 return setKernelOptionEnable(k_recordTgidPath, enable);
534 }
Jamie Gennise9b8cfb2013-03-12 23:00:10535 return true;
536}
537
Jamie Gennis6eea6fb2012-12-07 22:03:07538// Poke all the binder-enabled processes in the system to get them to re-read
539// their system properties.
540static bool pokeBinderServices()
541{
542 sp<IServiceManager> sm = defaultServiceManager();
543 Vector<String16> services = sm->listServices();
544 for (size_t i = 0; i < services.size(); i++) {
545 sp<IBinder> obj = sm->checkService(services[i]);
546 if (obj != NULL) {
547 Parcel data;
548 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
549 NULL, 0) != OK) {
550 if (false) {
551 // XXX: For some reason this fails on tablets trying to
552 // poke the "phone" service. It's not clear whether some
553 // are expected to fail.
554 String8 svc(services[i]);
555 fprintf(stderr, "error poking binder service %s\n",
556 svc.string());
557 return false;
558 }
559 }
560 }
561 }
562 return true;
563}
564
Martijn Coenenee9b97e2016-11-16 15:00:26565// Poke all the HAL processes in the system to get them to re-read
566// their system properties.
567static void pokeHalServices()
568{
Martijn Coenenf6ac8482017-01-02 14:17:11569 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 15:00:26570 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 15:00:26571 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 14:17:11572 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 15:00:26573
574 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 23:18:06575
576 if (sm == nullptr) {
577 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
578 return;
579 }
580
Yifan Hong8cf4ed12016-12-01 01:28:58581 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 15:00:26582 for (size_t i = 0; i < interfaces.size(); i++) {
583 string fqInstanceName = interfaces[i];
Chih-Hung Hsiehcb057c22017-08-03 22:48:25584 string::size_type n = fqInstanceName.find('/');
Martijn Coenenee9b97e2016-11-16 15:00:26585 if (n == std::string::npos || interfaces[i].size() == n+1)
586 continue;
587 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
588 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 14:17:11589 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
590 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 13:57:38591 // ignore
Martijn Coenenf6ac8482017-01-02 14:17:11592 continue;
593 }
Carmen Jackson73206122017-04-18 22:37:57594
Martijn Coenenf6ac8482017-01-02 14:17:11595 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 22:37:57596 if (interface == nullptr) {
597 // ignore
598 continue;
599 }
600
Martijn Coenenf6ac8482017-01-02 14:17:11601 auto notifyRet = interface->notifySyspropsChanged();
602 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 13:57:38603 // ignore
Yifan Hong8cf4ed12016-12-01 01:28:58604 }
Martijn Coenenee9b97e2016-11-16 15:00:26605 }
606 });
Yifan Hong8cf4ed12016-12-01 01:28:58607 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 16:16:31608 // TODO(b/34242478) fix this when we determine the correct ACL
609 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-12-01 01:28:58610 }
Martijn Coenenee9b97e2016-11-16 15:00:26611}
612
Jamie Gennis6eea6fb2012-12-07 22:03:07613// Set the trace tags that userland tracing uses, and poke the running
614// processes to pick up the new value.
615static bool setTagsProperty(uint64_t tags)
616{
Elliott Hughes5fd6ff62017-03-28 21:55:31617 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
618 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 22:03:07619 fprintf(stderr, "error setting trace tags system property\n");
620 return false;
621 }
Jamie Gennisf7f29c82013-03-27 22:50:58622 return true;
623}
624
sergeyv4144eff2016-04-28 18:40:04625static void clearAppProperties()
626{
Elliott Hughes5fd6ff62017-03-28 21:55:31627 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 18:40:04628 fprintf(stderr, "failed to clear system property: %s",
629 k_traceAppsNumberProperty);
630 }
631}
632
Jamie Gennisf7f29c82013-03-27 22:50:58633// Set the system property that indicates which apps should perform
634// application-level tracing.
Dan Austin09a79872016-05-31 20:27:03635static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 22:50:58636{
sergeyv4144eff2016-04-28 18:40:04637 int i = 0;
Dan Austin09a79872016-05-31 20:27:03638 char* start = cmdline;
sergeyv4144eff2016-04-28 18:40:04639 while (start != NULL) {
sergeyv4144eff2016-04-28 18:40:04640 char* end = strchr(start, ',');
641 if (end != NULL) {
642 *end = '\0';
643 end++;
644 }
Elliott Hughes5fd6ff62017-03-28 21:55:31645 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
646 if (!android::base::SetProperty(key, start)) {
647 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 18:40:04648 clearAppProperties();
649 return false;
650 }
651 start = end;
652 i++;
653 }
654
Elliott Hughes5fd6ff62017-03-28 21:55:31655 std::string value = android::base::StringPrintf("%d", i);
656 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
657 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 18:40:04658 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 22:50:58659 return false;
660 }
661 return true;
Jamie Gennis6eea6fb2012-12-07 22:03:07662}
663
664// Disable all /sys/ enable files.
665static bool disableKernelTraceEvents() {
666 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 21:55:31667 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 22:03:07668 const TracingCategory &c = k_categories[i];
669 for (int j = 0; j < MAX_SYS_FILES; j++) {
670 const char* path = c.sysfiles[j].path;
671 if (path != NULL && fileIsWritable(path)) {
672 ok &= setKernelOptionEnable(path, false);
673 }
674 }
675 }
676 return ok;
677}
678
Jamie Gennise9b8cfb2013-03-12 23:00:10679// Verify that the comma separated list of functions are being traced by the
680// kernel.
681static bool verifyKernelTraceFuncs(const char* funcs)
682{
Stephane Gasparinid8419c22016-03-02 12:45:15683 std::string buf;
Paul Lawrence2cd93cc2017-01-17 17:50:18684 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 12:45:15685 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 23:00:10686 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 12:45:15687 return false;
Jamie Gennise9b8cfb2013-03-12 23:00:10688 }
689
Stephane Gasparinid8419c22016-03-02 12:45:15690 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 23:00:10691
692 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 08:44:31693 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 23:00:10694 bool ok = true;
695 char* myFuncs = strdup(funcs);
696 char* func = strtok(myFuncs, ",");
697 while (func) {
Thomas Buhota2c22872016-01-27 08:44:31698 if (!strchr(func, '*')) {
699 String8 fancyFunc = String8::format("\n%s\n", func);
700 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
701 if (!found || func[0] == '\0') {
702 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
703 "to trace.\n", func);
704 ok = false;
705 }
Jamie Gennise9b8cfb2013-03-12 23:00:10706 }
707 func = strtok(NULL, ",");
708 }
709 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 23:00:10710 return ok;
711}
712
713// Set the comma separated list of functions that the kernel is to trace.
714static bool setKernelTraceFuncs(const char* funcs)
715{
716 bool ok = true;
717
718 if (funcs == NULL || funcs[0] == '\0') {
719 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 22:50:30720 if (fileIsWritable(k_currentTracerPath)) {
721 ok &= writeStr(k_currentTracerPath, "nop");
722 }
723 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 23:00:10724 ok &= truncateFile(k_ftraceFilterPath);
725 }
726 } else {
727 // Enable kernel function tracing.
728 ok &= writeStr(k_currentTracerPath, "function_graph");
729 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
730 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
731 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
732 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
733
734 // Set the requested filter functions.
735 ok &= truncateFile(k_ftraceFilterPath);
736 char* myFuncs = strdup(funcs);
737 char* func = strtok(myFuncs, ",");
738 while (func) {
739 ok &= appendStr(k_ftraceFilterPath, func);
740 func = strtok(NULL, ",");
741 }
742 free(myFuncs);
743
744 // Verify that the set functions are being traced.
745 if (ok) {
746 ok &= verifyKernelTraceFuncs(funcs);
747 }
748 }
749
750 return ok;
751}
752
Yasuhiro Matsuda46c51fb2015-06-29 10:20:39753static bool setCategoryEnable(const char* name, bool enable)
754{
Elliott Hughes5fd6ff62017-03-28 21:55:31755 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 10:20:39756 const TracingCategory& c = k_categories[i];
757 if (strcmp(name, c.name) == 0) {
758 if (isCategorySupported(c)) {
759 g_categoryEnables[i] = enable;
760 return true;
761 } else {
762 if (isCategorySupportedForRoot(c)) {
763 fprintf(stderr, "error: category \"%s\" requires root "
764 "privileges.\n", name);
765 } else {
766 fprintf(stderr, "error: category \"%s\" is not supported "
767 "on this device.\n", name);
768 }
769 return false;
770 }
771 }
772 }
773 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
774 return false;
775}
776
777static bool setCategoriesEnableFromFile(const char* categories_file)
778{
779 if (!categories_file) {
780 return true;
781 }
782 Tokenizer* tokenizer = NULL;
783 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
784 return false;
785 }
786 bool ok = true;
787 while (!tokenizer->isEol()) {
788 String8 token = tokenizer->nextToken(" ");
789 if (token.isEmpty()) {
790 tokenizer->skipDelimiters(" ");
791 continue;
792 }
793 ok &= setCategoryEnable(token.string(), true);
794 }
795 delete tokenizer;
796 return ok;
797}
798
Hector Dearman11845782018-03-08 14:35:44799static bool setUpUserspaceTracing()
Jamie Gennis6eea6fb2012-12-07 22:03:07800{
801 bool ok = true;
802
Jamie Gennis6eea6fb2012-12-07 22:03:07803 // Set up the tags property.
804 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 21:55:31805 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 22:03:07806 if (g_categoryEnables[i]) {
807 const TracingCategory &c = k_categories[i];
808 tags |= c.tags;
809 }
810 }
811 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-03 02:26:07812
813 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 21:55:31814 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-03 02:26:07815 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
816 coreServicesTagEnabled = g_categoryEnables[i];
817 }
Corey Tabakaa6c0a722017-05-31 23:37:40818
819 // Set whether to poke PDX services in this session.
820 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
821 g_tracePdx = g_categoryEnables[i];
822 }
sergeyvdb404152016-05-03 02:26:07823 }
824
825 std::string packageList(g_debugAppCmdLine);
826 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-03 02:26:07827 if (!packageList.empty()) {
828 packageList += ",";
829 }
Elliott Hughes5fd6ff62017-03-28 21:55:31830 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-03 02:26:07831 }
Dan Austin09a79872016-05-31 20:27:03832 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 22:50:58833 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 15:00:26834 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 22:03:07835
Corey Tabakaa6c0a722017-05-31 23:37:40836 if (g_tracePdx) {
837 ok &= ServiceUtility::PokeServices();
838 }
839
Hector Dearman11845782018-03-08 14:35:44840 return ok;
841}
842
843static void cleanUpUserspaceTracing()
844{
845 setTagsProperty(0);
846 clearAppProperties();
847 pokeBinderServices();
848
849 if (g_tracePdx) {
850 ServiceUtility::PokeServices();
851 }
852}
853
854
855// Set all the kernel tracing settings to the desired state for this trace
856// capture.
857static bool setUpKernelTracing()
858{
859 bool ok = true;
860
Carmen Jacksonab1118e2018-05-22 17:29:47861 ok &= setUserInitiatedTraceProperty(true);
862
Hector Dearman11845782018-03-08 14:35:44863 // Set up the tracing options.
864 ok &= setCategoriesEnableFromFile(g_categoriesFile);
865 ok &= setTraceOverwriteEnable(g_traceOverwrite);
866 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
867 // TODO: Re-enable after stabilization
868 //ok &= setCmdlineSize();
869 ok &= setClock();
870 ok &= setPrintTgidEnableIfPresent(true);
871 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
872
Jamie Gennis6eea6fb2012-12-07 22:03:07873 // Disable all the sysfs enables. This is done as a separate loop from
874 // the enables to allow the same enable to exist in multiple categories.
875 ok &= disableKernelTraceEvents();
876
877 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 21:55:31878 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 22:03:07879 if (g_categoryEnables[i]) {
880 const TracingCategory &c = k_categories[i];
881 for (int j = 0; j < MAX_SYS_FILES; j++) {
882 const char* path = c.sysfiles[j].path;
883 bool required = c.sysfiles[j].required == REQ;
884 if (path != NULL) {
885 if (fileIsWritable(path)) {
886 ok &= setKernelOptionEnable(path, true);
887 } else if (required) {
888 fprintf(stderr, "error writing file %s\n", path);
889 ok = false;
890 }
891 }
892 }
893 }
894 }
895
Jamie Gennis6eea6fb2012-12-07 22:03:07896 return ok;
897}
898
Jamie Gennise9b8cfb2013-03-12 23:00:10899// Reset all the kernel tracing settings to their default state.
Hector Dearman11845782018-03-08 14:35:44900static void cleanUpKernelTracing()
Jamie Gennis6eea6fb2012-12-07 22:03:07901{
Jamie Gennis6eea6fb2012-12-07 22:03:07902 // Disable all tracing that we're able to.
903 disableKernelTraceEvents();
904
Jamie Gennis6eea6fb2012-12-07 22:03:07905 // Set the options back to their defaults.
906 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 23:00:10907 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 23:00:10908 setPrintTgidEnableIfPresent(false);
909 setKernelTraceFuncs(NULL);
Carmen Jacksonab1118e2018-05-22 17:29:47910 setUserInitiatedTraceProperty(false);
Jamie Gennise9b8cfb2013-03-12 23:00:10911}
Jamie Gennis6eea6fb2012-12-07 22:03:07912
Jamie Gennise9b8cfb2013-03-12 23:00:10913// Enable tracing in the kernel.
914static bool startTrace()
915{
916 return setTracingEnabled(true);
917}
918
919// Disable tracing in the kernel.
920static void stopTrace()
921{
922 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 22:03:07923}
924
Martijn Coenend9535872015-11-26 09:00:55925// Read data from the tracing pipe and forward to stdout
926static void streamTrace()
927{
928 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 17:50:18929 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 09:00:55930 if (traceFD == -1) {
931 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
932 strerror(errno), errno);
933 return;
934 }
935 while (!g_traceAborted) {
936 ssize_t bytes_read = read(traceFD, trace_data, 4096);
937 if (bytes_read > 0) {
938 write(STDOUT_FILENO, trace_data, bytes_read);
939 fflush(stdout);
940 } else {
941 if (!g_traceAborted) {
942 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
943 bytes_read, errno, strerror(errno));
944 }
945 break;
946 }
947 }
948}
949
Jamie Gennis6eea6fb2012-12-07 22:03:07950// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 16:44:36951static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 22:03:07952{
John Reck6c8ac922016-03-28 18:25:30953 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 17:50:18954 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 22:03:07955 if (traceFD == -1) {
956 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
957 strerror(errno), errno);
958 return;
959 }
960
961 if (g_compress) {
962 z_stream zs;
Elliott Hughes3da5d232015-01-25 16:35:20963 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-22 00:12:15964
965 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 22:03:07966 if (result != Z_OK) {
967 fprintf(stderr, "error initializing zlib: %d\n", result);
968 close(traceFD);
969 return;
970 }
971
Elliott Hughesa252f4d2016-07-22 00:12:15972 constexpr size_t bufSize = 64*1024;
973 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
974 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
975 if (!in || !out) {
976 fprintf(stderr, "couldn't allocate buffers\n");
977 close(traceFD);
978 return;
979 }
Jamie Gennis6eea6fb2012-12-07 22:03:07980
Elliott Hughesa252f4d2016-07-22 00:12:15981 int flush = Z_NO_FLUSH;
982
983 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 22:03:07984 zs.avail_out = bufSize;
985
986 do {
987
988 if (zs.avail_in == 0) {
989 // More input is needed.
Elliott Hughesa252f4d2016-07-22 00:12:15990 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 22:03:07991 if (result < 0) {
992 fprintf(stderr, "error reading trace: %s (%d)\n",
993 strerror(errno), errno);
994 result = Z_STREAM_END;
995 break;
996 } else if (result == 0) {
997 flush = Z_FINISH;
998 } else {
Elliott Hughesa252f4d2016-07-22 00:12:15999 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 22:03:071000 zs.avail_in = result;
1001 }
1002 }
1003
1004 if (zs.avail_out == 0) {
1005 // Need to write the output.
Elliott Hughesb59e2962016-07-22 16:00:591006 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 22:03:071007 if ((size_t)result < bufSize) {
1008 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1009 strerror(errno), errno);
1010 result = Z_STREAM_END; // skip deflate error message
1011 zs.avail_out = bufSize; // skip the final write
1012 break;
1013 }
Elliott Hughesa252f4d2016-07-22 00:12:151014 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 22:03:071015 zs.avail_out = bufSize;
1016 }
1017
1018 } while ((result = deflate(&zs, flush)) == Z_OK);
1019
1020 if (result != Z_STREAM_END) {
1021 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
1022 }
1023
1024 if (zs.avail_out < bufSize) {
1025 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 16:00:591026 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 22:03:071027 if ((size_t)result < bytes) {
1028 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1029 strerror(errno), errno);
1030 }
1031 }
1032
1033 result = deflateEnd(&zs);
1034 if (result != Z_OK) {
1035 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1036 }
Jamie Gennis6eea6fb2012-12-07 22:03:071037 } else {
Josh Gaod3d36e72017-04-11 22:21:131038 char buf[4096];
1039 ssize_t rc;
1040 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1041 if (!android::base::WriteFully(outFd, buf, rc)) {
1042 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1043 break;
1044 }
1045 }
1046 if (rc == -1) {
1047 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 22:03:071048 }
1049 }
1050
1051 close(traceFD);
1052}
1053
Mark Salyzyn92dc3fc2014-03-12 20:12:441054static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 22:03:071055{
1056 if (!g_nohup) {
1057 g_traceAborted = true;
1058 }
1059}
1060
1061static void registerSigHandler()
1062{
1063 struct sigaction sa;
1064 sigemptyset(&sa.sa_mask);
1065 sa.sa_flags = 0;
1066 sa.sa_handler = handleSignal;
1067 sigaction(SIGHUP, &sa, NULL);
1068 sigaction(SIGINT, &sa, NULL);
1069 sigaction(SIGQUIT, &sa, NULL);
1070 sigaction(SIGTERM, &sa, NULL);
1071}
1072
Jamie Gennis6eea6fb2012-12-07 22:03:071073static void listSupportedCategories()
1074{
Elliott Hughes5fd6ff62017-03-28 21:55:311075 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 22:03:071076 const TracingCategory& c = k_categories[i];
1077 if (isCategorySupported(c)) {
1078 printf(" %10s - %s\n", c.name, c.longname);
1079 }
1080 }
1081}
1082
1083// Print the command usage help to stderr.
1084static void showHelp(const char *cmd)
1085{
1086 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1087 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 22:50:581088 " -a appname enable app-level tracing for a comma "
Daniel Colascione519a0792018-02-10 04:05:391089 "separated list of cmdlines; * is a wildcard matching any process\n"
Jamie Gennis6eea6fb2012-12-07 22:03:071090 " -b N use a trace buffer size of N KB\n"
1091 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 10:20:391092 " -f filename use the categories written in a file as space-separated\n"
1093 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 23:00:101094 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 22:03:071095 " -n ignore signals\n"
1096 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 18:40:121097 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 22:03:071098 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 18:40:121099 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 22:03:071100 " --async_dump dump the current contents of circular trace buffer\n"
1101 " --async_stop stop tracing and dump the current contents of circular\n"
1102 " trace buffer\n"
Martijn Coenend9535872015-11-26 09:00:551103 " --stream stream trace to stdout as it enters the trace buffer\n"
1104 " Note: this can take significant CPU time, and is best\n"
1105 " used for measuring things that are not affected by\n"
1106 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-08 00:29:031107 " --list_categories\n"
1108 " list the available tracing categories\n"
John Reck40b26b42016-03-30 16:44:361109 " -o filename write the trace to the specified file instead\n"
1110 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 22:03:071111 );
1112}
1113
Paul Lawrence2cd93cc2017-01-17 17:50:181114bool findTraceFiles()
1115{
1116 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1117 static const std::string tracefs_path = "/sys/kernel/tracing/";
1118 static const std::string trace_file = "trace_marker";
1119
1120 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1121 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1122
1123 if (!tracefs && !debugfs) {
1124 fprintf(stderr, "Error: Did not find trace folder\n");
1125 return false;
1126 }
1127
1128 if (tracefs) {
1129 g_traceFolder = tracefs_path;
1130 } else {
1131 g_traceFolder = debugfs_path;
1132 }
1133
1134 return true;
1135}
1136
Jamie Gennis6eea6fb2012-12-07 22:03:071137int main(int argc, char **argv)
1138{
1139 bool async = false;
1140 bool traceStart = true;
1141 bool traceStop = true;
1142 bool traceDump = true;
Martijn Coenend9535872015-11-26 09:00:551143 bool traceStream = false;
Hector Dearman11845782018-03-08 14:35:441144 bool onlyUserspace = false;
Jamie Gennis6eea6fb2012-12-07 22:03:071145
1146 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1147 showHelp(argv[0]);
1148 exit(0);
1149 }
1150
Paul Lawrence2cd93cc2017-01-17 17:50:181151 if (!findTraceFiles()) {
1152 fprintf(stderr, "No trace folder found\n");
1153 exit(-1);
1154 }
1155
Jamie Gennis6eea6fb2012-12-07 22:03:071156 for (;;) {
1157 int ret;
1158 int option_index = 0;
1159 static struct option long_options[] = {
Hector Dearman11845782018-03-08 14:35:441160 {"async_start", no_argument, 0, 0 },
1161 {"async_stop", no_argument, 0, 0 },
1162 {"async_dump", no_argument, 0, 0 },
1163 {"only_userspace", no_argument, 0, 0 },
1164 {"list_categories", no_argument, 0, 0 },
1165 {"stream", no_argument, 0, 0 },
1166 { 0, 0, 0, 0 }
Jamie Gennis6eea6fb2012-12-07 22:03:071167 };
1168
John Reck40b26b42016-03-30 16:44:361169 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 22:03:071170 long_options, &option_index);
1171
1172 if (ret < 0) {
1173 for (int i = optind; i < argc; i++) {
1174 if (!setCategoryEnable(argv[i], true)) {
1175 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1176 exit(1);
1177 }
1178 }
1179 break;
1180 }
1181
1182 switch(ret) {
Jamie Gennisf7f29c82013-03-27 22:50:581183 case 'a':
1184 g_debugAppCmdLine = optarg;
1185 break;
1186
Jamie Gennis6eea6fb2012-12-07 22:03:071187 case 'b':
1188 g_traceBufferSizeKB = atoi(optarg);
1189 break;
1190
1191 case 'c':
1192 g_traceOverwrite = true;
1193 break;
1194
Yasuhiro Matsuda46c51fb2015-06-29 10:20:391195 case 'f':
1196 g_categoriesFile = optarg;
1197 break;
1198
Jamie Gennise9b8cfb2013-03-12 23:00:101199 case 'k':
1200 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 22:50:301201 break;
Jamie Gennise9b8cfb2013-03-12 23:00:101202
Jamie Gennis6eea6fb2012-12-07 22:03:071203 case 'n':
1204 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 22:50:301205 break;
Jamie Gennis6eea6fb2012-12-07 22:03:071206
1207 case 's':
1208 g_initialSleepSecs = atoi(optarg);
1209 break;
1210
1211 case 't':
1212 g_traceDurationSeconds = atoi(optarg);
1213 break;
1214
1215 case 'z':
1216 g_compress = true;
1217 break;
1218
John Reck40b26b42016-03-30 16:44:361219 case 'o':
1220 g_outputFile = optarg;
1221 break;
1222
Jamie Gennis6eea6fb2012-12-07 22:03:071223 case 0:
1224 if (!strcmp(long_options[option_index].name, "async_start")) {
1225 async = true;
1226 traceStop = false;
1227 traceDump = false;
1228 g_traceOverwrite = true;
1229 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1230 async = true;
John Reck4ba2b632015-05-15 17:00:341231 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 22:03:071232 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1233 async = true;
1234 traceStart = false;
1235 traceStop = false;
Hector Dearman11845782018-03-08 14:35:441236 } else if (!strcmp(long_options[option_index].name, "only_userspace")) {
1237 onlyUserspace = true;
Martijn Coenend9535872015-11-26 09:00:551238 } else if (!strcmp(long_options[option_index].name, "stream")) {
1239 traceStream = true;
1240 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 22:03:071241 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1242 listSupportedCategories();
1243 exit(0);
1244 }
Jamie Gennis6f6f3f72013-03-27 22:50:301245 break;
Jamie Gennis6eea6fb2012-12-07 22:03:071246
1247 default:
1248 fprintf(stderr, "\n");
1249 showHelp(argv[0]);
1250 exit(-1);
1251 break;
1252 }
1253 }
1254
Hector Dearman11845782018-03-08 14:35:441255 if (onlyUserspace) {
1256 if (!async || !(traceStart || traceStop)) {
1257 fprintf(stderr, "--only_userspace can only be used with "
1258 "--async_start or --async_stop\n");
1259 exit(1);
1260 }
1261 }
1262
Jamie Gennis6eea6fb2012-12-07 22:03:071263 registerSigHandler();
1264
1265 if (g_initialSleepSecs > 0) {
1266 sleep(g_initialSleepSecs);
1267 }
1268
Jamie Gennise9b8cfb2013-03-12 23:00:101269 bool ok = true;
Hector Dearman11845782018-03-08 14:35:441270
Wei Wang5b73b742018-03-08 21:33:121271 if (traceStart) {
Hector Dearman11845782018-03-08 14:35:441272 ok &= setUpUserspaceTracing();
1273 }
1274
1275 if (ok && traceStart && !onlyUserspace) {
1276 ok &= setUpKernelTracing();
Wei Wang5b73b742018-03-08 21:33:121277 ok &= startTrace();
1278 }
Jamie Gennis6eea6fb2012-12-07 22:03:071279
1280 if (ok && traceStart) {
Hector Dearman11845782018-03-08 14:35:441281
1282 if (!traceStream && !onlyUserspace) {
Carmen Jacksonac53e732017-05-02 23:55:331283 printf("capturing trace...");
Martijn Coenend9535872015-11-26 09:00:551284 fflush(stdout);
1285 }
Jamie Gennis6eea6fb2012-12-07 22:03:071286
1287 // We clear the trace after starting it because tracing gets enabled for
1288 // each CPU individually in the kernel. Having the beginning of the trace
1289 // contain entries from only one CPU can cause "begin" entries without a
1290 // matching "end" entry to show up if a task gets migrated from one CPU to
1291 // another.
Hector Dearman11845782018-03-08 14:35:441292 if (!onlyUserspace)
1293 ok = clearTrace();
Jamie Gennis6eea6fb2012-12-07 22:03:071294
Martijn Coenen0bcd97a2015-07-15 12:25:231295 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 09:00:551296 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 22:03:071297 // Sleep to allow the trace to be captured.
1298 struct timespec timeLeft;
1299 timeLeft.tv_sec = g_traceDurationSeconds;
1300 timeLeft.tv_nsec = 0;
1301 do {
1302 if (g_traceAborted) {
1303 break;
1304 }
1305 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1306 }
Martijn Coenend9535872015-11-26 09:00:551307
1308 if (traceStream) {
1309 streamTrace();
1310 }
Jamie Gennis6eea6fb2012-12-07 22:03:071311 }
1312
1313 // Stop the trace and restore the default settings.
Hector Dearman11845782018-03-08 14:35:441314 if (traceStop && !onlyUserspace)
Jamie Gennis6eea6fb2012-12-07 22:03:071315 stopTrace();
1316
Hector Dearman11845782018-03-08 14:35:441317 if (ok && traceDump && !onlyUserspace) {
Jamie Gennis6eea6fb2012-12-07 22:03:071318 if (!g_traceAborted) {
John Reck40b26b42016-03-30 16:44:361319 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 22:03:071320 fflush(stdout);
John Reck40b26b42016-03-30 16:44:361321 int outFd = STDOUT_FILENO;
1322 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 08:25:311323 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 16:44:361324 }
1325 if (outFd == -1) {
1326 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1327 } else {
1328 dprintf(outFd, "TRACE:\n");
1329 dumpTrace(outFd);
1330 if (g_outputFile) {
1331 close(outFd);
1332 }
1333 }
Jamie Gennis6eea6fb2012-12-07 22:03:071334 } else {
1335 printf("\ntrace aborted.\n");
1336 fflush(stdout);
1337 }
1338 clearTrace();
1339 } else if (!ok) {
1340 fprintf(stderr, "unable to start tracing\n");
1341 }
1342
1343 // Reset the trace buffer size to 1.
Hector Dearman11845782018-03-08 14:35:441344 if (traceStop) {
1345 cleanUpUserspaceTracing();
1346 if (!onlyUserspace)
1347 cleanUpKernelTracing();
1348 }
Jamie Gennis6eea6fb2012-12-07 22:03:071349
1350 return g_traceAborted ? 1 : 0;
1351}