blob: 79419d3ae64c759f36dd90a67baa03574d2f6cdd [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
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700326static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800327 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700328
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800329static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800330 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800331
332static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800333 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800334
Martijn Coenend9535872015-11-26 10:00:55 +0100335static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800336 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100337
John Reck469a1942015-03-26 15:31:35 -0700338static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800339 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700340
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800341// Check whether a file exists.
342static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800343 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800344}
345
346// Check whether a file is writable.
347static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800348 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800349}
350
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700351// Truncate a file.
352static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800353{
Jamie Gennis43122e72013-03-21 14:06:31 -0700354 // This uses creat rather than truncate because some of the debug kernel
355 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
356 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800357 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700358 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800359 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700360 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700361 return false;
362 }
363
Jamie Gennis43122e72013-03-21 14:06:31 -0700364 close(traceFD);
365
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700366 return true;
367}
368
369static bool _writeStr(const char* filename, const char* str, int flags)
370{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800371 std::string fullFilename = g_traceFolder + filename;
372 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800373 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800374 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800375 strerror(errno), errno);
376 return false;
377 }
378
379 bool ok = true;
380 ssize_t len = strlen(str);
381 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800382 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800383 strerror(errno), errno);
384 ok = false;
385 }
386
387 close(fd);
388
389 return ok;
390}
391
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700392// Write a string to a file, returning true if the write was successful.
393static bool writeStr(const char* filename, const char* str)
394{
395 return _writeStr(filename, str, O_WRONLY);
396}
397
398// Append a string to a file, returning true if the write was successful.
399static bool appendStr(const char* filename, const char* str)
400{
401 return _writeStr(filename, str, O_APPEND|O_WRONLY);
402}
403
John Reck469a1942015-03-26 15:31:35 -0700404static void writeClockSyncMarker()
405{
406 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200407 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800408 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200409 if (fd == -1) {
410 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
411 strerror(errno), errno);
412 return;
413 }
John Reck469a1942015-03-26 15:31:35 -0700414 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200415
416 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
417 if (write(fd, buffer, len) != len) {
418 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
419 }
420
421 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
422 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
423 if (write(fd, buffer, len) != len) {
424 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
425 }
426
427 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700428}
429
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800430// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
431// file.
432static bool setKernelOptionEnable(const char* filename, bool enable)
433{
434 return writeStr(filename, enable ? "1" : "0");
435}
436
437// Check whether the category is supported on the device with the current
438// rootness. A category is supported only if all its required /sys/ files are
439// writable and if enabling the category will enable one or more tracing tags
440// or /sys/ files.
441static bool isCategorySupported(const TracingCategory& category)
442{
sergeyvdb404152016-05-02 19:26:07 -0700443 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700444 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700445 }
446
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700447 if (strcmp(category.name, k_pdxServiceCategory) == 0) {
448 return true;
449 }
450
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800451 bool ok = category.tags != 0;
452 for (int i = 0; i < MAX_SYS_FILES; i++) {
453 const char* path = category.sysfiles[i].path;
454 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700455 if (path != nullptr) {
Carmen Jackson5bbc9a22018-12-06 13:47:18 -0800456 if (fileIsWritable(path)) {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800457 ok = true;
Carmen Jackson5bbc9a22018-12-06 13:47:18 -0800458 } else if (req) {
459 return false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800460 }
461 }
462 }
463 return ok;
464}
465
466// Check whether the category would be supported on the device if the user
467// were root. This function assumes that root is able to write to any file
468// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700469// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800470static bool isCategorySupportedForRoot(const TracingCategory& category)
471{
472 bool ok = category.tags != 0;
473 for (int i = 0; i < MAX_SYS_FILES; i++) {
474 const char* path = category.sysfiles[i].path;
475 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700476 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800477 if (req) {
478 if (!fileExists(path)) {
479 return false;
480 } else {
481 ok = true;
482 }
483 } else {
484 ok |= fileExists(path);
485 }
486 }
487 }
488 return ok;
489}
490
491// Enable or disable overwriting of the kernel trace buffers. Disabling this
492// will cause tracing to stop once the trace buffers have filled up.
493static bool setTraceOverwriteEnable(bool enable)
494{
495 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
496}
497
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700498// Set the user initiated trace property
499static bool setUserInitiatedTraceProperty(bool enable)
500{
501 if (!android::base::SetProperty(k_userInitiatedTraceProperty, enable ? "1" : "")) {
502 fprintf(stderr, "error setting user initiated strace system property\n");
503 return false;
504 }
505 return true;
506}
507
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800508// Enable or disable kernel tracing.
509static bool setTracingEnabled(bool enable)
510{
511 return setKernelOptionEnable(k_tracingOnPath, enable);
512}
513
514// Clear the contents of the kernel trace.
515static bool clearTrace()
516{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700517 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800518}
519
520// Set the size of the kernel's trace buffer in kilobytes.
521static bool setTraceBufferSizeKB(int size)
522{
523 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800524 if (size < 1) {
525 size = 1;
526 }
527 snprintf(str, 32, "%d", size);
528 return writeStr(k_traceBufferSizePath, str);
529}
530
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700531#if 0
532// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700533// Set the default size of cmdline hashtable
534static bool setCmdlineSize()
535{
Joel Fernandesce964f22017-06-06 12:20:29 -0700536 if (fileExists(k_traceCmdlineSizePath)) {
537 return writeStr(k_traceCmdlineSizePath, "8192");
538 }
539 return true;
Joel Fernandesed80bd02017-06-02 10:19:28 -0700540}
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700541#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700542
Carmen Jacksonea826792017-05-05 11:42:32 -0700543// Set the clock to the best available option while tracing. Use 'boot' if it's
544// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700545// Any write to the trace_clock sysfs file will reset the buffer, so only
546// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700547static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800548{
Carmen Jacksonea826792017-05-05 11:42:32 -0700549 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
550 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
551 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700552
Carmen Jacksonea826792017-05-05 11:42:32 -0700553 std::string newClock;
554 if (clockStr.find("boot") != std::string::npos) {
555 newClock = "boot";
556 } else if (clockStr.find("mono") != std::string::npos) {
557 newClock = "mono";
558 } else {
559 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700560 }
561
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700562 size_t begin = clockStr.find('[') + 1;
563 size_t end = clockStr.find(']');
Carmen Jacksonea826792017-05-05 11:42:32 -0700564 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
565 return true;
566 }
567 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800568}
569
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700570static bool setPrintTgidEnableIfPresent(bool enable)
571{
John Reckedbf9ec2018-06-29 11:15:17 -0700572 // Pre-4.13 this was options/print-tgid as an android-specific option.
573 // In 4.13+ this is an upstream option called options/record-tgid
574 // Both options produce the same ftrace format change
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700575 if (fileExists(k_printTgidPath)) {
576 return setKernelOptionEnable(k_printTgidPath, enable);
577 }
John Recke757b1c2018-06-28 12:24:33 -0700578 if (fileExists(k_recordTgidPath)) {
579 return setKernelOptionEnable(k_recordTgidPath, enable);
580 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700581 return true;
582}
583
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800584// Set the trace tags that userland tracing uses, and poke the running
585// processes to pick up the new value.
586static bool setTagsProperty(uint64_t tags)
587{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700588 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
589 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800590 fprintf(stderr, "error setting trace tags system property\n");
591 return false;
592 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700593 return true;
594}
595
sergeyv4144eff2016-04-28 11:40:04 -0700596static void clearAppProperties()
597{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700598 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700599 fprintf(stderr, "failed to clear system property: %s",
600 k_traceAppsNumberProperty);
601 }
602}
603
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700604// Set the system property that indicates which apps should perform
605// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700606static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700607{
sergeyv4144eff2016-04-28 11:40:04 -0700608 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700609 char* start = cmdline;
Yi Kong19d5c002018-07-20 13:39:55 -0700610 while (start != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700611 char* end = strchr(start, ',');
Yi Kong19d5c002018-07-20 13:39:55 -0700612 if (end != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700613 *end = '\0';
614 end++;
615 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700616 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
617 if (!android::base::SetProperty(key, start)) {
618 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700619 clearAppProperties();
620 return false;
621 }
622 start = end;
623 i++;
624 }
625
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700626 std::string value = android::base::StringPrintf("%d", i);
627 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
628 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700629 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700630 return false;
631 }
632 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800633}
634
635// Disable all /sys/ enable files.
636static bool disableKernelTraceEvents() {
637 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700638 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800639 const TracingCategory &c = k_categories[i];
640 for (int j = 0; j < MAX_SYS_FILES; j++) {
641 const char* path = c.sysfiles[j].path;
Yi Kong19d5c002018-07-20 13:39:55 -0700642 if (path != nullptr && fileIsWritable(path)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800643 ok &= setKernelOptionEnable(path, false);
644 }
645 }
646 }
647 return ok;
648}
649
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700650// Verify that the comma separated list of functions are being traced by the
651// kernel.
652static bool verifyKernelTraceFuncs(const char* funcs)
653{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100654 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800655 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100656 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700657 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100658 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700659 }
660
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100661 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700662
663 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100664 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700665 bool ok = true;
666 char* myFuncs = strdup(funcs);
667 char* func = strtok(myFuncs, ",");
668 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100669 if (!strchr(func, '*')) {
670 String8 fancyFunc = String8::format("\n%s\n", func);
671 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
672 if (!found || func[0] == '\0') {
673 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
674 "to trace.\n", func);
675 ok = false;
676 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700677 }
Yi Kong19d5c002018-07-20 13:39:55 -0700678 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700679 }
680 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700681 return ok;
682}
683
684// Set the comma separated list of functions that the kernel is to trace.
685static bool setKernelTraceFuncs(const char* funcs)
686{
687 bool ok = true;
688
Yi Kong19d5c002018-07-20 13:39:55 -0700689 if (funcs == nullptr || funcs[0] == '\0') {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700690 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700691 if (fileIsWritable(k_currentTracerPath)) {
692 ok &= writeStr(k_currentTracerPath, "nop");
693 }
694 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700695 ok &= truncateFile(k_ftraceFilterPath);
696 }
697 } else {
698 // Enable kernel function tracing.
699 ok &= writeStr(k_currentTracerPath, "function_graph");
700 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
701 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
702 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700703
704 // Set the requested filter functions.
705 ok &= truncateFile(k_ftraceFilterPath);
706 char* myFuncs = strdup(funcs);
707 char* func = strtok(myFuncs, ",");
708 while (func) {
709 ok &= appendStr(k_ftraceFilterPath, func);
Yi Kong19d5c002018-07-20 13:39:55 -0700710 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700711 }
712 free(myFuncs);
713
714 // Verify that the set functions are being traced.
715 if (ok) {
716 ok &= verifyKernelTraceFuncs(funcs);
717 }
718 }
719
720 return ok;
721}
722
Wei Wang16a63a42018-09-21 15:47:45 -0700723static bool setCategoryEnable(const char* name)
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900724{
Wei Wang16a63a42018-09-21 15:47:45 -0700725 bool vendor_found = false;
726 for (auto &c : g_vendorCategories) {
727 if (strcmp(name, c.name.c_str()) == 0) {
728 c.enabled = true;
729 vendor_found = true;
730 }
731 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700732 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900733 const TracingCategory& c = k_categories[i];
734 if (strcmp(name, c.name) == 0) {
735 if (isCategorySupported(c)) {
Wei Wang16a63a42018-09-21 15:47:45 -0700736 g_categoryEnables[i] = true;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900737 return true;
738 } else {
739 if (isCategorySupportedForRoot(c)) {
740 fprintf(stderr, "error: category \"%s\" requires root "
741 "privileges.\n", name);
742 } else {
743 fprintf(stderr, "error: category \"%s\" is not supported "
744 "on this device.\n", name);
745 }
746 return false;
747 }
748 }
749 }
Wei Wang16a63a42018-09-21 15:47:45 -0700750 if (vendor_found) {
751 return true;
752 }
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900753 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
754 return false;
755}
756
757static bool setCategoriesEnableFromFile(const char* categories_file)
758{
759 if (!categories_file) {
760 return true;
761 }
Yi Kong19d5c002018-07-20 13:39:55 -0700762 Tokenizer* tokenizer = nullptr;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900763 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
764 return false;
765 }
766 bool ok = true;
767 while (!tokenizer->isEol()) {
768 String8 token = tokenizer->nextToken(" ");
769 if (token.isEmpty()) {
770 tokenizer->skipDelimiters(" ");
771 continue;
772 }
Wei Wang16a63a42018-09-21 15:47:45 -0700773 ok &= setCategoryEnable(token.string());
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900774 }
775 delete tokenizer;
776 return ok;
777}
778
Hector Dearman11845782018-03-08 14:35:44 +0000779static bool setUpUserspaceTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800780{
781 bool ok = true;
782
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800783 // Set up the tags property.
784 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700785 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800786 if (g_categoryEnables[i]) {
787 const TracingCategory &c = k_categories[i];
788 tags |= c.tags;
789 }
790 }
sergeyvdb404152016-05-02 19:26:07 -0700791
792 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700793 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700794 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
795 coreServicesTagEnabled = g_categoryEnables[i];
796 }
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700797
798 // Set whether to poke PDX services in this session.
799 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
800 g_tracePdx = g_categoryEnables[i];
801 }
sergeyvdb404152016-05-02 19:26:07 -0700802 }
803
804 std::string packageList(g_debugAppCmdLine);
805 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700806 if (!packageList.empty()) {
807 packageList += ",";
808 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700809 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700810 }
Dan Austin09a79872016-05-31 13:27:03 -0700811 ok &= setAppCmdlineProperty(&packageList[0]);
Florian Mayer6263b582019-12-10 13:28:45 +0000812 ok &= setTagsProperty(tags);
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700813 if (g_tracePdx) {
814 ok &= ServiceUtility::PokeServices();
815 }
816
Hector Dearman11845782018-03-08 14:35:44 +0000817 return ok;
818}
819
820static void cleanUpUserspaceTracing()
821{
822 setTagsProperty(0);
823 clearAppProperties();
Hector Dearman11845782018-03-08 14:35:44 +0000824
825 if (g_tracePdx) {
826 ServiceUtility::PokeServices();
827 }
828}
829
830
831// Set all the kernel tracing settings to the desired state for this trace
832// capture.
833static bool setUpKernelTracing()
834{
835 bool ok = true;
836
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700837 ok &= setUserInitiatedTraceProperty(true);
838
Hector Dearman11845782018-03-08 14:35:44 +0000839 // Set up the tracing options.
840 ok &= setCategoriesEnableFromFile(g_categoriesFile);
841 ok &= setTraceOverwriteEnable(g_traceOverwrite);
842 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
843 // TODO: Re-enable after stabilization
844 //ok &= setCmdlineSize();
845 ok &= setClock();
846 ok &= setPrintTgidEnableIfPresent(true);
847 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
848
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800849 // Disable all the sysfs enables. This is done as a separate loop from
850 // the enables to allow the same enable to exist in multiple categories.
851 ok &= disableKernelTraceEvents();
852
853 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700854 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800855 if (g_categoryEnables[i]) {
856 const TracingCategory &c = k_categories[i];
857 for (int j = 0; j < MAX_SYS_FILES; j++) {
858 const char* path = c.sysfiles[j].path;
859 bool required = c.sysfiles[j].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700860 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800861 if (fileIsWritable(path)) {
862 ok &= setKernelOptionEnable(path, true);
863 } else if (required) {
864 fprintf(stderr, "error writing file %s\n", path);
865 ok = false;
866 }
867 }
868 }
869 }
870 }
871
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800872 return ok;
873}
874
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700875// Reset all the kernel tracing settings to their default state.
Hector Dearman11845782018-03-08 14:35:44 +0000876static void cleanUpKernelTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800877{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800878 // Disable all tracing that we're able to.
879 disableKernelTraceEvents();
880
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800881 // Set the options back to their defaults.
882 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700883 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700884 setPrintTgidEnableIfPresent(false);
Yi Kong19d5c002018-07-20 13:39:55 -0700885 setKernelTraceFuncs(nullptr);
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700886 setUserInitiatedTraceProperty(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700887}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800888
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700889// Enable tracing in the kernel.
890static bool startTrace()
891{
892 return setTracingEnabled(true);
893}
894
895// Disable tracing in the kernel.
896static void stopTrace()
897{
898 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800899}
900
Martijn Coenend9535872015-11-26 10:00:55 +0100901// Read data from the tracing pipe and forward to stdout
902static void streamTrace()
903{
904 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800905 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100906 if (traceFD == -1) {
907 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
908 strerror(errno), errno);
909 return;
910 }
911 while (!g_traceAborted) {
912 ssize_t bytes_read = read(traceFD, trace_data, 4096);
913 if (bytes_read > 0) {
914 write(STDOUT_FILENO, trace_data, bytes_read);
915 fflush(stdout);
916 } else {
917 if (!g_traceAborted) {
918 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
919 bytes_read, errno, strerror(errno));
920 }
921 break;
922 }
923 }
924}
925
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800926// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700927static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800928{
John Reck6c8ac922016-03-28 11:25:30 -0700929 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800930 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800931 if (traceFD == -1) {
932 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
933 strerror(errno), errno);
934 return;
935 }
936
937 if (g_compress) {
938 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800939 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700940
941 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800942 if (result != Z_OK) {
943 fprintf(stderr, "error initializing zlib: %d\n", result);
944 close(traceFD);
945 return;
946 }
947
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700948 constexpr size_t bufSize = 64*1024;
949 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
950 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
951 if (!in || !out) {
952 fprintf(stderr, "couldn't allocate buffers\n");
953 close(traceFD);
954 return;
955 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800956
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700957 int flush = Z_NO_FLUSH;
958
959 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800960 zs.avail_out = bufSize;
961
962 do {
963
964 if (zs.avail_in == 0) {
965 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700966 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800967 if (result < 0) {
968 fprintf(stderr, "error reading trace: %s (%d)\n",
969 strerror(errno), errno);
970 result = Z_STREAM_END;
971 break;
972 } else if (result == 0) {
973 flush = Z_FINISH;
974 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700975 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800976 zs.avail_in = result;
977 }
978 }
979
980 if (zs.avail_out == 0) {
981 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700982 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800983 if ((size_t)result < bufSize) {
984 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
985 strerror(errno), errno);
986 result = Z_STREAM_END; // skip deflate error message
987 zs.avail_out = bufSize; // skip the final write
988 break;
989 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700990 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800991 zs.avail_out = bufSize;
992 }
993
994 } while ((result = deflate(&zs, flush)) == Z_OK);
995
996 if (result != Z_STREAM_END) {
997 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
998 }
999
1000 if (zs.avail_out < bufSize) {
1001 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -07001002 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001003 if ((size_t)result < bytes) {
1004 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1005 strerror(errno), errno);
1006 }
1007 }
1008
1009 result = deflateEnd(&zs);
1010 if (result != Z_OK) {
1011 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1012 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001013 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001014 char buf[4096];
1015 ssize_t rc;
1016 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1017 if (!android::base::WriteFully(outFd, buf, rc)) {
1018 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1019 break;
1020 }
1021 }
1022 if (rc == -1) {
1023 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001024 }
1025 }
1026
1027 close(traceFD);
1028}
1029
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001030static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001031{
1032 if (!g_nohup) {
1033 g_traceAborted = true;
1034 }
1035}
1036
1037static void registerSigHandler()
1038{
1039 struct sigaction sa;
1040 sigemptyset(&sa.sa_mask);
1041 sa.sa_flags = 0;
1042 sa.sa_handler = handleSignal;
Yi Kong19d5c002018-07-20 13:39:55 -07001043 sigaction(SIGHUP, &sa, nullptr);
1044 sigaction(SIGINT, &sa, nullptr);
1045 sigaction(SIGQUIT, &sa, nullptr);
1046 sigaction(SIGTERM, &sa, nullptr);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001047}
1048
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001049static void listSupportedCategories()
1050{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001051 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001052 const TracingCategory& c = k_categories[i];
1053 if (isCategorySupported(c)) {
1054 printf(" %10s - %s\n", c.name, c.longname);
1055 }
1056 }
Wei Wang16a63a42018-09-21 15:47:45 -07001057 for (const auto &c : g_vendorCategories) {
1058 printf(" %10s - %s (HAL)\n", c.name.c_str(), c.description.c_str());
1059 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001060}
1061
1062// Print the command usage help to stderr.
1063static void showHelp(const char *cmd)
1064{
1065 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1066 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001067 " -a appname enable app-level tracing for a comma "
Daniel Colascione519a0792018-02-09 20:05:39 -08001068 "separated list of cmdlines; * is a wildcard matching any process\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001069 " -b N use a trace buffer size of N KB\n"
1070 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001071 " -f filename use the categories written in a file as space-separated\n"
1072 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001073 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001074 " -n ignore signals\n"
1075 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001076 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001077 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001078 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001079 " --async_dump dump the current contents of circular trace buffer\n"
1080 " --async_stop stop tracing and dump the current contents of circular\n"
1081 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001082 " --stream stream trace to stdout as it enters the trace buffer\n"
1083 " Note: this can take significant CPU time, and is best\n"
1084 " used for measuring things that are not affected by\n"
1085 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001086 " --list_categories\n"
1087 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001088 " -o filename write the trace to the specified file instead\n"
1089 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001090 );
1091}
1092
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001093bool findTraceFiles()
1094{
1095 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1096 static const std::string tracefs_path = "/sys/kernel/tracing/";
1097 static const std::string trace_file = "trace_marker";
1098
1099 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1100 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1101
1102 if (!tracefs && !debugfs) {
1103 fprintf(stderr, "Error: Did not find trace folder\n");
1104 return false;
1105 }
1106
1107 if (tracefs) {
1108 g_traceFolder = tracefs_path;
1109 } else {
1110 g_traceFolder = debugfs_path;
1111 }
1112
1113 return true;
1114}
1115
Wei Wang16a63a42018-09-21 15:47:45 -07001116void initVendorCategories()
1117{
1118 g_atraceHal = IAtraceDevice::getService();
1119
1120 if (g_atraceHal == nullptr) {
1121 // No atrace HAL
1122 return;
1123 }
1124
1125 Return<void> ret = g_atraceHal->listCategories(
1126 [](const auto& list) {
1127 g_vendorCategories.reserve(list.size());
1128 for (const auto& category : list) {
1129 g_vendorCategories.emplace_back(category.name, category.description, false);
1130 }
1131 });
1132 if (!ret.isOk()) {
1133 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1134 }
1135}
1136
1137static bool setUpVendorTracing()
1138{
1139 if (g_atraceHal == nullptr) {
1140 // No atrace HAL
1141 return true;
1142 }
1143
1144 std::vector<hidl_string> categories;
1145 for (const auto &c : g_vendorCategories) {
1146 if (c.enabled) {
1147 categories.emplace_back(c.name);
1148 }
1149 }
1150
1151 if (!categories.size()) {
1152 return true;
1153 }
1154
1155 auto ret = g_atraceHal->enableCategories(categories);
1156 if (!ret.isOk()) {
1157 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1158 return false;
1159 } else if (ret != Status::SUCCESS) {
1160 fprintf(stderr, "calling atrace HAL failed: %s\n", toString(ret).c_str());
1161 return false;
1162 }
1163 return true;
1164}
1165
1166static bool cleanUpVendorTracing()
1167{
1168 if (g_atraceHal == nullptr) {
1169 // No atrace HAL
1170 return true;
1171 }
1172
1173 if (!g_vendorCategories.size()) {
1174 // No vendor categories
1175 return true;
1176 }
1177
1178 auto ret = g_atraceHal->disableAllCategories();
1179 if (!ret.isOk()) {
1180 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1181 return false;
1182 } else if (ret != Status::SUCCESS) {
1183 fprintf(stderr, "calling atrace HAL failed: %s\n", toString(ret).c_str());
1184 return false;
1185 }
1186 return true;
1187}
1188
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001189int main(int argc, char **argv)
1190{
1191 bool async = false;
1192 bool traceStart = true;
1193 bool traceStop = true;
1194 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001195 bool traceStream = false;
Hector Dearman11845782018-03-08 14:35:44 +00001196 bool onlyUserspace = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001197
1198 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1199 showHelp(argv[0]);
1200 exit(0);
1201 }
1202
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001203 if (!findTraceFiles()) {
1204 fprintf(stderr, "No trace folder found\n");
1205 exit(-1);
1206 }
1207
Wei Wang16a63a42018-09-21 15:47:45 -07001208 initVendorCategories();
1209
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001210 for (;;) {
1211 int ret;
1212 int option_index = 0;
1213 static struct option long_options[] = {
Yi Kong19d5c002018-07-20 13:39:55 -07001214 {"async_start", no_argument, nullptr, 0 },
1215 {"async_stop", no_argument, nullptr, 0 },
1216 {"async_dump", no_argument, nullptr, 0 },
1217 {"only_userspace", no_argument, nullptr, 0 },
1218 {"list_categories", no_argument, nullptr, 0 },
1219 {"stream", no_argument, nullptr, 0 },
1220 {nullptr, 0, nullptr, 0 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001221 };
1222
John Reck40b26b42016-03-30 09:44:36 -07001223 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001224 long_options, &option_index);
1225
1226 if (ret < 0) {
1227 for (int i = optind; i < argc; i++) {
Wei Wang16a63a42018-09-21 15:47:45 -07001228 if (!setCategoryEnable(argv[i])) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001229 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1230 exit(1);
1231 }
1232 }
1233 break;
1234 }
1235
1236 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001237 case 'a':
1238 g_debugAppCmdLine = optarg;
1239 break;
1240
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001241 case 'b':
1242 g_traceBufferSizeKB = atoi(optarg);
1243 break;
1244
1245 case 'c':
1246 g_traceOverwrite = true;
1247 break;
1248
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001249 case 'f':
1250 g_categoriesFile = optarg;
1251 break;
1252
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001253 case 'k':
1254 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001255 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001256
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001257 case 'n':
1258 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001259 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001260
1261 case 's':
1262 g_initialSleepSecs = atoi(optarg);
1263 break;
1264
1265 case 't':
1266 g_traceDurationSeconds = atoi(optarg);
1267 break;
1268
1269 case 'z':
1270 g_compress = true;
1271 break;
1272
John Reck40b26b42016-03-30 09:44:36 -07001273 case 'o':
1274 g_outputFile = optarg;
1275 break;
1276
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001277 case 0:
1278 if (!strcmp(long_options[option_index].name, "async_start")) {
1279 async = true;
1280 traceStop = false;
1281 traceDump = false;
1282 g_traceOverwrite = true;
1283 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1284 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001285 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001286 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1287 async = true;
1288 traceStart = false;
1289 traceStop = false;
Hector Dearman11845782018-03-08 14:35:44 +00001290 } else if (!strcmp(long_options[option_index].name, "only_userspace")) {
1291 onlyUserspace = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001292 } else if (!strcmp(long_options[option_index].name, "stream")) {
1293 traceStream = true;
1294 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001295 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1296 listSupportedCategories();
1297 exit(0);
1298 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001299 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001300
1301 default:
1302 fprintf(stderr, "\n");
1303 showHelp(argv[0]);
1304 exit(-1);
1305 break;
1306 }
1307 }
1308
Hector Dearman11845782018-03-08 14:35:44 +00001309 if (onlyUserspace) {
1310 if (!async || !(traceStart || traceStop)) {
1311 fprintf(stderr, "--only_userspace can only be used with "
1312 "--async_start or --async_stop\n");
1313 exit(1);
1314 }
1315 }
1316
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001317 registerSigHandler();
1318
1319 if (g_initialSleepSecs > 0) {
1320 sleep(g_initialSleepSecs);
1321 }
1322
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001323 bool ok = true;
Hector Dearman11845782018-03-08 14:35:44 +00001324
Wei Wang5b73b742018-03-08 13:33:12 -08001325 if (traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001326 ok &= setUpUserspaceTracing();
1327 }
1328
1329 if (ok && traceStart && !onlyUserspace) {
1330 ok &= setUpKernelTracing();
Wei Wang16a63a42018-09-21 15:47:45 -07001331 ok &= setUpVendorTracing();
Wei Wang5b73b742018-03-08 13:33:12 -08001332 ok &= startTrace();
1333 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001334
1335 if (ok && traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001336
1337 if (!traceStream && !onlyUserspace) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001338 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001339 fflush(stdout);
1340 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001341
1342 // We clear the trace after starting it because tracing gets enabled for
1343 // each CPU individually in the kernel. Having the beginning of the trace
1344 // contain entries from only one CPU can cause "begin" entries without a
1345 // matching "end" entry to show up if a task gets migrated from one CPU to
1346 // another.
Hector Dearman11845782018-03-08 14:35:44 +00001347 if (!onlyUserspace)
1348 ok = clearTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001349
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001350 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001351 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001352 // Sleep to allow the trace to be captured.
1353 struct timespec timeLeft;
1354 timeLeft.tv_sec = g_traceDurationSeconds;
1355 timeLeft.tv_nsec = 0;
1356 do {
1357 if (g_traceAborted) {
1358 break;
1359 }
1360 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1361 }
Martijn Coenend9535872015-11-26 10:00:55 +01001362
1363 if (traceStream) {
1364 streamTrace();
1365 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001366 }
1367
1368 // Stop the trace and restore the default settings.
Hector Dearman11845782018-03-08 14:35:44 +00001369 if (traceStop && !onlyUserspace)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001370 stopTrace();
1371
Hector Dearman11845782018-03-08 14:35:44 +00001372 if (ok && traceDump && !onlyUserspace) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001373 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001374 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001375 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001376 int outFd = STDOUT_FILENO;
1377 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001378 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001379 }
1380 if (outFd == -1) {
1381 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1382 } else {
1383 dprintf(outFd, "TRACE:\n");
1384 dumpTrace(outFd);
1385 if (g_outputFile) {
1386 close(outFd);
1387 }
1388 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001389 } else {
1390 printf("\ntrace aborted.\n");
1391 fflush(stdout);
1392 }
1393 clearTrace();
1394 } else if (!ok) {
1395 fprintf(stderr, "unable to start tracing\n");
1396 }
1397
1398 // Reset the trace buffer size to 1.
Hector Dearman11845782018-03-08 14:35:44 +00001399 if (traceStop) {
1400 cleanUpUserspaceTracing();
Hector Dearmanada0a4a2019-04-09 14:13:14 +01001401 if (!onlyUserspace) {
1402 cleanUpVendorTracing();
Hector Dearman11845782018-03-08 14:35:44 +00001403 cleanUpKernelTracing();
Hector Dearmanada0a4a2019-04-09 14:13:14 +01001404 }
Hector Dearman11845782018-03-08 14:35:44 +00001405 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001406
1407 return g_traceAborted ? 1 : 0;
1408}