blob: e89748259e11bf5529191ffb2202e6d9de6c0b27 [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
Wei Wang16a63a42018-09-21 15:47:45 -070040#include <android/hardware/atrace/1.0/IAtraceDevice.h>
Martijn Coenenee9b97e2016-11-16 16:00:26 +010041#include <android/hidl/manager/1.0/IServiceManager.h>
42#include <hidl/ServiceManagement.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080043
Corey Tabakaa6c0a722017-05-31 16:37:40 -070044#include <pdx/default_transport/service_utility.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080045#include <utils/String8.h>
John Reck469a1942015-03-26 15:31:35 -070046#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +090047#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080048#include <utils/Trace.h>
Stephane Gasparinid8419c22016-03-02 13:45:15 +010049#include <android-base/file.h>
Elliott Hughes5fd6ff62017-03-28 14:55:31 -070050#include <android-base/macros.h>
51#include <android-base/properties.h>
52#include <android-base/stringprintf.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080053
54using namespace android;
Corey Tabakaa6c0a722017-05-31 16:37:40 -070055using pdx::default_transport::ServiceUtility;
Wei Wang16a63a42018-09-21 15:47:45 -070056using hardware::hidl_vec;
57using hardware::hidl_string;
58using hardware::Return;
59using hardware::atrace::V1_0::IAtraceDevice;
60using hardware::atrace::V1_0::Status;
61using hardware::atrace::V1_0::toString;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080062
Martijn Coenenee9b97e2016-11-16 16:00:26 +010063using std::string;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080064
sergeyv4144eff2016-04-28 11:40:04 -070065#define MAX_SYS_FILES 10
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080066
67const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
Carmen Jackson65ecfbb2018-05-22 10:29:47 -070068const char* k_userInitiatedTraceProperty = "debug.atrace.user_initiated";
sergeyv4144eff2016-04-28 11:40:04 -070069
70const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
71const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070072const char* k_coreServiceCategory = "core_services";
Corey Tabakaa6c0a722017-05-31 16:37:40 -070073const char* k_pdxServiceCategory = "pdx";
sergeyvdb404152016-05-02 19:26:07 -070074const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080075
76typedef enum { OPT, REQ } requiredness ;
77
78struct TracingCategory {
79 // The name identifying the category.
80 const char* name;
81
82 // A longer description of the category.
83 const char* longname;
84
85 // The userland tracing tags that the category enables.
86 uint64_t tags;
87
88 // The fname==NULL terminated list of /sys/ files that the category
89 // enables.
90 struct {
91 // Whether the file must be writable in order to enable the tracing
92 // category.
93 requiredness required;
94
95 // The path to the enable file.
96 const char* path;
97 } sysfiles[MAX_SYS_FILES];
98};
99
100/* Tracing categories */
101static const TracingCategory k_categories[] = {
Wei Wang16a63a42018-09-21 15:47:45 -0700102 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700103 { "input", "Input", ATRACE_TAG_INPUT, { } },
104 { "view", "View System", ATRACE_TAG_VIEW, { } },
105 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
106 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
107 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -0500108 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700109 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
110 { "video", "Video", ATRACE_TAG_VIDEO, { } },
111 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
112 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -0700113 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -0700114 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -0700115 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -0700116 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700117 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 14:36:20 -0700118 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-07-01 01:46:25 +0900119 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Greg Hackmannbbd7d992014-12-01 14:43:34 -0800120 { "database", "Database", ATRACE_TAG_DATABASE, { } },
Felipe Leme0f97c1d2016-09-07 11:33:26 -0700121 { "network", "Network", ATRACE_TAG_NETWORK, { } },
Josh Gao468b4cb2016-11-29 10:55:21 -0800122 { "adb", "ADB", ATRACE_TAG_ADB, { } },
Martijn Coenen42f2ab42018-03-09 09:27:32 +0100123 { "vibrator", "Vibrator", ATRACE_TAG_VIBRATOR, { } },
124 { "aidl", "AIDL calls", ATRACE_TAG_AIDL, { } },
Mika Raentob363cf52018-04-23 22:09:13 +0100125 { "nnapi", "NNAPI", ATRACE_TAG_NNAPI, { } },
sergeyvdb404152016-05-02 19:26:07 -0700126 { k_coreServiceCategory, "Core services", 0, { } },
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700127 { k_pdxServiceCategory, "PDX services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700128 { "sched", "CPU Scheduling", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800129 { REQ, "events/sched/sched_switch/enable" },
130 { REQ, "events/sched/sched_wakeup/enable" },
Joel Fernandesee593e22017-06-04 13:05:59 -0700131 { OPT, "events/sched/sched_waking/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800132 { OPT, "events/sched/sched_blocked_reason/enable" },
133 { OPT, "events/sched/sched_cpu_hotplug/enable" },
Wei Wangca49dfc2018-05-03 15:45:20 -0700134 { OPT, "events/sched/sched_pi_setprio/enable" },
Joel Fernandes4dfca7c2017-06-15 16:53:52 -0700135 { OPT, "events/cgroup/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800136 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700137 { "irq", "IRQ Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800138 { REQ, "events/irq/enable" },
139 { OPT, "events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700140 } },
Joel Fernandes6ccad102017-08-31 08:35:05 -0700141 { "irqoff", "IRQ-disabled code section tracing", 0, {
142 { REQ, "events/preemptirq/irq_enable/enable" },
143 { REQ, "events/preemptirq/irq_disable/enable" },
144 } },
145 { "preemptoff", "Preempt-disabled code section tracing", 0, {
146 { REQ, "events/preemptirq/preempt_enable/enable" },
147 { REQ, "events/preemptirq/preempt_disable/enable" },
148 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100149 { "i2c", "I2C Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800150 { REQ, "events/i2c/enable" },
151 { REQ, "events/i2c/i2c_read/enable" },
152 { REQ, "events/i2c/i2c_write/enable" },
153 { REQ, "events/i2c/i2c_result/enable" },
154 { REQ, "events/i2c/i2c_reply/enable" },
155 { OPT, "events/i2c/smbus_read/enable" },
156 { OPT, "events/i2c/smbus_write/enable" },
157 { OPT, "events/i2c/smbus_result/enable" },
158 { OPT, "events/i2c/smbus_reply/enable" },
Michael Wright43fb6782016-08-18 19:56:43 +0100159 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700160 { "freq", "CPU Frequency", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800161 { REQ, "events/power/cpu_frequency/enable" },
162 { OPT, "events/power/clock_set_rate/enable" },
Kevin DuBois062e0b92017-11-03 15:44:08 -0700163 { OPT, "events/power/clock_disable/enable" },
164 { OPT, "events/power/clock_enable/enable" },
Wei Wang53305dd2018-02-22 11:40:07 -0800165 { OPT, "events/clk/clk_set_rate/enable" },
166 { OPT, "events/clk/clk_disable/enable" },
167 { OPT, "events/clk/clk_enable/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800168 { OPT, "events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800169 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700170 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800171 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800172 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700173 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800174 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800175 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700176 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800177 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
178 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
179 { OPT, "events/f2fs/f2fs_write_begin/enable" },
180 { OPT, "events/f2fs/f2fs_write_end/enable" },
181 { OPT, "events/ext4/ext4_da_write_begin/enable" },
182 { OPT, "events/ext4/ext4_da_write_end/enable" },
183 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
184 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
185 { REQ, "events/block/block_rq_issue/enable" },
186 { REQ, "events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800187 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700188 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800189 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700190 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700191 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800192 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800193 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700194 { "sync", "Synchronization", 0, {
Jesse Hallae001a32018-05-15 12:02:15 -0700195 // before linux kernel 4.9
196 { OPT, "events/sync/enable" },
197 // starting in linux kernel 4.9
198 { OPT, "events/fence/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800199 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700200 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800201 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800202 } },
Colin Cross580407f2014-08-18 15:22:13 -0700203 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800204 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
205 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
206 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
207 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Carmen Jackson7a23eb72018-07-02 13:14:56 -0700208 { OPT, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700209 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800210 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800211 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800212 } },
Scott Bauerae473362015-06-08 16:32:36 -0700213 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800214 { REQ, "events/binder/binder_transaction/enable" },
215 { REQ, "events/binder/binder_transaction_received/enable" },
Mika Raento80c3e5d2018-06-25 16:47:24 +0100216 { REQ, "events/binder/binder_transaction_alloc_buf/enable" },
Martijn Coenen7f3d7a22017-05-26 09:50:55 -0700217 { OPT, "events/binder/binder_set_priority/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700218 } },
219 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800220 { OPT, "events/binder/binder_lock/enable" },
221 { OPT, "events/binder/binder_locked/enable" },
222 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700223 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200224 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800225 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200226 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800227};
228
Wei Wang16a63a42018-09-21 15:47:45 -0700229struct TracingVendorCategory {
230 // The name identifying the category.
231 std::string name;
232
233 // A longer description of the category.
234 std::string description;
235
236 // If the category is enabled through command.
237 bool enabled;
238
239 TracingVendorCategory(string &&name, string &&description, bool enabled)
240 : name(std::move(name))
241 , description(std::move(description))
242 , enabled(enabled)
243 {}
244};
245
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800246/* Command line options */
247static int g_traceDurationSeconds = 5;
248static bool g_traceOverwrite = false;
249static int g_traceBufferSizeKB = 2048;
250static bool g_compress = false;
251static bool g_nohup = false;
252static int g_initialSleepSecs = 0;
Yi Kong19d5c002018-07-20 13:39:55 -0700253static const char* g_categoriesFile = nullptr;
254static const char* g_kernelTraceFuncs = nullptr;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700255static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700256static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800257
258/* Global state */
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700259static bool g_tracePdx = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800260static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700261static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800262static std::string g_traceFolder;
Wei Wang16a63a42018-09-21 15:47:45 -0700263static sp<IAtraceDevice> g_atraceHal;
264static std::vector<TracingVendorCategory> g_vendorCategories;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800265
266/* Sys file paths */
267static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800268 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800269
270static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800271 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800272
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700273#if 0
274// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700275static const char* k_traceCmdlineSizePath =
276 "saved_cmdlines_size";
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700277#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700278
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800279static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800280 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800281
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700282static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800283 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700284
285static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800286 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700287
John Recke757b1c2018-06-28 12:24:33 -0700288static const char* k_recordTgidPath =
289 "options/record-tgid";
290
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700291static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800292 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700293
294static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800295 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700296
297static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800298 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700299
300static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800301 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700302
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700303static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800304 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700305
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800306static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800307 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800308
309static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800310 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800311
Martijn Coenend9535872015-11-26 10:00:55 +0100312static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800313 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100314
John Reck469a1942015-03-26 15:31:35 -0700315static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800316 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700317
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800318// Check whether a file exists.
319static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800320 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800321}
322
323// Check whether a file is writable.
324static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800325 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800326}
327
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700328// Truncate a file.
329static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800330{
Jamie Gennis43122e72013-03-21 14:06:31 -0700331 // This uses creat rather than truncate because some of the debug kernel
332 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
333 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800334 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700335 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800336 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700337 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700338 return false;
339 }
340
Jamie Gennis43122e72013-03-21 14:06:31 -0700341 close(traceFD);
342
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700343 return true;
344}
345
346static bool _writeStr(const char* filename, const char* str, int flags)
347{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800348 std::string fullFilename = g_traceFolder + filename;
349 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800350 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800351 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800352 strerror(errno), errno);
353 return false;
354 }
355
356 bool ok = true;
357 ssize_t len = strlen(str);
358 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800359 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800360 strerror(errno), errno);
361 ok = false;
362 }
363
364 close(fd);
365
366 return ok;
367}
368
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700369// Write a string to a file, returning true if the write was successful.
370static bool writeStr(const char* filename, const char* str)
371{
372 return _writeStr(filename, str, O_WRONLY);
373}
374
375// Append a string to a file, returning true if the write was successful.
376static bool appendStr(const char* filename, const char* str)
377{
378 return _writeStr(filename, str, O_APPEND|O_WRONLY);
379}
380
John Reck469a1942015-03-26 15:31:35 -0700381static void writeClockSyncMarker()
382{
383 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200384 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800385 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200386 if (fd == -1) {
387 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
388 strerror(errno), errno);
389 return;
390 }
John Reck469a1942015-03-26 15:31:35 -0700391 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200392
393 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
394 if (write(fd, buffer, len) != len) {
395 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
396 }
397
398 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
399 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
400 if (write(fd, buffer, len) != len) {
401 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
402 }
403
404 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700405}
406
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800407// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
408// file.
409static bool setKernelOptionEnable(const char* filename, bool enable)
410{
411 return writeStr(filename, enable ? "1" : "0");
412}
413
414// Check whether the category is supported on the device with the current
415// rootness. A category is supported only if all its required /sys/ files are
416// writable and if enabling the category will enable one or more tracing tags
417// or /sys/ files.
418static bool isCategorySupported(const TracingCategory& category)
419{
sergeyvdb404152016-05-02 19:26:07 -0700420 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700421 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700422 }
423
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700424 if (strcmp(category.name, k_pdxServiceCategory) == 0) {
425 return true;
426 }
427
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800428 bool ok = category.tags != 0;
429 for (int i = 0; i < MAX_SYS_FILES; i++) {
430 const char* path = category.sysfiles[i].path;
431 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700432 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800433 if (req) {
434 if (!fileIsWritable(path)) {
435 return false;
436 } else {
437 ok = true;
438 }
439 } else {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800440 ok = true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800441 }
442 }
443 }
444 return ok;
445}
446
447// Check whether the category would be supported on the device if the user
448// were root. This function assumes that root is able to write to any file
449// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700450// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800451static bool isCategorySupportedForRoot(const TracingCategory& category)
452{
453 bool ok = category.tags != 0;
454 for (int i = 0; i < MAX_SYS_FILES; i++) {
455 const char* path = category.sysfiles[i].path;
456 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700457 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800458 if (req) {
459 if (!fileExists(path)) {
460 return false;
461 } else {
462 ok = true;
463 }
464 } else {
465 ok |= fileExists(path);
466 }
467 }
468 }
469 return ok;
470}
471
472// Enable or disable overwriting of the kernel trace buffers. Disabling this
473// will cause tracing to stop once the trace buffers have filled up.
474static bool setTraceOverwriteEnable(bool enable)
475{
476 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
477}
478
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700479// Set the user initiated trace property
480static bool setUserInitiatedTraceProperty(bool enable)
481{
482 if (!android::base::SetProperty(k_userInitiatedTraceProperty, enable ? "1" : "")) {
483 fprintf(stderr, "error setting user initiated strace system property\n");
484 return false;
485 }
486 return true;
487}
488
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800489// Enable or disable kernel tracing.
490static bool setTracingEnabled(bool enable)
491{
492 return setKernelOptionEnable(k_tracingOnPath, enable);
493}
494
495// Clear the contents of the kernel trace.
496static bool clearTrace()
497{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700498 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800499}
500
501// Set the size of the kernel's trace buffer in kilobytes.
502static bool setTraceBufferSizeKB(int size)
503{
504 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800505 if (size < 1) {
506 size = 1;
507 }
508 snprintf(str, 32, "%d", size);
509 return writeStr(k_traceBufferSizePath, str);
510}
511
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700512#if 0
513// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700514// Set the default size of cmdline hashtable
515static bool setCmdlineSize()
516{
Joel Fernandesce964f22017-06-06 12:20:29 -0700517 if (fileExists(k_traceCmdlineSizePath)) {
518 return writeStr(k_traceCmdlineSizePath, "8192");
519 }
520 return true;
Joel Fernandesed80bd02017-06-02 10:19:28 -0700521}
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700522#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700523
Carmen Jacksonea826792017-05-05 11:42:32 -0700524// Set the clock to the best available option while tracing. Use 'boot' if it's
525// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700526// Any write to the trace_clock sysfs file will reset the buffer, so only
527// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700528static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800529{
Carmen Jacksonea826792017-05-05 11:42:32 -0700530 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
531 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
532 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700533
Carmen Jacksonea826792017-05-05 11:42:32 -0700534 std::string newClock;
535 if (clockStr.find("boot") != std::string::npos) {
536 newClock = "boot";
537 } else if (clockStr.find("mono") != std::string::npos) {
538 newClock = "mono";
539 } else {
540 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700541 }
542
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700543 size_t begin = clockStr.find('[') + 1;
544 size_t end = clockStr.find(']');
Carmen Jacksonea826792017-05-05 11:42:32 -0700545 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
546 return true;
547 }
548 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800549}
550
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700551static bool setPrintTgidEnableIfPresent(bool enable)
552{
John Reckedbf9ec2018-06-29 11:15:17 -0700553 // Pre-4.13 this was options/print-tgid as an android-specific option.
554 // In 4.13+ this is an upstream option called options/record-tgid
555 // Both options produce the same ftrace format change
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700556 if (fileExists(k_printTgidPath)) {
557 return setKernelOptionEnable(k_printTgidPath, enable);
558 }
John Recke757b1c2018-06-28 12:24:33 -0700559 if (fileExists(k_recordTgidPath)) {
560 return setKernelOptionEnable(k_recordTgidPath, enable);
561 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700562 return true;
563}
564
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800565// Poke all the binder-enabled processes in the system to get them to re-read
566// their system properties.
567static bool pokeBinderServices()
568{
569 sp<IServiceManager> sm = defaultServiceManager();
570 Vector<String16> services = sm->listServices();
571 for (size_t i = 0; i < services.size(); i++) {
572 sp<IBinder> obj = sm->checkService(services[i]);
Yi Kong19d5c002018-07-20 13:39:55 -0700573 if (obj != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800574 Parcel data;
575 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
Yi Kong19d5c002018-07-20 13:39:55 -0700576 nullptr, 0) != OK) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800577 if (false) {
578 // XXX: For some reason this fails on tablets trying to
579 // poke the "phone" service. It's not clear whether some
580 // are expected to fail.
581 String8 svc(services[i]);
582 fprintf(stderr, "error poking binder service %s\n",
583 svc.string());
584 return false;
585 }
586 }
587 }
588 }
589 return true;
590}
591
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100592// Poke all the HAL processes in the system to get them to re-read
593// their system properties.
594static void pokeHalServices()
595{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100596 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100597 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100598 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100599 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100600
601 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800602
603 if (sm == nullptr) {
604 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
605 return;
606 }
607
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800608 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100609 for (size_t i = 0; i < interfaces.size(); i++) {
610 string fqInstanceName = interfaces[i];
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700611 string::size_type n = fqInstanceName.find('/');
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100612 if (n == std::string::npos || interfaces[i].size() == n+1)
613 continue;
614 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
615 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100616 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
617 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100618 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100619 continue;
620 }
Carmen Jackson73206122017-04-18 15:37:57 -0700621
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100622 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700623 if (interface == nullptr) {
624 // ignore
625 continue;
626 }
627
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100628 auto notifyRet = interface->notifySyspropsChanged();
629 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100630 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800631 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100632 }
633 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800634 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100635 // TODO(b/34242478) fix this when we determine the correct ACL
636 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800637 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100638}
639
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800640// Set the trace tags that userland tracing uses, and poke the running
641// processes to pick up the new value.
642static bool setTagsProperty(uint64_t tags)
643{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700644 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
645 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800646 fprintf(stderr, "error setting trace tags system property\n");
647 return false;
648 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700649 return true;
650}
651
sergeyv4144eff2016-04-28 11:40:04 -0700652static void clearAppProperties()
653{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700654 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700655 fprintf(stderr, "failed to clear system property: %s",
656 k_traceAppsNumberProperty);
657 }
658}
659
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700660// Set the system property that indicates which apps should perform
661// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700662static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700663{
sergeyv4144eff2016-04-28 11:40:04 -0700664 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700665 char* start = cmdline;
Yi Kong19d5c002018-07-20 13:39:55 -0700666 while (start != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700667 char* end = strchr(start, ',');
Yi Kong19d5c002018-07-20 13:39:55 -0700668 if (end != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700669 *end = '\0';
670 end++;
671 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700672 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
673 if (!android::base::SetProperty(key, start)) {
674 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700675 clearAppProperties();
676 return false;
677 }
678 start = end;
679 i++;
680 }
681
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700682 std::string value = android::base::StringPrintf("%d", i);
683 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
684 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700685 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700686 return false;
687 }
688 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800689}
690
691// Disable all /sys/ enable files.
692static bool disableKernelTraceEvents() {
693 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700694 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800695 const TracingCategory &c = k_categories[i];
696 for (int j = 0; j < MAX_SYS_FILES; j++) {
697 const char* path = c.sysfiles[j].path;
Yi Kong19d5c002018-07-20 13:39:55 -0700698 if (path != nullptr && fileIsWritable(path)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800699 ok &= setKernelOptionEnable(path, false);
700 }
701 }
702 }
703 return ok;
704}
705
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700706// Verify that the comma separated list of functions are being traced by the
707// kernel.
708static bool verifyKernelTraceFuncs(const char* funcs)
709{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100710 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800711 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100712 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700713 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100714 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700715 }
716
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100717 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700718
719 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100720 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700721 bool ok = true;
722 char* myFuncs = strdup(funcs);
723 char* func = strtok(myFuncs, ",");
724 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100725 if (!strchr(func, '*')) {
726 String8 fancyFunc = String8::format("\n%s\n", func);
727 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
728 if (!found || func[0] == '\0') {
729 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
730 "to trace.\n", func);
731 ok = false;
732 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700733 }
Yi Kong19d5c002018-07-20 13:39:55 -0700734 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700735 }
736 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700737 return ok;
738}
739
740// Set the comma separated list of functions that the kernel is to trace.
741static bool setKernelTraceFuncs(const char* funcs)
742{
743 bool ok = true;
744
Yi Kong19d5c002018-07-20 13:39:55 -0700745 if (funcs == nullptr || funcs[0] == '\0') {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700746 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700747 if (fileIsWritable(k_currentTracerPath)) {
748 ok &= writeStr(k_currentTracerPath, "nop");
749 }
750 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700751 ok &= truncateFile(k_ftraceFilterPath);
752 }
753 } else {
754 // Enable kernel function tracing.
755 ok &= writeStr(k_currentTracerPath, "function_graph");
756 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
757 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
758 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
759 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
760
761 // Set the requested filter functions.
762 ok &= truncateFile(k_ftraceFilterPath);
763 char* myFuncs = strdup(funcs);
764 char* func = strtok(myFuncs, ",");
765 while (func) {
766 ok &= appendStr(k_ftraceFilterPath, func);
Yi Kong19d5c002018-07-20 13:39:55 -0700767 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700768 }
769 free(myFuncs);
770
771 // Verify that the set functions are being traced.
772 if (ok) {
773 ok &= verifyKernelTraceFuncs(funcs);
774 }
775 }
776
777 return ok;
778}
779
Wei Wang16a63a42018-09-21 15:47:45 -0700780static bool setCategoryEnable(const char* name)
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900781{
Wei Wang16a63a42018-09-21 15:47:45 -0700782 bool vendor_found = false;
783 for (auto &c : g_vendorCategories) {
784 if (strcmp(name, c.name.c_str()) == 0) {
785 c.enabled = true;
786 vendor_found = true;
787 }
788 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700789 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900790 const TracingCategory& c = k_categories[i];
791 if (strcmp(name, c.name) == 0) {
792 if (isCategorySupported(c)) {
Wei Wang16a63a42018-09-21 15:47:45 -0700793 g_categoryEnables[i] = true;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900794 return true;
795 } else {
796 if (isCategorySupportedForRoot(c)) {
797 fprintf(stderr, "error: category \"%s\" requires root "
798 "privileges.\n", name);
799 } else {
800 fprintf(stderr, "error: category \"%s\" is not supported "
801 "on this device.\n", name);
802 }
803 return false;
804 }
805 }
806 }
Wei Wang16a63a42018-09-21 15:47:45 -0700807 if (vendor_found) {
808 return true;
809 }
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900810 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
811 return false;
812}
813
814static bool setCategoriesEnableFromFile(const char* categories_file)
815{
816 if (!categories_file) {
817 return true;
818 }
Yi Kong19d5c002018-07-20 13:39:55 -0700819 Tokenizer* tokenizer = nullptr;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900820 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
821 return false;
822 }
823 bool ok = true;
824 while (!tokenizer->isEol()) {
825 String8 token = tokenizer->nextToken(" ");
826 if (token.isEmpty()) {
827 tokenizer->skipDelimiters(" ");
828 continue;
829 }
Wei Wang16a63a42018-09-21 15:47:45 -0700830 ok &= setCategoryEnable(token.string());
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900831 }
832 delete tokenizer;
833 return ok;
834}
835
Hector Dearman11845782018-03-08 14:35:44 +0000836static bool setUpUserspaceTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800837{
838 bool ok = true;
839
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800840 // Set up the tags property.
841 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700842 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800843 if (g_categoryEnables[i]) {
844 const TracingCategory &c = k_categories[i];
845 tags |= c.tags;
846 }
847 }
848 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700849
850 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700851 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700852 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
853 coreServicesTagEnabled = g_categoryEnables[i];
854 }
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700855
856 // Set whether to poke PDX services in this session.
857 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
858 g_tracePdx = g_categoryEnables[i];
859 }
sergeyvdb404152016-05-02 19:26:07 -0700860 }
861
862 std::string packageList(g_debugAppCmdLine);
863 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700864 if (!packageList.empty()) {
865 packageList += ",";
866 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700867 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700868 }
Dan Austin09a79872016-05-31 13:27:03 -0700869 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700870 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100871 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800872
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700873 if (g_tracePdx) {
874 ok &= ServiceUtility::PokeServices();
875 }
876
Hector Dearman11845782018-03-08 14:35:44 +0000877 return ok;
878}
879
880static void cleanUpUserspaceTracing()
881{
882 setTagsProperty(0);
883 clearAppProperties();
884 pokeBinderServices();
885
886 if (g_tracePdx) {
887 ServiceUtility::PokeServices();
888 }
889}
890
891
892// Set all the kernel tracing settings to the desired state for this trace
893// capture.
894static bool setUpKernelTracing()
895{
896 bool ok = true;
897
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700898 ok &= setUserInitiatedTraceProperty(true);
899
Hector Dearman11845782018-03-08 14:35:44 +0000900 // Set up the tracing options.
901 ok &= setCategoriesEnableFromFile(g_categoriesFile);
902 ok &= setTraceOverwriteEnable(g_traceOverwrite);
903 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
904 // TODO: Re-enable after stabilization
905 //ok &= setCmdlineSize();
906 ok &= setClock();
907 ok &= setPrintTgidEnableIfPresent(true);
908 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
909
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800910 // Disable all the sysfs enables. This is done as a separate loop from
911 // the enables to allow the same enable to exist in multiple categories.
912 ok &= disableKernelTraceEvents();
913
914 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700915 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800916 if (g_categoryEnables[i]) {
917 const TracingCategory &c = k_categories[i];
918 for (int j = 0; j < MAX_SYS_FILES; j++) {
919 const char* path = c.sysfiles[j].path;
920 bool required = c.sysfiles[j].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700921 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800922 if (fileIsWritable(path)) {
923 ok &= setKernelOptionEnable(path, true);
924 } else if (required) {
925 fprintf(stderr, "error writing file %s\n", path);
926 ok = false;
927 }
928 }
929 }
930 }
931 }
932
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800933 return ok;
934}
935
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700936// Reset all the kernel tracing settings to their default state.
Hector Dearman11845782018-03-08 14:35:44 +0000937static void cleanUpKernelTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800938{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800939 // Disable all tracing that we're able to.
940 disableKernelTraceEvents();
941
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800942 // Set the options back to their defaults.
943 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700944 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700945 setPrintTgidEnableIfPresent(false);
Yi Kong19d5c002018-07-20 13:39:55 -0700946 setKernelTraceFuncs(nullptr);
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700947 setUserInitiatedTraceProperty(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700948}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800949
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700950// Enable tracing in the kernel.
951static bool startTrace()
952{
953 return setTracingEnabled(true);
954}
955
956// Disable tracing in the kernel.
957static void stopTrace()
958{
959 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800960}
961
Martijn Coenend9535872015-11-26 10:00:55 +0100962// Read data from the tracing pipe and forward to stdout
963static void streamTrace()
964{
965 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800966 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100967 if (traceFD == -1) {
968 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
969 strerror(errno), errno);
970 return;
971 }
972 while (!g_traceAborted) {
973 ssize_t bytes_read = read(traceFD, trace_data, 4096);
974 if (bytes_read > 0) {
975 write(STDOUT_FILENO, trace_data, bytes_read);
976 fflush(stdout);
977 } else {
978 if (!g_traceAborted) {
979 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
980 bytes_read, errno, strerror(errno));
981 }
982 break;
983 }
984 }
985}
986
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800987// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700988static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800989{
John Reck6c8ac922016-03-28 11:25:30 -0700990 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800991 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800992 if (traceFD == -1) {
993 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
994 strerror(errno), errno);
995 return;
996 }
997
998 if (g_compress) {
999 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -08001000 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001001
1002 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001003 if (result != Z_OK) {
1004 fprintf(stderr, "error initializing zlib: %d\n", result);
1005 close(traceFD);
1006 return;
1007 }
1008
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001009 constexpr size_t bufSize = 64*1024;
1010 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
1011 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
1012 if (!in || !out) {
1013 fprintf(stderr, "couldn't allocate buffers\n");
1014 close(traceFD);
1015 return;
1016 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001017
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001018 int flush = Z_NO_FLUSH;
1019
1020 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001021 zs.avail_out = bufSize;
1022
1023 do {
1024
1025 if (zs.avail_in == 0) {
1026 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001027 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001028 if (result < 0) {
1029 fprintf(stderr, "error reading trace: %s (%d)\n",
1030 strerror(errno), errno);
1031 result = Z_STREAM_END;
1032 break;
1033 } else if (result == 0) {
1034 flush = Z_FINISH;
1035 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001036 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001037 zs.avail_in = result;
1038 }
1039 }
1040
1041 if (zs.avail_out == 0) {
1042 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -07001043 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001044 if ((size_t)result < bufSize) {
1045 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1046 strerror(errno), errno);
1047 result = Z_STREAM_END; // skip deflate error message
1048 zs.avail_out = bufSize; // skip the final write
1049 break;
1050 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001051 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001052 zs.avail_out = bufSize;
1053 }
1054
1055 } while ((result = deflate(&zs, flush)) == Z_OK);
1056
1057 if (result != Z_STREAM_END) {
1058 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
1059 }
1060
1061 if (zs.avail_out < bufSize) {
1062 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -07001063 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001064 if ((size_t)result < bytes) {
1065 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1066 strerror(errno), errno);
1067 }
1068 }
1069
1070 result = deflateEnd(&zs);
1071 if (result != Z_OK) {
1072 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1073 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001074 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001075 char buf[4096];
1076 ssize_t rc;
1077 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1078 if (!android::base::WriteFully(outFd, buf, rc)) {
1079 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1080 break;
1081 }
1082 }
1083 if (rc == -1) {
1084 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001085 }
1086 }
1087
1088 close(traceFD);
1089}
1090
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001091static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001092{
1093 if (!g_nohup) {
1094 g_traceAborted = true;
1095 }
1096}
1097
1098static void registerSigHandler()
1099{
1100 struct sigaction sa;
1101 sigemptyset(&sa.sa_mask);
1102 sa.sa_flags = 0;
1103 sa.sa_handler = handleSignal;
Yi Kong19d5c002018-07-20 13:39:55 -07001104 sigaction(SIGHUP, &sa, nullptr);
1105 sigaction(SIGINT, &sa, nullptr);
1106 sigaction(SIGQUIT, &sa, nullptr);
1107 sigaction(SIGTERM, &sa, nullptr);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001108}
1109
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001110static void listSupportedCategories()
1111{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001112 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001113 const TracingCategory& c = k_categories[i];
1114 if (isCategorySupported(c)) {
1115 printf(" %10s - %s\n", c.name, c.longname);
1116 }
1117 }
Wei Wang16a63a42018-09-21 15:47:45 -07001118 for (const auto &c : g_vendorCategories) {
1119 printf(" %10s - %s (HAL)\n", c.name.c_str(), c.description.c_str());
1120 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001121}
1122
1123// Print the command usage help to stderr.
1124static void showHelp(const char *cmd)
1125{
1126 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1127 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001128 " -a appname enable app-level tracing for a comma "
Daniel Colascione519a0792018-02-09 20:05:39 -08001129 "separated list of cmdlines; * is a wildcard matching any process\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001130 " -b N use a trace buffer size of N KB\n"
1131 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001132 " -f filename use the categories written in a file as space-separated\n"
1133 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001134 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001135 " -n ignore signals\n"
1136 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001137 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001138 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001139 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001140 " --async_dump dump the current contents of circular trace buffer\n"
1141 " --async_stop stop tracing and dump the current contents of circular\n"
1142 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001143 " --stream stream trace to stdout as it enters the trace buffer\n"
1144 " Note: this can take significant CPU time, and is best\n"
1145 " used for measuring things that are not affected by\n"
1146 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001147 " --list_categories\n"
1148 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001149 " -o filename write the trace to the specified file instead\n"
1150 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001151 );
1152}
1153
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001154bool findTraceFiles()
1155{
1156 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1157 static const std::string tracefs_path = "/sys/kernel/tracing/";
1158 static const std::string trace_file = "trace_marker";
1159
1160 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1161 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1162
1163 if (!tracefs && !debugfs) {
1164 fprintf(stderr, "Error: Did not find trace folder\n");
1165 return false;
1166 }
1167
1168 if (tracefs) {
1169 g_traceFolder = tracefs_path;
1170 } else {
1171 g_traceFolder = debugfs_path;
1172 }
1173
1174 return true;
1175}
1176
Wei Wang16a63a42018-09-21 15:47:45 -07001177void initVendorCategories()
1178{
1179 g_atraceHal = IAtraceDevice::getService();
1180
1181 if (g_atraceHal == nullptr) {
1182 // No atrace HAL
1183 return;
1184 }
1185
1186 Return<void> ret = g_atraceHal->listCategories(
1187 [](const auto& list) {
1188 g_vendorCategories.reserve(list.size());
1189 for (const auto& category : list) {
1190 g_vendorCategories.emplace_back(category.name, category.description, false);
1191 }
1192 });
1193 if (!ret.isOk()) {
1194 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1195 }
1196}
1197
1198static bool setUpVendorTracing()
1199{
1200 if (g_atraceHal == nullptr) {
1201 // No atrace HAL
1202 return true;
1203 }
1204
1205 std::vector<hidl_string> categories;
1206 for (const auto &c : g_vendorCategories) {
1207 if (c.enabled) {
1208 categories.emplace_back(c.name);
1209 }
1210 }
1211
1212 if (!categories.size()) {
1213 return true;
1214 }
1215
1216 auto ret = g_atraceHal->enableCategories(categories);
1217 if (!ret.isOk()) {
1218 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1219 return false;
1220 } else if (ret != Status::SUCCESS) {
1221 fprintf(stderr, "calling atrace HAL failed: %s\n", toString(ret).c_str());
1222 return false;
1223 }
1224 return true;
1225}
1226
1227static bool cleanUpVendorTracing()
1228{
1229 if (g_atraceHal == nullptr) {
1230 // No atrace HAL
1231 return true;
1232 }
1233
1234 if (!g_vendorCategories.size()) {
1235 // No vendor categories
1236 return true;
1237 }
1238
1239 auto ret = g_atraceHal->disableAllCategories();
1240 if (!ret.isOk()) {
1241 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1242 return false;
1243 } else if (ret != Status::SUCCESS) {
1244 fprintf(stderr, "calling atrace HAL failed: %s\n", toString(ret).c_str());
1245 return false;
1246 }
1247 return true;
1248}
1249
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001250int main(int argc, char **argv)
1251{
1252 bool async = false;
1253 bool traceStart = true;
1254 bool traceStop = true;
1255 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001256 bool traceStream = false;
Hector Dearman11845782018-03-08 14:35:44 +00001257 bool onlyUserspace = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001258
1259 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1260 showHelp(argv[0]);
1261 exit(0);
1262 }
1263
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001264 if (!findTraceFiles()) {
1265 fprintf(stderr, "No trace folder found\n");
1266 exit(-1);
1267 }
1268
Wei Wang16a63a42018-09-21 15:47:45 -07001269 initVendorCategories();
1270
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001271 for (;;) {
1272 int ret;
1273 int option_index = 0;
1274 static struct option long_options[] = {
Yi Kong19d5c002018-07-20 13:39:55 -07001275 {"async_start", no_argument, nullptr, 0 },
1276 {"async_stop", no_argument, nullptr, 0 },
1277 {"async_dump", no_argument, nullptr, 0 },
1278 {"only_userspace", no_argument, nullptr, 0 },
1279 {"list_categories", no_argument, nullptr, 0 },
1280 {"stream", no_argument, nullptr, 0 },
1281 {nullptr, 0, nullptr, 0 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001282 };
1283
John Reck40b26b42016-03-30 09:44:36 -07001284 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001285 long_options, &option_index);
1286
1287 if (ret < 0) {
1288 for (int i = optind; i < argc; i++) {
Wei Wang16a63a42018-09-21 15:47:45 -07001289 if (!setCategoryEnable(argv[i])) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001290 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1291 exit(1);
1292 }
1293 }
1294 break;
1295 }
1296
1297 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001298 case 'a':
1299 g_debugAppCmdLine = optarg;
1300 break;
1301
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001302 case 'b':
1303 g_traceBufferSizeKB = atoi(optarg);
1304 break;
1305
1306 case 'c':
1307 g_traceOverwrite = true;
1308 break;
1309
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001310 case 'f':
1311 g_categoriesFile = optarg;
1312 break;
1313
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001314 case 'k':
1315 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001316 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001317
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001318 case 'n':
1319 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001320 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001321
1322 case 's':
1323 g_initialSleepSecs = atoi(optarg);
1324 break;
1325
1326 case 't':
1327 g_traceDurationSeconds = atoi(optarg);
1328 break;
1329
1330 case 'z':
1331 g_compress = true;
1332 break;
1333
John Reck40b26b42016-03-30 09:44:36 -07001334 case 'o':
1335 g_outputFile = optarg;
1336 break;
1337
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001338 case 0:
1339 if (!strcmp(long_options[option_index].name, "async_start")) {
1340 async = true;
1341 traceStop = false;
1342 traceDump = false;
1343 g_traceOverwrite = true;
1344 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1345 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001346 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001347 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1348 async = true;
1349 traceStart = false;
1350 traceStop = false;
Hector Dearman11845782018-03-08 14:35:44 +00001351 } else if (!strcmp(long_options[option_index].name, "only_userspace")) {
1352 onlyUserspace = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001353 } else if (!strcmp(long_options[option_index].name, "stream")) {
1354 traceStream = true;
1355 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001356 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1357 listSupportedCategories();
1358 exit(0);
1359 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001360 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001361
1362 default:
1363 fprintf(stderr, "\n");
1364 showHelp(argv[0]);
1365 exit(-1);
1366 break;
1367 }
1368 }
1369
Hector Dearman11845782018-03-08 14:35:44 +00001370 if (onlyUserspace) {
1371 if (!async || !(traceStart || traceStop)) {
1372 fprintf(stderr, "--only_userspace can only be used with "
1373 "--async_start or --async_stop\n");
1374 exit(1);
1375 }
1376 }
1377
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001378 registerSigHandler();
1379
1380 if (g_initialSleepSecs > 0) {
1381 sleep(g_initialSleepSecs);
1382 }
1383
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001384 bool ok = true;
Hector Dearman11845782018-03-08 14:35:44 +00001385
Wei Wang5b73b742018-03-08 13:33:12 -08001386 if (traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001387 ok &= setUpUserspaceTracing();
1388 }
1389
1390 if (ok && traceStart && !onlyUserspace) {
1391 ok &= setUpKernelTracing();
Wei Wang16a63a42018-09-21 15:47:45 -07001392 ok &= setUpVendorTracing();
Wei Wang5b73b742018-03-08 13:33:12 -08001393 ok &= startTrace();
1394 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001395
1396 if (ok && traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001397
1398 if (!traceStream && !onlyUserspace) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001399 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001400 fflush(stdout);
1401 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001402
1403 // We clear the trace after starting it because tracing gets enabled for
1404 // each CPU individually in the kernel. Having the beginning of the trace
1405 // contain entries from only one CPU can cause "begin" entries without a
1406 // matching "end" entry to show up if a task gets migrated from one CPU to
1407 // another.
Hector Dearman11845782018-03-08 14:35:44 +00001408 if (!onlyUserspace)
1409 ok = clearTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001410
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001411 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001412 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001413 // Sleep to allow the trace to be captured.
1414 struct timespec timeLeft;
1415 timeLeft.tv_sec = g_traceDurationSeconds;
1416 timeLeft.tv_nsec = 0;
1417 do {
1418 if (g_traceAborted) {
1419 break;
1420 }
1421 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1422 }
Martijn Coenend9535872015-11-26 10:00:55 +01001423
1424 if (traceStream) {
1425 streamTrace();
1426 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001427 }
1428
1429 // Stop the trace and restore the default settings.
Hector Dearman11845782018-03-08 14:35:44 +00001430 if (traceStop && !onlyUserspace)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001431 stopTrace();
1432
Hector Dearman11845782018-03-08 14:35:44 +00001433 if (ok && traceDump && !onlyUserspace) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001434 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001435 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001436 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001437 int outFd = STDOUT_FILENO;
1438 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001439 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001440 }
1441 if (outFd == -1) {
1442 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1443 } else {
1444 dprintf(outFd, "TRACE:\n");
1445 dumpTrace(outFd);
1446 if (g_outputFile) {
1447 close(outFd);
1448 }
1449 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001450 } else {
1451 printf("\ntrace aborted.\n");
1452 fflush(stdout);
1453 }
1454 clearTrace();
1455 } else if (!ok) {
1456 fprintf(stderr, "unable to start tracing\n");
1457 }
1458
1459 // Reset the trace buffer size to 1.
Hector Dearman11845782018-03-08 14:35:44 +00001460 if (traceStop) {
Wei Wang16a63a42018-09-21 15:47:45 -07001461 cleanUpVendorTracing();
Hector Dearman11845782018-03-08 14:35:44 +00001462 cleanUpUserspaceTracing();
1463 if (!onlyUserspace)
1464 cleanUpKernelTracing();
1465 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001466
1467 return g_traceAborted ? 1 : 0;
1468}