blob: cedff0ba8ac3941f48f2301dff5d207af2186e89 [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
Wei Wang963999c2021-03-17 16:28:59 -070065#define MAX_SYS_FILES 12
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[] = {
Yiwei Zhang63775062020-09-18 11:42:33 -0700102 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, {
103 { OPT, "events/gpu_mem/gpu_mem_total/enable" },
104 } },
MÃ¥rten Kongstad2d4f89b2018-12-03 12:58:56 +0100105 { "input", "Input", ATRACE_TAG_INPUT, { } },
106 { "view", "View System", ATRACE_TAG_VIEW, { } },
107 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
108 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
109 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
110 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
111 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
112 { "video", "Video", ATRACE_TAG_VIDEO, { } },
113 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
114 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
115 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
116 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
117 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
118 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
119 { "power", "Power Management", ATRACE_TAG_POWER, { } },
120 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
121 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
122 { "database", "Database", ATRACE_TAG_DATABASE, { } },
123 { "network", "Network", ATRACE_TAG_NETWORK, { } },
124 { "adb", "ADB", ATRACE_TAG_ADB, { } },
125 { "vibrator", "Vibrator", ATRACE_TAG_VIBRATOR, { } },
126 { "aidl", "AIDL calls", ATRACE_TAG_AIDL, { } },
127 { "nnapi", "NNAPI", ATRACE_TAG_NNAPI, { } },
128 { "rro", "Runtime Resource Overlay", ATRACE_TAG_RRO, { } },
Chienyuan Huang53a8b412020-08-20 08:42:31 +0000129 { "sysprop", "System Property", ATRACE_TAG_SYSPROP, { } },
sergeyvdb404152016-05-02 19:26:07 -0700130 { k_coreServiceCategory, "Core services", 0, { } },
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700131 { k_pdxServiceCategory, "PDX services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700132 { "sched", "CPU Scheduling", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800133 { REQ, "events/sched/sched_switch/enable" },
134 { REQ, "events/sched/sched_wakeup/enable" },
Joel Fernandesee593e22017-06-04 13:05:59 -0700135 { OPT, "events/sched/sched_waking/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800136 { OPT, "events/sched/sched_blocked_reason/enable" },
137 { OPT, "events/sched/sched_cpu_hotplug/enable" },
Wei Wangca49dfc2018-05-03 15:45:20 -0700138 { OPT, "events/sched/sched_pi_setprio/enable" },
Carmen Jackson63ea2912019-04-26 10:41:00 -0700139 { OPT, "events/sched/sched_process_exit/enable" },
Joel Fernandes4dfca7c2017-06-15 16:53:52 -0700140 { OPT, "events/cgroup/enable" },
Carmen Jackson63ea2912019-04-26 10:41:00 -0700141 { OPT, "events/oom/oom_score_adj_update/enable" },
142 { OPT, "events/task/task_rename/enable" },
143 { OPT, "events/task/task_newtask/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800144 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700145 { "irq", "IRQ Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800146 { REQ, "events/irq/enable" },
147 { OPT, "events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700148 } },
Joel Fernandes6ccad102017-08-31 08:35:05 -0700149 { "irqoff", "IRQ-disabled code section tracing", 0, {
150 { REQ, "events/preemptirq/irq_enable/enable" },
151 { REQ, "events/preemptirq/irq_disable/enable" },
152 } },
153 { "preemptoff", "Preempt-disabled code section tracing", 0, {
154 { REQ, "events/preemptirq/preempt_enable/enable" },
155 { REQ, "events/preemptirq/preempt_disable/enable" },
156 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100157 { "i2c", "I2C Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800158 { REQ, "events/i2c/enable" },
159 { REQ, "events/i2c/i2c_read/enable" },
160 { REQ, "events/i2c/i2c_write/enable" },
161 { REQ, "events/i2c/i2c_result/enable" },
162 { REQ, "events/i2c/i2c_reply/enable" },
163 { OPT, "events/i2c/smbus_read/enable" },
164 { OPT, "events/i2c/smbus_write/enable" },
165 { OPT, "events/i2c/smbus_result/enable" },
166 { OPT, "events/i2c/smbus_reply/enable" },
Michael Wright43fb6782016-08-18 19:56:43 +0100167 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700168 { "freq", "CPU Frequency", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800169 { REQ, "events/power/cpu_frequency/enable" },
170 { OPT, "events/power/clock_set_rate/enable" },
Kevin DuBois062e0b92017-11-03 15:44:08 -0700171 { OPT, "events/power/clock_disable/enable" },
172 { OPT, "events/power/clock_enable/enable" },
Wei Wang53305dd2018-02-22 11:40:07 -0800173 { OPT, "events/clk/clk_set_rate/enable" },
174 { OPT, "events/clk/clk_disable/enable" },
175 { OPT, "events/clk/clk_enable/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800176 { OPT, "events/power/cpu_frequency_limits/enable" },
Carmen Jackson5ab84322019-08-08 14:35:47 -0700177 { OPT, "events/power/suspend_resume/enable" },
Wei Wang2ded52d2020-07-31 01:13:58 -0700178 { OPT, "events/cpuhp/cpuhp_enter/enable" },
179 { OPT, "events/cpuhp/cpuhp_exit/enable" },
Wei Wang963999c2021-03-17 16:28:59 -0700180 { OPT, "events/cpuhp/cpuhp_pause/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800181 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700182 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800183 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800184 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700185 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800186 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800187 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700188 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800189 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
190 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
191 { OPT, "events/f2fs/f2fs_write_begin/enable" },
192 { OPT, "events/f2fs/f2fs_write_end/enable" },
193 { OPT, "events/ext4/ext4_da_write_begin/enable" },
194 { OPT, "events/ext4/ext4_da_write_end/enable" },
195 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
196 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
197 { REQ, "events/block/block_rq_issue/enable" },
198 { REQ, "events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800199 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700200 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800201 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700202 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700203 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800204 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800205 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700206 { "sync", "Synchronization", 0, {
Jesse Halla978cef2019-02-25 16:24:10 -0800207 // linux kernel < 4.9
Jesse Hallae001a32018-05-15 12:02:15 -0700208 { OPT, "events/sync/enable" },
Jesse Halla978cef2019-02-25 16:24:10 -0800209 // linux kernel == 4.9.x
Jesse Hallae001a32018-05-15 12:02:15 -0700210 { OPT, "events/fence/enable" },
Jesse Halla978cef2019-02-25 16:24:10 -0800211 // linux kernel > 4.9
212 { OPT, "events/dma_fence/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800213 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700214 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800215 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800216 } },
Colin Cross580407f2014-08-18 15:22:13 -0700217 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800218 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
219 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
220 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
221 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Carmen Jackson7a23eb72018-07-02 13:14:56 -0700222 { OPT, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700223 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800224 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800225 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800226 } },
Scott Bauerae473362015-06-08 16:32:36 -0700227 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800228 { REQ, "events/binder/binder_transaction/enable" },
229 { REQ, "events/binder/binder_transaction_received/enable" },
Mika Raento80c3e5d2018-06-25 16:47:24 +0100230 { REQ, "events/binder/binder_transaction_alloc_buf/enable" },
Martijn Coenen7f3d7a22017-05-26 09:50:55 -0700231 { OPT, "events/binder/binder_set_priority/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700232 } },
233 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800234 { OPT, "events/binder/binder_lock/enable" },
235 { OPT, "events/binder/binder_locked/enable" },
236 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700237 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200238 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800239 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200240 } },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700241 { "memory", "Memory", 0, {
Collin Fijalkovich08e3f4a2020-03-30 16:20:24 -0700242 { OPT, "events/mm_event/mm_event_record/enable" },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700243 { OPT, "events/kmem/rss_stat/enable" },
244 { OPT, "events/kmem/ion_heap_grow/enable" },
245 { OPT, "events/kmem/ion_heap_shrink/enable" },
Ioannis Ilkos88a85f32020-04-23 22:43:40 +0100246 { OPT, "events/ion/ion_stat/enable" },
Yiwei Zhang63775062020-09-18 11:42:33 -0700247 { OPT, "events/gpu_mem/gpu_mem_total/enable" },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700248 } },
Wei Wange3079a92020-07-08 15:33:20 -0700249 { "thermal", "Thermal event", 0, {
250 { REQ, "events/thermal/thermal_temperature/enable" },
251 { OPT, "events/thermal/cdev_update/enable" },
252 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800253};
254
Wei Wang16a63a42018-09-21 15:47:45 -0700255struct TracingVendorCategory {
256 // The name identifying the category.
257 std::string name;
258
259 // A longer description of the category.
260 std::string description;
261
262 // If the category is enabled through command.
263 bool enabled;
264
265 TracingVendorCategory(string &&name, string &&description, bool enabled)
266 : name(std::move(name))
267 , description(std::move(description))
268 , enabled(enabled)
269 {}
270};
271
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800272/* Command line options */
273static int g_traceDurationSeconds = 5;
274static bool g_traceOverwrite = false;
275static int g_traceBufferSizeKB = 2048;
276static bool g_compress = false;
277static bool g_nohup = false;
278static int g_initialSleepSecs = 0;
Yi Kong19d5c002018-07-20 13:39:55 -0700279static const char* g_categoriesFile = nullptr;
280static const char* g_kernelTraceFuncs = nullptr;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700281static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700282static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800283
284/* Global state */
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700285static bool g_tracePdx = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800286static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700287static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800288static std::string g_traceFolder;
Wei Wang16a63a42018-09-21 15:47:45 -0700289static sp<IAtraceDevice> g_atraceHal;
290static std::vector<TracingVendorCategory> g_vendorCategories;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800291
292/* Sys file paths */
293static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800294 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800295
296static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800297 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800298
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700299#if 0
300// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700301static const char* k_traceCmdlineSizePath =
302 "saved_cmdlines_size";
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700303#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700304
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800305static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800306 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800307
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700308static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800309 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700310
311static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800312 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700313
John Recke757b1c2018-06-28 12:24:33 -0700314static const char* k_recordTgidPath =
315 "options/record-tgid";
316
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700317static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800318 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700319
320static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800321 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700322
323static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800324 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700325
326static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800327 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700328
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700329static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800330 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700331
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800332static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800333 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800334
335static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800336 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800337
Martijn Coenend9535872015-11-26 10:00:55 +0100338static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800339 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100340
John Reck469a1942015-03-26 15:31:35 -0700341static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800342 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700343
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800344// Check whether a file exists.
345static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800346 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800347}
348
349// Check whether a file is writable.
350static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800351 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800352}
353
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700354// Truncate a file.
355static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800356{
Jamie Gennis43122e72013-03-21 14:06:31 -0700357 // This uses creat rather than truncate because some of the debug kernel
358 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
359 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800360 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700361 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800362 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700363 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700364 return false;
365 }
366
Jamie Gennis43122e72013-03-21 14:06:31 -0700367 close(traceFD);
368
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700369 return true;
370}
371
372static bool _writeStr(const char* filename, const char* str, int flags)
373{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800374 std::string fullFilename = g_traceFolder + filename;
375 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800376 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800377 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800378 strerror(errno), errno);
379 return false;
380 }
381
382 bool ok = true;
383 ssize_t len = strlen(str);
384 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800385 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800386 strerror(errno), errno);
387 ok = false;
388 }
389
390 close(fd);
391
392 return ok;
393}
394
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700395// Write a string to a file, returning true if the write was successful.
396static bool writeStr(const char* filename, const char* str)
397{
398 return _writeStr(filename, str, O_WRONLY);
399}
400
401// Append a string to a file, returning true if the write was successful.
402static bool appendStr(const char* filename, const char* str)
403{
404 return _writeStr(filename, str, O_APPEND|O_WRONLY);
405}
406
John Reck469a1942015-03-26 15:31:35 -0700407static void writeClockSyncMarker()
408{
409 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200410 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800411 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200412 if (fd == -1) {
413 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
414 strerror(errno), errno);
415 return;
416 }
John Reck469a1942015-03-26 15:31:35 -0700417 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200418
419 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
420 if (write(fd, buffer, len) != len) {
421 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
422 }
423
424 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
425 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
426 if (write(fd, buffer, len) != len) {
427 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
428 }
429
430 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700431}
432
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800433// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
434// file.
435static bool setKernelOptionEnable(const char* filename, bool enable)
436{
437 return writeStr(filename, enable ? "1" : "0");
438}
439
440// Check whether the category is supported on the device with the current
441// rootness. A category is supported only if all its required /sys/ files are
442// writable and if enabling the category will enable one or more tracing tags
443// or /sys/ files.
444static bool isCategorySupported(const TracingCategory& category)
445{
sergeyvdb404152016-05-02 19:26:07 -0700446 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700447 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700448 }
449
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700450 if (strcmp(category.name, k_pdxServiceCategory) == 0) {
451 return true;
452 }
453
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800454 bool ok = category.tags != 0;
455 for (int i = 0; i < MAX_SYS_FILES; i++) {
456 const char* path = category.sysfiles[i].path;
457 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700458 if (path != nullptr) {
Carmen Jackson5bbc9a22018-12-06 13:47:18 -0800459 if (fileIsWritable(path)) {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800460 ok = true;
Carmen Jackson5bbc9a22018-12-06 13:47:18 -0800461 } else if (req) {
462 return false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800463 }
464 }
465 }
466 return ok;
467}
468
469// Check whether the category would be supported on the device if the user
470// were root. This function assumes that root is able to write to any file
471// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700472// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800473static bool isCategorySupportedForRoot(const TracingCategory& category)
474{
475 bool ok = category.tags != 0;
476 for (int i = 0; i < MAX_SYS_FILES; i++) {
477 const char* path = category.sysfiles[i].path;
478 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700479 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800480 if (req) {
481 if (!fileExists(path)) {
482 return false;
483 } else {
484 ok = true;
485 }
486 } else {
487 ok |= fileExists(path);
488 }
489 }
490 }
491 return ok;
492}
493
494// Enable or disable overwriting of the kernel trace buffers. Disabling this
495// will cause tracing to stop once the trace buffers have filled up.
496static bool setTraceOverwriteEnable(bool enable)
497{
498 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
499}
500
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700501// Set the user initiated trace property
502static bool setUserInitiatedTraceProperty(bool enable)
503{
504 if (!android::base::SetProperty(k_userInitiatedTraceProperty, enable ? "1" : "")) {
505 fprintf(stderr, "error setting user initiated strace system property\n");
506 return false;
507 }
508 return true;
509}
510
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800511// Enable or disable kernel tracing.
512static bool setTracingEnabled(bool enable)
513{
514 return setKernelOptionEnable(k_tracingOnPath, enable);
515}
516
517// Clear the contents of the kernel trace.
518static bool clearTrace()
519{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700520 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800521}
522
523// Set the size of the kernel's trace buffer in kilobytes.
524static bool setTraceBufferSizeKB(int size)
525{
526 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800527 if (size < 1) {
528 size = 1;
529 }
530 snprintf(str, 32, "%d", size);
531 return writeStr(k_traceBufferSizePath, str);
532}
533
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700534#if 0
535// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700536// Set the default size of cmdline hashtable
537static bool setCmdlineSize()
538{
Joel Fernandesce964f22017-06-06 12:20:29 -0700539 if (fileExists(k_traceCmdlineSizePath)) {
540 return writeStr(k_traceCmdlineSizePath, "8192");
541 }
542 return true;
Joel Fernandesed80bd02017-06-02 10:19:28 -0700543}
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700544#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700545
Carmen Jacksonea826792017-05-05 11:42:32 -0700546// Set the clock to the best available option while tracing. Use 'boot' if it's
547// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700548// Any write to the trace_clock sysfs file will reset the buffer, so only
549// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700550static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800551{
Carmen Jacksonea826792017-05-05 11:42:32 -0700552 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
553 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
554 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700555
Carmen Jacksonea826792017-05-05 11:42:32 -0700556 std::string newClock;
557 if (clockStr.find("boot") != std::string::npos) {
558 newClock = "boot";
559 } else if (clockStr.find("mono") != std::string::npos) {
560 newClock = "mono";
561 } else {
562 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700563 }
564
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700565 size_t begin = clockStr.find('[') + 1;
566 size_t end = clockStr.find(']');
Carmen Jacksonea826792017-05-05 11:42:32 -0700567 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
568 return true;
569 }
570 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800571}
572
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700573static bool setPrintTgidEnableIfPresent(bool enable)
574{
John Reckedbf9ec2018-06-29 11:15:17 -0700575 // Pre-4.13 this was options/print-tgid as an android-specific option.
576 // In 4.13+ this is an upstream option called options/record-tgid
577 // Both options produce the same ftrace format change
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700578 if (fileExists(k_printTgidPath)) {
579 return setKernelOptionEnable(k_printTgidPath, enable);
580 }
John Recke757b1c2018-06-28 12:24:33 -0700581 if (fileExists(k_recordTgidPath)) {
582 return setKernelOptionEnable(k_recordTgidPath, enable);
583 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700584 return true;
585}
586
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800587// Set the trace tags that userland tracing uses, and poke the running
588// processes to pick up the new value.
589static bool setTagsProperty(uint64_t tags)
590{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700591 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
592 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800593 fprintf(stderr, "error setting trace tags system property\n");
594 return false;
595 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700596 return true;
597}
598
sergeyv4144eff2016-04-28 11:40:04 -0700599static void clearAppProperties()
600{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700601 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700602 fprintf(stderr, "failed to clear system property: %s",
603 k_traceAppsNumberProperty);
604 }
605}
606
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700607// Set the system property that indicates which apps should perform
608// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700609static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700610{
sergeyv4144eff2016-04-28 11:40:04 -0700611 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700612 char* start = cmdline;
Yi Kong19d5c002018-07-20 13:39:55 -0700613 while (start != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700614 char* end = strchr(start, ',');
Yi Kong19d5c002018-07-20 13:39:55 -0700615 if (end != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700616 *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;
Yi Kong19d5c002018-07-20 13:39:55 -0700645 if (path != nullptr && fileIsWritable(path)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800646 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 }
Yi Kong19d5c002018-07-20 13:39:55 -0700681 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700682 }
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
Yi Kong19d5c002018-07-20 13:39:55 -0700692 if (funcs == nullptr || funcs[0] == '\0') {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700693 // 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);
Yi Kong19d5c002018-07-20 13:39:55 -0700714 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700715 }
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
Wei Wang16a63a42018-09-21 15:47:45 -0700727static bool setCategoryEnable(const char* name)
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900728{
Wei Wang16a63a42018-09-21 15:47:45 -0700729 bool vendor_found = false;
730 for (auto &c : g_vendorCategories) {
731 if (strcmp(name, c.name.c_str()) == 0) {
732 c.enabled = true;
733 vendor_found = true;
734 }
735 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700736 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900737 const TracingCategory& c = k_categories[i];
738 if (strcmp(name, c.name) == 0) {
739 if (isCategorySupported(c)) {
Wei Wang16a63a42018-09-21 15:47:45 -0700740 g_categoryEnables[i] = true;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900741 return true;
742 } else {
743 if (isCategorySupportedForRoot(c)) {
744 fprintf(stderr, "error: category \"%s\" requires root "
745 "privileges.\n", name);
746 } else {
747 fprintf(stderr, "error: category \"%s\" is not supported "
748 "on this device.\n", name);
749 }
750 return false;
751 }
752 }
753 }
Wei Wang16a63a42018-09-21 15:47:45 -0700754 if (vendor_found) {
755 return true;
756 }
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900757 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
758 return false;
759}
760
761static bool setCategoriesEnableFromFile(const char* categories_file)
762{
763 if (!categories_file) {
764 return true;
765 }
Yi Kong19d5c002018-07-20 13:39:55 -0700766 Tokenizer* tokenizer = nullptr;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900767 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
768 return false;
769 }
770 bool ok = true;
771 while (!tokenizer->isEol()) {
772 String8 token = tokenizer->nextToken(" ");
773 if (token.isEmpty()) {
774 tokenizer->skipDelimiters(" ");
775 continue;
776 }
Wei Wang16a63a42018-09-21 15:47:45 -0700777 ok &= setCategoryEnable(token.string());
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900778 }
779 delete tokenizer;
780 return ok;
781}
782
Hector Dearman11845782018-03-08 14:35:44 +0000783static bool setUpUserspaceTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800784{
785 bool ok = true;
786
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800787 // Set up the tags property.
788 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700789 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800790 if (g_categoryEnables[i]) {
791 const TracingCategory &c = k_categories[i];
792 tags |= c.tags;
793 }
794 }
sergeyvdb404152016-05-02 19:26:07 -0700795
796 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700797 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700798 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
799 coreServicesTagEnabled = g_categoryEnables[i];
800 }
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700801
802 // Set whether to poke PDX services in this session.
803 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
804 g_tracePdx = g_categoryEnables[i];
805 }
sergeyvdb404152016-05-02 19:26:07 -0700806 }
807
808 std::string packageList(g_debugAppCmdLine);
809 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700810 if (!packageList.empty()) {
811 packageList += ",";
812 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700813 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700814 }
Dan Austin09a79872016-05-31 13:27:03 -0700815 ok &= setAppCmdlineProperty(&packageList[0]);
Florian Mayer6263b582019-12-10 13:28:45 +0000816 ok &= setTagsProperty(tags);
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700817 if (g_tracePdx) {
818 ok &= ServiceUtility::PokeServices();
819 }
820
Hector Dearman11845782018-03-08 14:35:44 +0000821 return ok;
822}
823
824static void cleanUpUserspaceTracing()
825{
826 setTagsProperty(0);
827 clearAppProperties();
Hector Dearman11845782018-03-08 14:35:44 +0000828
829 if (g_tracePdx) {
830 ServiceUtility::PokeServices();
831 }
832}
833
834
835// Set all the kernel tracing settings to the desired state for this trace
836// capture.
837static bool setUpKernelTracing()
838{
839 bool ok = true;
840
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700841 ok &= setUserInitiatedTraceProperty(true);
842
Hector Dearman11845782018-03-08 14:35:44 +0000843 // Set up the tracing options.
844 ok &= setCategoriesEnableFromFile(g_categoriesFile);
845 ok &= setTraceOverwriteEnable(g_traceOverwrite);
846 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
847 // TODO: Re-enable after stabilization
848 //ok &= setCmdlineSize();
849 ok &= setClock();
850 ok &= setPrintTgidEnableIfPresent(true);
851 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
852
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800853 // Disable all the sysfs enables. This is done as a separate loop from
854 // the enables to allow the same enable to exist in multiple categories.
855 ok &= disableKernelTraceEvents();
856
857 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700858 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800859 if (g_categoryEnables[i]) {
860 const TracingCategory &c = k_categories[i];
861 for (int j = 0; j < MAX_SYS_FILES; j++) {
862 const char* path = c.sysfiles[j].path;
863 bool required = c.sysfiles[j].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700864 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800865 if (fileIsWritable(path)) {
866 ok &= setKernelOptionEnable(path, true);
867 } else if (required) {
868 fprintf(stderr, "error writing file %s\n", path);
869 ok = false;
870 }
871 }
872 }
873 }
874 }
875
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800876 return ok;
877}
878
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700879// Reset all the kernel tracing settings to their default state.
Hector Dearman11845782018-03-08 14:35:44 +0000880static void cleanUpKernelTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800881{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800882 // Disable all tracing that we're able to.
883 disableKernelTraceEvents();
884
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800885 // Set the options back to their defaults.
886 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700887 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700888 setPrintTgidEnableIfPresent(false);
Yi Kong19d5c002018-07-20 13:39:55 -0700889 setKernelTraceFuncs(nullptr);
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700890 setUserInitiatedTraceProperty(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700891}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800892
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700893// Enable tracing in the kernel.
894static bool startTrace()
895{
896 return setTracingEnabled(true);
897}
898
899// Disable tracing in the kernel.
900static void stopTrace()
901{
902 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800903}
904
Martijn Coenend9535872015-11-26 10:00:55 +0100905// Read data from the tracing pipe and forward to stdout
906static void streamTrace()
907{
908 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800909 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100910 if (traceFD == -1) {
911 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
912 strerror(errno), errno);
913 return;
914 }
915 while (!g_traceAborted) {
916 ssize_t bytes_read = read(traceFD, trace_data, 4096);
917 if (bytes_read > 0) {
918 write(STDOUT_FILENO, trace_data, bytes_read);
919 fflush(stdout);
920 } else {
921 if (!g_traceAborted) {
922 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
923 bytes_read, errno, strerror(errno));
924 }
925 break;
926 }
927 }
928}
929
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800930// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700931static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800932{
John Reck6c8ac922016-03-28 11:25:30 -0700933 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800934 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800935 if (traceFD == -1) {
936 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
937 strerror(errno), errno);
938 return;
939 }
940
941 if (g_compress) {
942 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800943 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700944
945 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800946 if (result != Z_OK) {
947 fprintf(stderr, "error initializing zlib: %d\n", result);
948 close(traceFD);
949 return;
950 }
951
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700952 constexpr size_t bufSize = 64*1024;
953 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
954 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
955 if (!in || !out) {
956 fprintf(stderr, "couldn't allocate buffers\n");
957 close(traceFD);
958 return;
959 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800960
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700961 int flush = Z_NO_FLUSH;
962
963 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800964 zs.avail_out = bufSize;
965
966 do {
967
968 if (zs.avail_in == 0) {
969 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700970 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800971 if (result < 0) {
972 fprintf(stderr, "error reading trace: %s (%d)\n",
973 strerror(errno), errno);
974 result = Z_STREAM_END;
975 break;
976 } else if (result == 0) {
977 flush = Z_FINISH;
978 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700979 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800980 zs.avail_in = result;
981 }
982 }
983
984 if (zs.avail_out == 0) {
985 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700986 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800987 if ((size_t)result < bufSize) {
988 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
989 strerror(errno), errno);
990 result = Z_STREAM_END; // skip deflate error message
991 zs.avail_out = bufSize; // skip the final write
992 break;
993 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700994 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800995 zs.avail_out = bufSize;
996 }
997
998 } while ((result = deflate(&zs, flush)) == Z_OK);
999
1000 if (result != Z_STREAM_END) {
1001 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
1002 }
1003
1004 if (zs.avail_out < bufSize) {
1005 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -07001006 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001007 if ((size_t)result < bytes) {
1008 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1009 strerror(errno), errno);
1010 }
1011 }
1012
1013 result = deflateEnd(&zs);
1014 if (result != Z_OK) {
1015 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1016 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001017 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001018 char buf[4096];
1019 ssize_t rc;
1020 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1021 if (!android::base::WriteFully(outFd, buf, rc)) {
1022 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1023 break;
1024 }
1025 }
1026 if (rc == -1) {
1027 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001028 }
1029 }
1030
1031 close(traceFD);
1032}
1033
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001034static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001035{
1036 if (!g_nohup) {
1037 g_traceAborted = true;
1038 }
1039}
1040
1041static void registerSigHandler()
1042{
1043 struct sigaction sa;
1044 sigemptyset(&sa.sa_mask);
1045 sa.sa_flags = 0;
1046 sa.sa_handler = handleSignal;
Yi Kong19d5c002018-07-20 13:39:55 -07001047 sigaction(SIGHUP, &sa, nullptr);
1048 sigaction(SIGINT, &sa, nullptr);
1049 sigaction(SIGQUIT, &sa, nullptr);
1050 sigaction(SIGTERM, &sa, nullptr);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001051}
1052
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001053static void listSupportedCategories()
1054{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001055 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001056 const TracingCategory& c = k_categories[i];
1057 if (isCategorySupported(c)) {
1058 printf(" %10s - %s\n", c.name, c.longname);
1059 }
1060 }
Wei Wang16a63a42018-09-21 15:47:45 -07001061 for (const auto &c : g_vendorCategories) {
1062 printf(" %10s - %s (HAL)\n", c.name.c_str(), c.description.c_str());
1063 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001064}
1065
1066// Print the command usage help to stderr.
1067static void showHelp(const char *cmd)
1068{
1069 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1070 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001071 " -a appname enable app-level tracing for a comma "
Daniel Colascione519a0792018-02-09 20:05:39 -08001072 "separated list of cmdlines; * is a wildcard matching any process\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001073 " -b N use a trace buffer size of N KB\n"
1074 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001075 " -f filename use the categories written in a file as space-separated\n"
1076 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001077 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001078 " -n ignore signals\n"
1079 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001080 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001081 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001082 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001083 " --async_dump dump the current contents of circular trace buffer\n"
1084 " --async_stop stop tracing and dump the current contents of circular\n"
1085 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001086 " --stream stream trace to stdout as it enters the trace buffer\n"
1087 " Note: this can take significant CPU time, and is best\n"
1088 " used for measuring things that are not affected by\n"
1089 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001090 " --list_categories\n"
1091 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001092 " -o filename write the trace to the specified file instead\n"
1093 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001094 );
1095}
1096
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001097bool findTraceFiles()
1098{
1099 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1100 static const std::string tracefs_path = "/sys/kernel/tracing/";
1101 static const std::string trace_file = "trace_marker";
1102
1103 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1104 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1105
1106 if (!tracefs && !debugfs) {
1107 fprintf(stderr, "Error: Did not find trace folder\n");
1108 return false;
1109 }
1110
1111 if (tracefs) {
1112 g_traceFolder = tracefs_path;
1113 } else {
1114 g_traceFolder = debugfs_path;
1115 }
1116
1117 return true;
1118}
1119
Wei Wang16a63a42018-09-21 15:47:45 -07001120void initVendorCategories()
1121{
1122 g_atraceHal = IAtraceDevice::getService();
1123
1124 if (g_atraceHal == nullptr) {
1125 // No atrace HAL
1126 return;
1127 }
1128
1129 Return<void> ret = g_atraceHal->listCategories(
1130 [](const auto& list) {
1131 g_vendorCategories.reserve(list.size());
1132 for (const auto& category : list) {
1133 g_vendorCategories.emplace_back(category.name, category.description, false);
1134 }
1135 });
1136 if (!ret.isOk()) {
1137 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1138 }
1139}
1140
1141static bool setUpVendorTracing()
1142{
1143 if (g_atraceHal == nullptr) {
1144 // No atrace HAL
1145 return true;
1146 }
1147
1148 std::vector<hidl_string> categories;
1149 for (const auto &c : g_vendorCategories) {
1150 if (c.enabled) {
1151 categories.emplace_back(c.name);
1152 }
1153 }
1154
1155 if (!categories.size()) {
1156 return true;
1157 }
1158
1159 auto ret = g_atraceHal->enableCategories(categories);
1160 if (!ret.isOk()) {
1161 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1162 return false;
1163 } else if (ret != Status::SUCCESS) {
1164 fprintf(stderr, "calling atrace HAL failed: %s\n", toString(ret).c_str());
1165 return false;
1166 }
1167 return true;
1168}
1169
1170static bool cleanUpVendorTracing()
1171{
1172 if (g_atraceHal == nullptr) {
1173 // No atrace HAL
1174 return true;
1175 }
1176
1177 if (!g_vendorCategories.size()) {
1178 // No vendor categories
1179 return true;
1180 }
1181
1182 auto ret = g_atraceHal->disableAllCategories();
1183 if (!ret.isOk()) {
1184 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1185 return false;
1186 } else if (ret != Status::SUCCESS) {
1187 fprintf(stderr, "calling atrace HAL failed: %s\n", toString(ret).c_str());
1188 return false;
1189 }
1190 return true;
1191}
1192
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001193int main(int argc, char **argv)
1194{
1195 bool async = false;
1196 bool traceStart = true;
1197 bool traceStop = true;
1198 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001199 bool traceStream = false;
Hector Dearman11845782018-03-08 14:35:44 +00001200 bool onlyUserspace = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001201
1202 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1203 showHelp(argv[0]);
1204 exit(0);
1205 }
1206
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001207 if (!findTraceFiles()) {
1208 fprintf(stderr, "No trace folder found\n");
1209 exit(-1);
1210 }
1211
Wei Wang16a63a42018-09-21 15:47:45 -07001212 initVendorCategories();
1213
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001214 for (;;) {
1215 int ret;
1216 int option_index = 0;
1217 static struct option long_options[] = {
Yi Kong19d5c002018-07-20 13:39:55 -07001218 {"async_start", no_argument, nullptr, 0 },
1219 {"async_stop", no_argument, nullptr, 0 },
1220 {"async_dump", no_argument, nullptr, 0 },
1221 {"only_userspace", no_argument, nullptr, 0 },
1222 {"list_categories", no_argument, nullptr, 0 },
1223 {"stream", no_argument, nullptr, 0 },
1224 {nullptr, 0, nullptr, 0 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001225 };
1226
John Reck40b26b42016-03-30 09:44:36 -07001227 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001228 long_options, &option_index);
1229
1230 if (ret < 0) {
1231 for (int i = optind; i < argc; i++) {
Wei Wang16a63a42018-09-21 15:47:45 -07001232 if (!setCategoryEnable(argv[i])) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001233 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1234 exit(1);
1235 }
1236 }
1237 break;
1238 }
1239
1240 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001241 case 'a':
1242 g_debugAppCmdLine = optarg;
1243 break;
1244
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001245 case 'b':
1246 g_traceBufferSizeKB = atoi(optarg);
1247 break;
1248
1249 case 'c':
1250 g_traceOverwrite = true;
1251 break;
1252
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001253 case 'f':
1254 g_categoriesFile = optarg;
1255 break;
1256
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001257 case 'k':
1258 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001259 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001260
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001261 case 'n':
1262 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001263 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001264
1265 case 's':
1266 g_initialSleepSecs = atoi(optarg);
1267 break;
1268
1269 case 't':
1270 g_traceDurationSeconds = atoi(optarg);
1271 break;
1272
1273 case 'z':
1274 g_compress = true;
1275 break;
1276
John Reck40b26b42016-03-30 09:44:36 -07001277 case 'o':
1278 g_outputFile = optarg;
1279 break;
1280
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001281 case 0:
1282 if (!strcmp(long_options[option_index].name, "async_start")) {
1283 async = true;
1284 traceStop = false;
1285 traceDump = false;
1286 g_traceOverwrite = true;
1287 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1288 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001289 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001290 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1291 async = true;
1292 traceStart = false;
1293 traceStop = false;
Hector Dearman11845782018-03-08 14:35:44 +00001294 } else if (!strcmp(long_options[option_index].name, "only_userspace")) {
1295 onlyUserspace = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001296 } else if (!strcmp(long_options[option_index].name, "stream")) {
1297 traceStream = true;
1298 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001299 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1300 listSupportedCategories();
1301 exit(0);
1302 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001303 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001304
1305 default:
1306 fprintf(stderr, "\n");
1307 showHelp(argv[0]);
1308 exit(-1);
1309 break;
1310 }
1311 }
1312
Hector Dearman11845782018-03-08 14:35:44 +00001313 if (onlyUserspace) {
1314 if (!async || !(traceStart || traceStop)) {
1315 fprintf(stderr, "--only_userspace can only be used with "
1316 "--async_start or --async_stop\n");
1317 exit(1);
1318 }
1319 }
1320
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001321 registerSigHandler();
1322
1323 if (g_initialSleepSecs > 0) {
1324 sleep(g_initialSleepSecs);
1325 }
1326
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001327 bool ok = true;
Hector Dearman11845782018-03-08 14:35:44 +00001328
Wei Wang5b73b742018-03-08 13:33:12 -08001329 if (traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001330 ok &= setUpUserspaceTracing();
1331 }
1332
1333 if (ok && traceStart && !onlyUserspace) {
1334 ok &= setUpKernelTracing();
Wei Wang16a63a42018-09-21 15:47:45 -07001335 ok &= setUpVendorTracing();
Wei Wang5b73b742018-03-08 13:33:12 -08001336 ok &= startTrace();
1337 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001338
1339 if (ok && traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001340
1341 if (!traceStream && !onlyUserspace) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001342 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001343 fflush(stdout);
1344 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001345
1346 // We clear the trace after starting it because tracing gets enabled for
1347 // each CPU individually in the kernel. Having the beginning of the trace
1348 // contain entries from only one CPU can cause "begin" entries without a
1349 // matching "end" entry to show up if a task gets migrated from one CPU to
1350 // another.
Hector Dearman11845782018-03-08 14:35:44 +00001351 if (!onlyUserspace)
1352 ok = clearTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001353
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001354 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001355 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001356 // Sleep to allow the trace to be captured.
1357 struct timespec timeLeft;
1358 timeLeft.tv_sec = g_traceDurationSeconds;
1359 timeLeft.tv_nsec = 0;
1360 do {
1361 if (g_traceAborted) {
1362 break;
1363 }
1364 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1365 }
Martijn Coenend9535872015-11-26 10:00:55 +01001366
1367 if (traceStream) {
1368 streamTrace();
1369 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001370 }
1371
1372 // Stop the trace and restore the default settings.
Hector Dearman11845782018-03-08 14:35:44 +00001373 if (traceStop && !onlyUserspace)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001374 stopTrace();
1375
Hector Dearman11845782018-03-08 14:35:44 +00001376 if (ok && traceDump && !onlyUserspace) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001377 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001378 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001379 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001380 int outFd = STDOUT_FILENO;
1381 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001382 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001383 }
1384 if (outFd == -1) {
1385 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1386 } else {
1387 dprintf(outFd, "TRACE:\n");
1388 dumpTrace(outFd);
1389 if (g_outputFile) {
1390 close(outFd);
1391 }
1392 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001393 } else {
1394 printf("\ntrace aborted.\n");
1395 fflush(stdout);
1396 }
1397 clearTrace();
1398 } else if (!ok) {
1399 fprintf(stderr, "unable to start tracing\n");
1400 }
1401
1402 // Reset the trace buffer size to 1.
Hector Dearman11845782018-03-08 14:35:44 +00001403 if (traceStop) {
1404 cleanUpUserspaceTracing();
Hector Dearmanada0a4a2019-04-09 14:13:14 +01001405 if (!onlyUserspace) {
1406 cleanUpVendorTracing();
Hector Dearman11845782018-03-08 14:35:44 +00001407 cleanUpKernelTracing();
Hector Dearmanada0a4a2019-04-09 14:13:14 +01001408 }
Hector Dearman11845782018-03-08 14:35:44 +00001409 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001410
1411 return g_traceAborted ? 1 : 0;
1412}