blob: a478d4c123e64767eb7d7dab9c417fb15db73428 [file] [log] [blame]
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Paul Lawrence2cd93cc2017-01-17 09:50:18 -080017#define LOG_TAG "atrace"
John Reck40b26b42016-03-30 09:44:36 -070018
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080019#include <errno.h>
20#include <fcntl.h>
21#include <getopt.h>
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070022#include <inttypes.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080023#include <signal.h>
24#include <stdarg.h>
25#include <stdbool.h>
26#include <stdio.h>
27#include <stdlib.h>
Elliott Hughes3da5d232015-01-25 08:35:20 -080028#include <string.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080029#include <time.h>
Martijn Coenend9535872015-11-26 10:00:55 +010030#include <unistd.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080031#include <zlib.h>
32
Carmen Jacksonea826792017-05-05 11:42:32 -070033#include <fstream>
Elliott Hughesa252f4d2016-07-21 17:12:15 -070034#include <memory>
35
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080036#include <binder/IBinder.h>
37#include <binder/IServiceManager.h>
38#include <binder/Parcel.h>
39
Martijn Coenenee9b97e2016-11-16 16:00:26 +010040#include <android/hidl/manager/1.0/IServiceManager.h>
41#include <hidl/ServiceManagement.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080042
Corey Tabakaa6c0a722017-05-31 16:37:40 -070043#include <pdx/default_transport/service_utility.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080044#include <utils/String8.h>
John Reck469a1942015-03-26 15:31:35 -070045#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +090046#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080047#include <utils/Trace.h>
Stephane Gasparinid8419c22016-03-02 13:45:15 +010048#include <android-base/file.h>
Elliott Hughes5fd6ff62017-03-28 14:55:31 -070049#include <android-base/macros.h>
50#include <android-base/properties.h>
51#include <android-base/stringprintf.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080052
53using namespace android;
Corey Tabakaa6c0a722017-05-31 16:37:40 -070054using pdx::default_transport::ServiceUtility;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080055
Martijn Coenenee9b97e2016-11-16 16:00:26 +010056using std::string;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080057
sergeyv4144eff2016-04-28 11:40:04 -070058#define MAX_SYS_FILES 10
59#define MAX_PACKAGES 16
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080060
61const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
sergeyv4144eff2016-04-28 11:40:04 -070062
63const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
64const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070065const char* k_coreServiceCategory = "core_services";
Corey Tabakaa6c0a722017-05-31 16:37:40 -070066const char* k_pdxServiceCategory = "pdx";
sergeyvdb404152016-05-02 19:26:07 -070067const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080068
69typedef enum { OPT, REQ } requiredness ;
70
71struct TracingCategory {
72 // The name identifying the category.
73 const char* name;
74
75 // A longer description of the category.
76 const char* longname;
77
78 // The userland tracing tags that the category enables.
79 uint64_t tags;
80
81 // The fname==NULL terminated list of /sys/ files that the category
82 // enables.
83 struct {
84 // Whether the file must be writable in order to enable the tracing
85 // category.
86 requiredness required;
87
88 // The path to the enable file.
89 const char* path;
90 } sysfiles[MAX_SYS_FILES];
91};
92
93/* Tracing categories */
94static const TracingCategory k_categories[] = {
John Reck732a29a2017-05-24 16:09:21 -070095 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, {
96 { OPT, "events/mdss/enable" },
97 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070098 { "input", "Input", ATRACE_TAG_INPUT, { } },
99 { "view", "View System", ATRACE_TAG_VIEW, { } },
100 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
101 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
102 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -0500103 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700104 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
105 { "video", "Video", ATRACE_TAG_VIDEO, { } },
106 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
107 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700108 { "app", "Application", ATRACE_TAG_APP, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -0700109 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -0700110 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -0700111 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -0700112 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700113 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 14:36:20 -0700114 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-07-01 01:46:25 +0900115 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Greg Hackmannbbd7d992014-12-01 14:43:34 -0800116 { "database", "Database", ATRACE_TAG_DATABASE, { } },
Felipe Leme0f97c1d2016-09-07 11:33:26 -0700117 { "network", "Network", ATRACE_TAG_NETWORK, { } },
Josh Gao468b4cb2016-11-29 10:55:21 -0800118 { "adb", "ADB", ATRACE_TAG_ADB, { } },
sergeyvdb404152016-05-02 19:26:07 -0700119 { k_coreServiceCategory, "Core services", 0, { } },
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700120 { k_pdxServiceCategory, "PDX services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700121 { "sched", "CPU Scheduling", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800122 { REQ, "events/sched/sched_switch/enable" },
123 { REQ, "events/sched/sched_wakeup/enable" },
Joel Fernandesee593e22017-06-04 13:05:59 -0700124 { OPT, "events/sched/sched_waking/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800125 { OPT, "events/sched/sched_blocked_reason/enable" },
126 { OPT, "events/sched/sched_cpu_hotplug/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800127 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700128 { "irq", "IRQ Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800129 { REQ, "events/irq/enable" },
130 { OPT, "events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700131 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100132 { "i2c", "I2C Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800133 { REQ, "events/i2c/enable" },
134 { REQ, "events/i2c/i2c_read/enable" },
135 { REQ, "events/i2c/i2c_write/enable" },
136 { REQ, "events/i2c/i2c_result/enable" },
137 { REQ, "events/i2c/i2c_reply/enable" },
138 { OPT, "events/i2c/smbus_read/enable" },
139 { OPT, "events/i2c/smbus_write/enable" },
140 { OPT, "events/i2c/smbus_result/enable" },
141 { OPT, "events/i2c/smbus_reply/enable" },
Michael Wright43fb6782016-08-18 19:56:43 +0100142 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700143 { "freq", "CPU Frequency", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800144 { REQ, "events/power/cpu_frequency/enable" },
145 { OPT, "events/power/clock_set_rate/enable" },
146 { OPT, "events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800147 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700148 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800149 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800150 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700151 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800152 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800153 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700154 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800155 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
156 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
157 { OPT, "events/f2fs/f2fs_write_begin/enable" },
158 { OPT, "events/f2fs/f2fs_write_end/enable" },
159 { OPT, "events/ext4/ext4_da_write_begin/enable" },
160 { OPT, "events/ext4/ext4_da_write_end/enable" },
161 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
162 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
163 { REQ, "events/block/block_rq_issue/enable" },
164 { REQ, "events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800165 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700166 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800167 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700168 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700169 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800170 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800171 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700172 { "sync", "Synchronization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800173 { REQ, "events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800174 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700175 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800176 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800177 } },
Colin Cross580407f2014-08-18 15:22:13 -0700178 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800179 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
180 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
181 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
182 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Marc Hittingerf1f62e32017-05-17 15:57:43 -0700183 { REQ, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700184 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800185 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800186 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800187 } },
Scott Bauerae473362015-06-08 16:32:36 -0700188 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800189 { REQ, "events/binder/binder_transaction/enable" },
190 { REQ, "events/binder/binder_transaction_received/enable" },
Martijn Coenen7f3d7a22017-05-26 09:50:55 -0700191 { OPT, "events/binder/binder_set_priority/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700192 } },
193 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800194 { OPT, "events/binder/binder_lock/enable" },
195 { OPT, "events/binder/binder_locked/enable" },
196 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700197 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200198 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800199 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200200 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800201};
202
203/* Command line options */
204static int g_traceDurationSeconds = 5;
205static bool g_traceOverwrite = false;
206static int g_traceBufferSizeKB = 2048;
207static bool g_compress = false;
208static bool g_nohup = false;
209static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900210static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700211static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700212static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700213static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800214
215/* Global state */
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700216static bool g_tracePdx = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800217static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700218static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800219static std::string g_traceFolder;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800220
221/* Sys file paths */
222static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800223 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800224
225static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800226 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800227
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700228#if 0
229// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700230static const char* k_traceCmdlineSizePath =
231 "saved_cmdlines_size";
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700232#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700233
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800234static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800235 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800236
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700237static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800238 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700239
240static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800241 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700242
243static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800244 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700245
246static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800247 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700248
249static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800250 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700251
252static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800253 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700254
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700255static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800256 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700257
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800258static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800259 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800260
261static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800262 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800263
Martijn Coenend9535872015-11-26 10:00:55 +0100264static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800265 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100266
John Reck469a1942015-03-26 15:31:35 -0700267static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800268 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700269
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800270// Check whether a file exists.
271static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800272 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800273}
274
275// Check whether a file is writable.
276static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800277 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800278}
279
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700280// Truncate a file.
281static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800282{
Jamie Gennis43122e72013-03-21 14:06:31 -0700283 // This uses creat rather than truncate because some of the debug kernel
284 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
285 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800286 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700287 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800288 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700289 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700290 return false;
291 }
292
Jamie Gennis43122e72013-03-21 14:06:31 -0700293 close(traceFD);
294
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700295 return true;
296}
297
298static bool _writeStr(const char* filename, const char* str, int flags)
299{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800300 std::string fullFilename = g_traceFolder + filename;
301 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800302 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800303 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800304 strerror(errno), errno);
305 return false;
306 }
307
308 bool ok = true;
309 ssize_t len = strlen(str);
310 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800311 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800312 strerror(errno), errno);
313 ok = false;
314 }
315
316 close(fd);
317
318 return ok;
319}
320
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700321// Write a string to a file, returning true if the write was successful.
322static bool writeStr(const char* filename, const char* str)
323{
324 return _writeStr(filename, str, O_WRONLY);
325}
326
327// Append a string to a file, returning true if the write was successful.
328static bool appendStr(const char* filename, const char* str)
329{
330 return _writeStr(filename, str, O_APPEND|O_WRONLY);
331}
332
John Reck469a1942015-03-26 15:31:35 -0700333static void writeClockSyncMarker()
334{
335 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200336 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800337 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200338 if (fd == -1) {
339 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
340 strerror(errno), errno);
341 return;
342 }
John Reck469a1942015-03-26 15:31:35 -0700343 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200344
345 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
346 if (write(fd, buffer, len) != len) {
347 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
348 }
349
350 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
351 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
352 if (write(fd, buffer, len) != len) {
353 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
354 }
355
356 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700357}
358
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800359// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
360// file.
361static bool setKernelOptionEnable(const char* filename, bool enable)
362{
363 return writeStr(filename, enable ? "1" : "0");
364}
365
366// Check whether the category is supported on the device with the current
367// rootness. A category is supported only if all its required /sys/ files are
368// writable and if enabling the category will enable one or more tracing tags
369// or /sys/ files.
370static bool isCategorySupported(const TracingCategory& category)
371{
sergeyvdb404152016-05-02 19:26:07 -0700372 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700373 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700374 }
375
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700376 if (strcmp(category.name, k_pdxServiceCategory) == 0) {
377 return true;
378 }
379
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800380 bool ok = category.tags != 0;
381 for (int i = 0; i < MAX_SYS_FILES; i++) {
382 const char* path = category.sysfiles[i].path;
383 bool req = category.sysfiles[i].required == REQ;
384 if (path != NULL) {
385 if (req) {
386 if (!fileIsWritable(path)) {
387 return false;
388 } else {
389 ok = true;
390 }
391 } else {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800392 ok = true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800393 }
394 }
395 }
396 return ok;
397}
398
399// Check whether the category would be supported on the device if the user
400// were root. This function assumes that root is able to write to any file
401// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700402// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800403static bool isCategorySupportedForRoot(const TracingCategory& category)
404{
405 bool ok = category.tags != 0;
406 for (int i = 0; i < MAX_SYS_FILES; i++) {
407 const char* path = category.sysfiles[i].path;
408 bool req = category.sysfiles[i].required == REQ;
409 if (path != NULL) {
410 if (req) {
411 if (!fileExists(path)) {
412 return false;
413 } else {
414 ok = true;
415 }
416 } else {
417 ok |= fileExists(path);
418 }
419 }
420 }
421 return ok;
422}
423
424// Enable or disable overwriting of the kernel trace buffers. Disabling this
425// will cause tracing to stop once the trace buffers have filled up.
426static bool setTraceOverwriteEnable(bool enable)
427{
428 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
429}
430
431// Enable or disable kernel tracing.
432static bool setTracingEnabled(bool enable)
433{
434 return setKernelOptionEnable(k_tracingOnPath, enable);
435}
436
437// Clear the contents of the kernel trace.
438static bool clearTrace()
439{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700440 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800441}
442
443// Set the size of the kernel's trace buffer in kilobytes.
444static bool setTraceBufferSizeKB(int size)
445{
446 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800447 if (size < 1) {
448 size = 1;
449 }
450 snprintf(str, 32, "%d", size);
451 return writeStr(k_traceBufferSizePath, str);
452}
453
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700454#if 0
455// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700456// Set the default size of cmdline hashtable
457static bool setCmdlineSize()
458{
Joel Fernandesce964f22017-06-06 12:20:29 -0700459 if (fileExists(k_traceCmdlineSizePath)) {
460 return writeStr(k_traceCmdlineSizePath, "8192");
461 }
462 return true;
Joel Fernandesed80bd02017-06-02 10:19:28 -0700463}
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700464#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700465
Carmen Jacksonea826792017-05-05 11:42:32 -0700466// Set the clock to the best available option while tracing. Use 'boot' if it's
467// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700468// Any write to the trace_clock sysfs file will reset the buffer, so only
469// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700470static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800471{
Carmen Jacksonea826792017-05-05 11:42:32 -0700472 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
473 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
474 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700475
Carmen Jacksonea826792017-05-05 11:42:32 -0700476 std::string newClock;
477 if (clockStr.find("boot") != std::string::npos) {
478 newClock = "boot";
479 } else if (clockStr.find("mono") != std::string::npos) {
480 newClock = "mono";
481 } else {
482 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700483 }
484
Chih-Hung Hsieh0e1f4ce2017-08-03 15:48:25 -0700485 size_t begin = clockStr.find('[') + 1;
486 size_t end = clockStr.find(']');
Carmen Jacksonea826792017-05-05 11:42:32 -0700487 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
488 return true;
489 }
490 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800491}
492
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700493static bool setPrintTgidEnableIfPresent(bool enable)
494{
495 if (fileExists(k_printTgidPath)) {
496 return setKernelOptionEnable(k_printTgidPath, enable);
497 }
498 return true;
499}
500
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800501// Poke all the binder-enabled processes in the system to get them to re-read
502// their system properties.
503static bool pokeBinderServices()
504{
505 sp<IServiceManager> sm = defaultServiceManager();
506 Vector<String16> services = sm->listServices();
507 for (size_t i = 0; i < services.size(); i++) {
508 sp<IBinder> obj = sm->checkService(services[i]);
509 if (obj != NULL) {
510 Parcel data;
511 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
512 NULL, 0) != OK) {
513 if (false) {
514 // XXX: For some reason this fails on tablets trying to
515 // poke the "phone" service. It's not clear whether some
516 // are expected to fail.
517 String8 svc(services[i]);
518 fprintf(stderr, "error poking binder service %s\n",
519 svc.string());
520 return false;
521 }
522 }
523 }
524 }
525 return true;
526}
527
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100528// Poke all the HAL processes in the system to get them to re-read
529// their system properties.
530static void pokeHalServices()
531{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100532 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100533 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100534 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100535 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100536
537 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800538
539 if (sm == nullptr) {
540 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
541 return;
542 }
543
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800544 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100545 for (size_t i = 0; i < interfaces.size(); i++) {
546 string fqInstanceName = interfaces[i];
Chih-Hung Hsieh0e1f4ce2017-08-03 15:48:25 -0700547 string::size_type n = fqInstanceName.find('/');
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100548 if (n == std::string::npos || interfaces[i].size() == n+1)
549 continue;
550 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
551 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100552 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
553 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100554 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100555 continue;
556 }
Carmen Jackson73206122017-04-18 15:37:57 -0700557
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100558 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700559 if (interface == nullptr) {
560 // ignore
561 continue;
562 }
563
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100564 auto notifyRet = interface->notifySyspropsChanged();
565 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100566 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800567 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100568 }
569 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800570 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100571 // TODO(b/34242478) fix this when we determine the correct ACL
572 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800573 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100574}
575
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800576// Set the trace tags that userland tracing uses, and poke the running
577// processes to pick up the new value.
578static bool setTagsProperty(uint64_t tags)
579{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700580 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
581 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800582 fprintf(stderr, "error setting trace tags system property\n");
583 return false;
584 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700585 return true;
586}
587
sergeyv4144eff2016-04-28 11:40:04 -0700588static void clearAppProperties()
589{
sergeyv4144eff2016-04-28 11:40:04 -0700590 for (int i = 0; i < MAX_PACKAGES; i++) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700591 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
592 if (!android::base::SetProperty(key, "")) {
593 fprintf(stderr, "failed to clear system property: %s\n", key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700594 }
595 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700596 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700597 fprintf(stderr, "failed to clear system property: %s",
598 k_traceAppsNumberProperty);
599 }
600}
601
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700602// Set the system property that indicates which apps should perform
603// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700604static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700605{
sergeyv4144eff2016-04-28 11:40:04 -0700606 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700607 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700608 while (start != NULL) {
609 if (i == MAX_PACKAGES) {
610 fprintf(stderr, "error: only 16 packages could be traced at once\n");
611 clearAppProperties();
612 return false;
613 }
614 char* end = strchr(start, ',');
615 if (end != NULL) {
616 *end = '\0';
617 end++;
618 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700619 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
620 if (!android::base::SetProperty(key, start)) {
621 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700622 clearAppProperties();
623 return false;
624 }
625 start = end;
626 i++;
627 }
628
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700629 std::string value = android::base::StringPrintf("%d", i);
630 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
631 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700632 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700633 return false;
634 }
635 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800636}
637
638// Disable all /sys/ enable files.
639static bool disableKernelTraceEvents() {
640 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700641 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800642 const TracingCategory &c = k_categories[i];
643 for (int j = 0; j < MAX_SYS_FILES; j++) {
644 const char* path = c.sysfiles[j].path;
645 if (path != NULL && fileIsWritable(path)) {
646 ok &= setKernelOptionEnable(path, false);
647 }
648 }
649 }
650 return ok;
651}
652
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700653// Verify that the comma separated list of functions are being traced by the
654// kernel.
655static bool verifyKernelTraceFuncs(const char* funcs)
656{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100657 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800658 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100659 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700660 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100661 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700662 }
663
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100664 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700665
666 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100667 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700668 bool ok = true;
669 char* myFuncs = strdup(funcs);
670 char* func = strtok(myFuncs, ",");
671 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100672 if (!strchr(func, '*')) {
673 String8 fancyFunc = String8::format("\n%s\n", func);
674 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
675 if (!found || func[0] == '\0') {
676 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
677 "to trace.\n", func);
678 ok = false;
679 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700680 }
681 func = strtok(NULL, ",");
682 }
683 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700684 return ok;
685}
686
687// Set the comma separated list of functions that the kernel is to trace.
688static bool setKernelTraceFuncs(const char* funcs)
689{
690 bool ok = true;
691
692 if (funcs == NULL || funcs[0] == '\0') {
693 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700694 if (fileIsWritable(k_currentTracerPath)) {
695 ok &= writeStr(k_currentTracerPath, "nop");
696 }
697 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700698 ok &= truncateFile(k_ftraceFilterPath);
699 }
700 } else {
701 // Enable kernel function tracing.
702 ok &= writeStr(k_currentTracerPath, "function_graph");
703 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
704 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
705 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
706 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
707
708 // Set the requested filter functions.
709 ok &= truncateFile(k_ftraceFilterPath);
710 char* myFuncs = strdup(funcs);
711 char* func = strtok(myFuncs, ",");
712 while (func) {
713 ok &= appendStr(k_ftraceFilterPath, func);
714 func = strtok(NULL, ",");
715 }
716 free(myFuncs);
717
718 // Verify that the set functions are being traced.
719 if (ok) {
720 ok &= verifyKernelTraceFuncs(funcs);
721 }
722 }
723
724 return ok;
725}
726
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900727static bool setCategoryEnable(const char* name, bool enable)
728{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700729 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900730 const TracingCategory& c = k_categories[i];
731 if (strcmp(name, c.name) == 0) {
732 if (isCategorySupported(c)) {
733 g_categoryEnables[i] = enable;
734 return true;
735 } else {
736 if (isCategorySupportedForRoot(c)) {
737 fprintf(stderr, "error: category \"%s\" requires root "
738 "privileges.\n", name);
739 } else {
740 fprintf(stderr, "error: category \"%s\" is not supported "
741 "on this device.\n", name);
742 }
743 return false;
744 }
745 }
746 }
747 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
748 return false;
749}
750
751static bool setCategoriesEnableFromFile(const char* categories_file)
752{
753 if (!categories_file) {
754 return true;
755 }
756 Tokenizer* tokenizer = NULL;
757 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
758 return false;
759 }
760 bool ok = true;
761 while (!tokenizer->isEol()) {
762 String8 token = tokenizer->nextToken(" ");
763 if (token.isEmpty()) {
764 tokenizer->skipDelimiters(" ");
765 continue;
766 }
767 ok &= setCategoryEnable(token.string(), true);
768 }
769 delete tokenizer;
770 return ok;
771}
772
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700773// Set all the kernel tracing settings to the desired state for this trace
774// capture.
775static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800776{
777 bool ok = true;
778
779 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900780 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800781 ok &= setTraceOverwriteEnable(g_traceOverwrite);
782 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
John Reckba54d5b2017-06-23 09:44:08 -0700783 // TODO: Re-enable after stabilization
784 //ok &= setCmdlineSize();
Carmen Jacksonea826792017-05-05 11:42:32 -0700785 ok &= setClock();
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700786 ok &= setPrintTgidEnableIfPresent(true);
787 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800788
789 // Set up the tags property.
790 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700791 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800792 if (g_categoryEnables[i]) {
793 const TracingCategory &c = k_categories[i];
794 tags |= c.tags;
795 }
796 }
797 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700798
799 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700800 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700801 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
802 coreServicesTagEnabled = g_categoryEnables[i];
803 }
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700804
805 // Set whether to poke PDX services in this session.
806 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
807 g_tracePdx = g_categoryEnables[i];
808 }
sergeyvdb404152016-05-02 19:26:07 -0700809 }
810
811 std::string packageList(g_debugAppCmdLine);
812 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700813 if (!packageList.empty()) {
814 packageList += ",";
815 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700816 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700817 }
Dan Austin09a79872016-05-31 13:27:03 -0700818 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700819 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100820 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800821
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700822 if (g_tracePdx) {
823 ok &= ServiceUtility::PokeServices();
824 }
825
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800826 // Disable all the sysfs enables. This is done as a separate loop from
827 // the enables to allow the same enable to exist in multiple categories.
828 ok &= disableKernelTraceEvents();
829
830 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700831 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800832 if (g_categoryEnables[i]) {
833 const TracingCategory &c = k_categories[i];
834 for (int j = 0; j < MAX_SYS_FILES; j++) {
835 const char* path = c.sysfiles[j].path;
836 bool required = c.sysfiles[j].required == REQ;
837 if (path != NULL) {
838 if (fileIsWritable(path)) {
839 ok &= setKernelOptionEnable(path, true);
840 } else if (required) {
841 fprintf(stderr, "error writing file %s\n", path);
842 ok = false;
843 }
844 }
845 }
846 }
847 }
848
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800849 return ok;
850}
851
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700852// Reset all the kernel tracing settings to their default state.
853static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800854{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800855 // Disable all tracing that we're able to.
856 disableKernelTraceEvents();
857
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700858 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800859 setTagsProperty(0);
sergeyv4144eff2016-04-28 11:40:04 -0700860 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700861 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800862
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700863 if (g_tracePdx) {
864 ServiceUtility::PokeServices();
865 }
866
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800867 // Set the options back to their defaults.
868 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700869 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700870 setPrintTgidEnableIfPresent(false);
871 setKernelTraceFuncs(NULL);
872}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800873
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700874
875// Enable tracing in the kernel.
876static bool startTrace()
877{
878 return setTracingEnabled(true);
879}
880
881// Disable tracing in the kernel.
882static void stopTrace()
883{
884 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800885}
886
Martijn Coenend9535872015-11-26 10:00:55 +0100887// Read data from the tracing pipe and forward to stdout
888static void streamTrace()
889{
890 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800891 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100892 if (traceFD == -1) {
893 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
894 strerror(errno), errno);
895 return;
896 }
897 while (!g_traceAborted) {
898 ssize_t bytes_read = read(traceFD, trace_data, 4096);
899 if (bytes_read > 0) {
900 write(STDOUT_FILENO, trace_data, bytes_read);
901 fflush(stdout);
902 } else {
903 if (!g_traceAborted) {
904 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
905 bytes_read, errno, strerror(errno));
906 }
907 break;
908 }
909 }
910}
911
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800912// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700913static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800914{
John Reck6c8ac922016-03-28 11:25:30 -0700915 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800916 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800917 if (traceFD == -1) {
918 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
919 strerror(errno), errno);
920 return;
921 }
922
923 if (g_compress) {
924 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800925 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700926
927 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800928 if (result != Z_OK) {
929 fprintf(stderr, "error initializing zlib: %d\n", result);
930 close(traceFD);
931 return;
932 }
933
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700934 constexpr size_t bufSize = 64*1024;
935 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
936 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
937 if (!in || !out) {
938 fprintf(stderr, "couldn't allocate buffers\n");
939 close(traceFD);
940 return;
941 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800942
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700943 int flush = Z_NO_FLUSH;
944
945 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800946 zs.avail_out = bufSize;
947
948 do {
949
950 if (zs.avail_in == 0) {
951 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700952 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800953 if (result < 0) {
954 fprintf(stderr, "error reading trace: %s (%d)\n",
955 strerror(errno), errno);
956 result = Z_STREAM_END;
957 break;
958 } else if (result == 0) {
959 flush = Z_FINISH;
960 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700961 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800962 zs.avail_in = result;
963 }
964 }
965
966 if (zs.avail_out == 0) {
967 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700968 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800969 if ((size_t)result < bufSize) {
970 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
971 strerror(errno), errno);
972 result = Z_STREAM_END; // skip deflate error message
973 zs.avail_out = bufSize; // skip the final write
974 break;
975 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700976 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800977 zs.avail_out = bufSize;
978 }
979
980 } while ((result = deflate(&zs, flush)) == Z_OK);
981
982 if (result != Z_STREAM_END) {
983 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
984 }
985
986 if (zs.avail_out < bufSize) {
987 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -0700988 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800989 if ((size_t)result < bytes) {
990 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
991 strerror(errno), errno);
992 }
993 }
994
995 result = deflateEnd(&zs);
996 if (result != Z_OK) {
997 fprintf(stderr, "error cleaning up zlib: %d\n", result);
998 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800999 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001000 char buf[4096];
1001 ssize_t rc;
1002 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1003 if (!android::base::WriteFully(outFd, buf, rc)) {
1004 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1005 break;
1006 }
1007 }
1008 if (rc == -1) {
1009 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001010 }
1011 }
1012
1013 close(traceFD);
1014}
1015
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001016static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001017{
1018 if (!g_nohup) {
1019 g_traceAborted = true;
1020 }
1021}
1022
1023static void registerSigHandler()
1024{
1025 struct sigaction sa;
1026 sigemptyset(&sa.sa_mask);
1027 sa.sa_flags = 0;
1028 sa.sa_handler = handleSignal;
1029 sigaction(SIGHUP, &sa, NULL);
1030 sigaction(SIGINT, &sa, NULL);
1031 sigaction(SIGQUIT, &sa, NULL);
1032 sigaction(SIGTERM, &sa, NULL);
1033}
1034
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001035static void listSupportedCategories()
1036{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001037 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001038 const TracingCategory& c = k_categories[i];
1039 if (isCategorySupported(c)) {
1040 printf(" %10s - %s\n", c.name, c.longname);
1041 }
1042 }
1043}
1044
1045// Print the command usage help to stderr.
1046static void showHelp(const char *cmd)
1047{
1048 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1049 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001050 " -a appname enable app-level tracing for a comma "
1051 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001052 " -b N use a trace buffer size of N KB\n"
1053 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001054 " -f filename use the categories written in a file as space-separated\n"
1055 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001056 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001057 " -n ignore signals\n"
1058 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001059 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001060 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001061 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001062 " --async_dump dump the current contents of circular trace buffer\n"
1063 " --async_stop stop tracing and dump the current contents of circular\n"
1064 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001065 " --stream stream trace to stdout as it enters the trace buffer\n"
1066 " Note: this can take significant CPU time, and is best\n"
1067 " used for measuring things that are not affected by\n"
1068 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001069 " --list_categories\n"
1070 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001071 " -o filename write the trace to the specified file instead\n"
1072 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001073 );
1074}
1075
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001076bool findTraceFiles()
1077{
1078 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1079 static const std::string tracefs_path = "/sys/kernel/tracing/";
1080 static const std::string trace_file = "trace_marker";
1081
1082 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1083 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1084
1085 if (!tracefs && !debugfs) {
1086 fprintf(stderr, "Error: Did not find trace folder\n");
1087 return false;
1088 }
1089
1090 if (tracefs) {
1091 g_traceFolder = tracefs_path;
1092 } else {
1093 g_traceFolder = debugfs_path;
1094 }
1095
1096 return true;
1097}
1098
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001099int main(int argc, char **argv)
1100{
1101 bool async = false;
1102 bool traceStart = true;
1103 bool traceStop = true;
1104 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001105 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001106
1107 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1108 showHelp(argv[0]);
1109 exit(0);
1110 }
1111
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001112 if (!findTraceFiles()) {
1113 fprintf(stderr, "No trace folder found\n");
1114 exit(-1);
1115 }
1116
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001117 for (;;) {
1118 int ret;
1119 int option_index = 0;
1120 static struct option long_options[] = {
1121 {"async_start", no_argument, 0, 0 },
1122 {"async_stop", no_argument, 0, 0 },
1123 {"async_dump", no_argument, 0, 0 },
1124 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 10:00:55 +01001125 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001126 { 0, 0, 0, 0 }
1127 };
1128
John Reck40b26b42016-03-30 09:44:36 -07001129 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001130 long_options, &option_index);
1131
1132 if (ret < 0) {
1133 for (int i = optind; i < argc; i++) {
1134 if (!setCategoryEnable(argv[i], true)) {
1135 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1136 exit(1);
1137 }
1138 }
1139 break;
1140 }
1141
1142 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001143 case 'a':
1144 g_debugAppCmdLine = optarg;
1145 break;
1146
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001147 case 'b':
1148 g_traceBufferSizeKB = atoi(optarg);
1149 break;
1150
1151 case 'c':
1152 g_traceOverwrite = true;
1153 break;
1154
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001155 case 'f':
1156 g_categoriesFile = optarg;
1157 break;
1158
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001159 case 'k':
1160 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001161 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001162
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001163 case 'n':
1164 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001165 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001166
1167 case 's':
1168 g_initialSleepSecs = atoi(optarg);
1169 break;
1170
1171 case 't':
1172 g_traceDurationSeconds = atoi(optarg);
1173 break;
1174
1175 case 'z':
1176 g_compress = true;
1177 break;
1178
John Reck40b26b42016-03-30 09:44:36 -07001179 case 'o':
1180 g_outputFile = optarg;
1181 break;
1182
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001183 case 0:
1184 if (!strcmp(long_options[option_index].name, "async_start")) {
1185 async = true;
1186 traceStop = false;
1187 traceDump = false;
1188 g_traceOverwrite = true;
1189 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1190 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001191 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001192 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1193 async = true;
1194 traceStart = false;
1195 traceStop = false;
Martijn Coenend9535872015-11-26 10:00:55 +01001196 } else if (!strcmp(long_options[option_index].name, "stream")) {
1197 traceStream = true;
1198 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001199 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1200 listSupportedCategories();
1201 exit(0);
1202 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001203 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001204
1205 default:
1206 fprintf(stderr, "\n");
1207 showHelp(argv[0]);
1208 exit(-1);
1209 break;
1210 }
1211 }
1212
1213 registerSigHandler();
1214
1215 if (g_initialSleepSecs > 0) {
1216 sleep(g_initialSleepSecs);
1217 }
1218
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001219 bool ok = true;
1220 ok &= setUpTrace();
1221 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001222
1223 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 10:00:55 +01001224 if (!traceStream) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001225 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001226 fflush(stdout);
1227 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001228
1229 // We clear the trace after starting it because tracing gets enabled for
1230 // each CPU individually in the kernel. Having the beginning of the trace
1231 // contain entries from only one CPU can cause "begin" entries without a
1232 // matching "end" entry to show up if a task gets migrated from one CPU to
1233 // another.
1234 ok = clearTrace();
1235
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001236 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001237 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001238 // Sleep to allow the trace to be captured.
1239 struct timespec timeLeft;
1240 timeLeft.tv_sec = g_traceDurationSeconds;
1241 timeLeft.tv_nsec = 0;
1242 do {
1243 if (g_traceAborted) {
1244 break;
1245 }
1246 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1247 }
Martijn Coenend9535872015-11-26 10:00:55 +01001248
1249 if (traceStream) {
1250 streamTrace();
1251 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001252 }
1253
1254 // Stop the trace and restore the default settings.
1255 if (traceStop)
1256 stopTrace();
1257
1258 if (ok && traceDump) {
1259 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001260 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001261 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001262 int outFd = STDOUT_FILENO;
1263 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001264 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001265 }
1266 if (outFd == -1) {
1267 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1268 } else {
1269 dprintf(outFd, "TRACE:\n");
1270 dumpTrace(outFd);
1271 if (g_outputFile) {
1272 close(outFd);
1273 }
1274 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001275 } else {
1276 printf("\ntrace aborted.\n");
1277 fflush(stdout);
1278 }
1279 clearTrace();
1280 } else if (!ok) {
1281 fprintf(stderr, "unable to start tracing\n");
1282 }
1283
1284 // Reset the trace buffer size to 1.
1285 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001286 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001287
1288 return g_traceAborted ? 1 : 0;
1289}