blob: 64ba254a61e0849e36f0ef291f87e1e02f0914c8 [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>
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +000052#include <android-base/strings.h>
Elliott Hughes5fd6ff62017-03-28 14:55:31 -070053#include <android-base/stringprintf.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080054
55using namespace android;
Corey Tabakaa6c0a722017-05-31 16:37:40 -070056using pdx::default_transport::ServiceUtility;
Wei Wang16a63a42018-09-21 15:47:45 -070057using hardware::hidl_vec;
58using hardware::hidl_string;
59using hardware::Return;
60using hardware::atrace::V1_0::IAtraceDevice;
61using hardware::atrace::V1_0::Status;
62using hardware::atrace::V1_0::toString;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080063
Martijn Coenenee9b97e2016-11-16 16:00:26 +010064using std::string;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080065
Wei Wang963999c2021-03-17 16:28:59 -070066#define MAX_SYS_FILES 12
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080067
68const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
Carmen Jackson65ecfbb2018-05-22 10:29:47 -070069const char* k_userInitiatedTraceProperty = "debug.atrace.user_initiated";
sergeyv4144eff2016-04-28 11:40:04 -070070
71const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
72const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070073const char* k_coreServiceCategory = "core_services";
Corey Tabakaa6c0a722017-05-31 16:37:40 -070074const char* k_pdxServiceCategory = "pdx";
sergeyvdb404152016-05-02 19:26:07 -070075const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080076
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +000077const char* kVendorCategoriesPath = "/vendor/etc/atrace/atrace_categories.txt";
78
79typedef enum { OPT, REQ } requiredness;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080080
81struct TracingCategory {
82 // The name identifying the category.
83 const char* name;
84
85 // A longer description of the category.
86 const char* longname;
87
88 // The userland tracing tags that the category enables.
89 uint64_t tags;
90
91 // The fname==NULL terminated list of /sys/ files that the category
92 // enables.
93 struct {
94 // Whether the file must be writable in order to enable the tracing
95 // category.
96 requiredness required;
97
98 // The path to the enable file.
99 const char* path;
100 } sysfiles[MAX_SYS_FILES];
101};
102
103/* Tracing categories */
104static const TracingCategory k_categories[] = {
Yiwei Zhang63775062020-09-18 11:42:33 -0700105 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, {
106 { OPT, "events/gpu_mem/gpu_mem_total/enable" },
107 } },
MÃ¥rten Kongstad2d4f89b2018-12-03 12:58:56 +0100108 { "input", "Input", ATRACE_TAG_INPUT, { } },
109 { "view", "View System", ATRACE_TAG_VIEW, { } },
110 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
111 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
112 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
113 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
114 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
115 { "video", "Video", ATRACE_TAG_VIDEO, { } },
116 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
117 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
118 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
119 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
120 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
121 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
122 { "power", "Power Management", ATRACE_TAG_POWER, { } },
123 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
124 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
125 { "database", "Database", ATRACE_TAG_DATABASE, { } },
126 { "network", "Network", ATRACE_TAG_NETWORK, { } },
127 { "adb", "ADB", ATRACE_TAG_ADB, { } },
128 { "vibrator", "Vibrator", ATRACE_TAG_VIBRATOR, { } },
129 { "aidl", "AIDL calls", ATRACE_TAG_AIDL, { } },
130 { "nnapi", "NNAPI", ATRACE_TAG_NNAPI, { } },
131 { "rro", "Runtime Resource Overlay", ATRACE_TAG_RRO, { } },
sergeyvdb404152016-05-02 19:26:07 -0700132 { k_coreServiceCategory, "Core services", 0, { } },
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700133 { k_pdxServiceCategory, "PDX services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700134 { "sched", "CPU Scheduling", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800135 { REQ, "events/sched/sched_switch/enable" },
136 { REQ, "events/sched/sched_wakeup/enable" },
Joel Fernandesee593e22017-06-04 13:05:59 -0700137 { OPT, "events/sched/sched_waking/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800138 { OPT, "events/sched/sched_blocked_reason/enable" },
139 { OPT, "events/sched/sched_cpu_hotplug/enable" },
Wei Wangca49dfc2018-05-03 15:45:20 -0700140 { OPT, "events/sched/sched_pi_setprio/enable" },
Carmen Jackson63ea2912019-04-26 10:41:00 -0700141 { OPT, "events/sched/sched_process_exit/enable" },
Joel Fernandes4dfca7c2017-06-15 16:53:52 -0700142 { OPT, "events/cgroup/enable" },
Carmen Jackson63ea2912019-04-26 10:41:00 -0700143 { OPT, "events/oom/oom_score_adj_update/enable" },
144 { OPT, "events/task/task_rename/enable" },
145 { OPT, "events/task/task_newtask/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800146 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700147 { "irq", "IRQ Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800148 { REQ, "events/irq/enable" },
149 { OPT, "events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700150 } },
Joel Fernandes6ccad102017-08-31 08:35:05 -0700151 { "irqoff", "IRQ-disabled code section tracing", 0, {
152 { REQ, "events/preemptirq/irq_enable/enable" },
153 { REQ, "events/preemptirq/irq_disable/enable" },
154 } },
155 { "preemptoff", "Preempt-disabled code section tracing", 0, {
156 { REQ, "events/preemptirq/preempt_enable/enable" },
157 { REQ, "events/preemptirq/preempt_disable/enable" },
158 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100159 { "i2c", "I2C Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800160 { REQ, "events/i2c/enable" },
161 { REQ, "events/i2c/i2c_read/enable" },
162 { REQ, "events/i2c/i2c_write/enable" },
163 { REQ, "events/i2c/i2c_result/enable" },
164 { REQ, "events/i2c/i2c_reply/enable" },
165 { OPT, "events/i2c/smbus_read/enable" },
166 { OPT, "events/i2c/smbus_write/enable" },
167 { OPT, "events/i2c/smbus_result/enable" },
168 { OPT, "events/i2c/smbus_reply/enable" },
Michael Wright43fb6782016-08-18 19:56:43 +0100169 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700170 { "freq", "CPU Frequency", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800171 { REQ, "events/power/cpu_frequency/enable" },
172 { OPT, "events/power/clock_set_rate/enable" },
Kevin DuBois062e0b92017-11-03 15:44:08 -0700173 { OPT, "events/power/clock_disable/enable" },
174 { OPT, "events/power/clock_enable/enable" },
Wei Wang53305dd2018-02-22 11:40:07 -0800175 { OPT, "events/clk/clk_set_rate/enable" },
176 { OPT, "events/clk/clk_disable/enable" },
177 { OPT, "events/clk/clk_enable/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800178 { OPT, "events/power/cpu_frequency_limits/enable" },
Carmen Jackson5ab84322019-08-08 14:35:47 -0700179 { OPT, "events/power/suspend_resume/enable" },
Wei Wang2ded52d2020-07-31 01:13:58 -0700180 { OPT, "events/cpuhp/cpuhp_enter/enable" },
181 { OPT, "events/cpuhp/cpuhp_exit/enable" },
Wei Wang963999c2021-03-17 16:28:59 -0700182 { OPT, "events/cpuhp/cpuhp_pause/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800183 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700184 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800185 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800186 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700187 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800188 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800189 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700190 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800191 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
192 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
193 { OPT, "events/f2fs/f2fs_write_begin/enable" },
194 { OPT, "events/f2fs/f2fs_write_end/enable" },
195 { OPT, "events/ext4/ext4_da_write_begin/enable" },
196 { OPT, "events/ext4/ext4_da_write_end/enable" },
197 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
198 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
YH Linc08daed2022-10-01 09:43:06 +0800199 { OPT, "events/block/block_bio_queue/enable" },
200 { OPT, "events/block/block_bio_complete/enable" },
201 { OPT, "events/ufs/ufshcd_command/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800202 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700203 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800204 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700205 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700206 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800207 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800208 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700209 { "sync", "Synchronization", 0, {
Jesse Halla978cef2019-02-25 16:24:10 -0800210 // linux kernel < 4.9
Jesse Hallae001a32018-05-15 12:02:15 -0700211 { OPT, "events/sync/enable" },
Jesse Halla978cef2019-02-25 16:24:10 -0800212 // linux kernel == 4.9.x
Jesse Hallae001a32018-05-15 12:02:15 -0700213 { OPT, "events/fence/enable" },
Jesse Halla978cef2019-02-25 16:24:10 -0800214 // linux kernel > 4.9
215 { OPT, "events/dma_fence/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800216 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700217 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800218 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800219 } },
Colin Cross580407f2014-08-18 15:22:13 -0700220 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800221 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
222 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
223 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
224 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Carmen Jackson7a23eb72018-07-02 13:14:56 -0700225 { OPT, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700226 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800227 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800228 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800229 } },
Scott Bauerae473362015-06-08 16:32:36 -0700230 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800231 { REQ, "events/binder/binder_transaction/enable" },
232 { REQ, "events/binder/binder_transaction_received/enable" },
Mika Raento80c3e5d2018-06-25 16:47:24 +0100233 { REQ, "events/binder/binder_transaction_alloc_buf/enable" },
Martijn Coenen7f3d7a22017-05-26 09:50:55 -0700234 { OPT, "events/binder/binder_set_priority/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700235 } },
236 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800237 { OPT, "events/binder/binder_lock/enable" },
238 { OPT, "events/binder/binder_locked/enable" },
239 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700240 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200241 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800242 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200243 } },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700244 { "memory", "Memory", 0, {
Collin Fijalkovich08e3f4a2020-03-30 16:20:24 -0700245 { OPT, "events/mm_event/mm_event_record/enable" },
Primiano Tucci806ee9e2021-11-15 21:08:06 +0000246 { OPT, "events/synthetic/rss_stat_throttled/enable" },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700247 { OPT, "events/kmem/ion_heap_grow/enable" },
248 { OPT, "events/kmem/ion_heap_shrink/enable" },
Ioannis Ilkos88a85f32020-04-23 22:43:40 +0100249 { OPT, "events/ion/ion_stat/enable" },
Yiwei Zhang63775062020-09-18 11:42:33 -0700250 { OPT, "events/gpu_mem/gpu_mem_total/enable" },
Collin Fijalkovichd4db32b2021-05-21 11:41:40 -0700251 { OPT, "events/fastrpc/fastrpc_dma_stat/enable" },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700252 } },
TeYuan Wang377ca212022-02-14 10:25:00 +0800253 { "thermal", "Thermal event", ATRACE_TAG_THERMAL, {
Wei Wange3079a92020-07-08 15:33:20 -0700254 { REQ, "events/thermal/thermal_temperature/enable" },
255 { OPT, "events/thermal/cdev_update/enable" },
256 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800257};
258
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +0000259// A category in the vendor categories file.
260struct TracingVendorFileCategory {
261 // The name identifying the category.
262 std::string name;
263
264 // If the category is enabled through command.
265 bool enabled = false;
266
267 // Paths to the ftrace enable files (relative to g_traceFolder).
268 std::vector<std::string> ftrace_enable_paths;
269};
270
271// A category in the vendor HIDL HAL.
272struct TracingVendorHalCategory {
Wei Wang16a63a42018-09-21 15:47:45 -0700273 // The name identifying the category.
274 std::string name;
275
276 // A longer description of the category.
277 std::string description;
278
279 // If the category is enabled through command.
280 bool enabled;
281
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +0000282 TracingVendorHalCategory(string&& name, string&& description, bool enabled)
283 : name(std::move(name)), description(std::move(description)), enabled(enabled) {}
Wei Wang16a63a42018-09-21 15:47:45 -0700284};
285
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800286/* Command line options */
287static int g_traceDurationSeconds = 5;
288static bool g_traceOverwrite = false;
289static int g_traceBufferSizeKB = 2048;
290static bool g_compress = false;
291static bool g_nohup = false;
292static int g_initialSleepSecs = 0;
Yi Kong19d5c002018-07-20 13:39:55 -0700293static const char* g_categoriesFile = nullptr;
294static const char* g_kernelTraceFuncs = nullptr;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700295static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700296static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800297
298/* Global state */
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700299static bool g_tracePdx = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800300static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700301static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800302static std::string g_traceFolder;
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +0000303static std::vector<TracingVendorFileCategory> g_vendorFileCategories;
Wei Wang16a63a42018-09-21 15:47:45 -0700304static sp<IAtraceDevice> g_atraceHal;
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +0000305static std::vector<TracingVendorHalCategory> g_vendorHalCategories;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800306
307/* Sys file paths */
308static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800309 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800310
311static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800312 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800313
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700314#if 0
315// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700316static const char* k_traceCmdlineSizePath =
317 "saved_cmdlines_size";
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700318#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700319
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800320static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800321 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800322
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700323static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800324 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700325
326static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800327 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700328
John Recke757b1c2018-06-28 12:24:33 -0700329static const char* k_recordTgidPath =
330 "options/record-tgid";
331
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700332static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800333 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700334
335static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800336 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700337
338static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800339 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700340
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700341static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800342 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700343
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800344static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800345 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800346
347static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800348 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800349
Martijn Coenend9535872015-11-26 10:00:55 +0100350static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800351 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100352
John Reck469a1942015-03-26 15:31:35 -0700353static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800354 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700355
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800356// Check whether a file exists.
357static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800358 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800359}
360
361// Check whether a file is writable.
362static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800363 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800364}
365
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700366// Truncate a file.
367static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800368{
Jamie Gennis43122e72013-03-21 14:06:31 -0700369 // This uses creat rather than truncate because some of the debug kernel
370 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
371 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800372 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700373 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800374 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700375 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700376 return false;
377 }
378
Jamie Gennis43122e72013-03-21 14:06:31 -0700379 close(traceFD);
380
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700381 return true;
382}
383
384static bool _writeStr(const char* filename, const char* str, int flags)
385{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800386 std::string fullFilename = g_traceFolder + filename;
387 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800388 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800389 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800390 strerror(errno), errno);
391 return false;
392 }
393
394 bool ok = true;
395 ssize_t len = strlen(str);
396 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800397 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800398 strerror(errno), errno);
399 ok = false;
400 }
401
402 close(fd);
403
404 return ok;
405}
406
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700407// Write a string to a file, returning true if the write was successful.
408static bool writeStr(const char* filename, const char* str)
409{
410 return _writeStr(filename, str, O_WRONLY);
411}
412
413// Append a string to a file, returning true if the write was successful.
414static bool appendStr(const char* filename, const char* str)
415{
416 return _writeStr(filename, str, O_APPEND|O_WRONLY);
417}
418
John Reck469a1942015-03-26 15:31:35 -0700419static void writeClockSyncMarker()
420{
421 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200422 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800423 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200424 if (fd == -1) {
425 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
426 strerror(errno), errno);
427 return;
428 }
John Reck469a1942015-03-26 15:31:35 -0700429 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200430
431 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
432 if (write(fd, buffer, len) != len) {
433 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
434 }
435
436 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
437 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
438 if (write(fd, buffer, len) != len) {
439 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
440 }
441
442 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700443}
444
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800445// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
446// file.
447static bool setKernelOptionEnable(const char* filename, bool enable)
448{
449 return writeStr(filename, enable ? "1" : "0");
450}
451
452// Check whether the category is supported on the device with the current
453// rootness. A category is supported only if all its required /sys/ files are
454// writable and if enabling the category will enable one or more tracing tags
455// or /sys/ files.
456static bool isCategorySupported(const TracingCategory& category)
457{
sergeyvdb404152016-05-02 19:26:07 -0700458 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700459 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700460 }
461
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700462 if (strcmp(category.name, k_pdxServiceCategory) == 0) {
463 return true;
464 }
465
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800466 bool ok = category.tags != 0;
467 for (int i = 0; i < MAX_SYS_FILES; i++) {
468 const char* path = category.sysfiles[i].path;
469 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700470 if (path != nullptr) {
Carmen Jackson5bbc9a22018-12-06 13:47:18 -0800471 if (fileIsWritable(path)) {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800472 ok = true;
Carmen Jackson5bbc9a22018-12-06 13:47:18 -0800473 } else if (req) {
474 return false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800475 }
476 }
477 }
478 return ok;
479}
480
481// Check whether the category would be supported on the device if the user
482// were root. This function assumes that root is able to write to any file
483// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700484// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800485static bool isCategorySupportedForRoot(const TracingCategory& category)
486{
487 bool ok = category.tags != 0;
488 for (int i = 0; i < MAX_SYS_FILES; i++) {
489 const char* path = category.sysfiles[i].path;
490 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700491 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800492 if (req) {
493 if (!fileExists(path)) {
494 return false;
495 } else {
496 ok = true;
497 }
498 } else {
499 ok |= fileExists(path);
500 }
501 }
502 }
503 return ok;
504}
505
506// Enable or disable overwriting of the kernel trace buffers. Disabling this
507// will cause tracing to stop once the trace buffers have filled up.
508static bool setTraceOverwriteEnable(bool enable)
509{
510 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
511}
512
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700513// Set the user initiated trace property
514static bool setUserInitiatedTraceProperty(bool enable)
515{
516 if (!android::base::SetProperty(k_userInitiatedTraceProperty, enable ? "1" : "")) {
517 fprintf(stderr, "error setting user initiated strace system property\n");
518 return false;
519 }
520 return true;
521}
522
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800523// Enable or disable kernel tracing.
524static bool setTracingEnabled(bool enable)
525{
526 return setKernelOptionEnable(k_tracingOnPath, enable);
527}
528
529// Clear the contents of the kernel trace.
530static bool clearTrace()
531{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700532 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800533}
534
535// Set the size of the kernel's trace buffer in kilobytes.
536static bool setTraceBufferSizeKB(int size)
537{
538 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800539 if (size < 1) {
540 size = 1;
541 }
542 snprintf(str, 32, "%d", size);
543 return writeStr(k_traceBufferSizePath, str);
544}
545
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700546#if 0
547// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700548// Set the default size of cmdline hashtable
549static bool setCmdlineSize()
550{
Joel Fernandesce964f22017-06-06 12:20:29 -0700551 if (fileExists(k_traceCmdlineSizePath)) {
552 return writeStr(k_traceCmdlineSizePath, "8192");
553 }
554 return true;
Joel Fernandesed80bd02017-06-02 10:19:28 -0700555}
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700556#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700557
Carmen Jacksonea826792017-05-05 11:42:32 -0700558// Set the clock to the best available option while tracing. Use 'boot' if it's
559// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700560// Any write to the trace_clock sysfs file will reset the buffer, so only
561// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700562static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800563{
Carmen Jacksonea826792017-05-05 11:42:32 -0700564 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
565 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
566 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700567
Carmen Jacksonea826792017-05-05 11:42:32 -0700568 std::string newClock;
569 if (clockStr.find("boot") != std::string::npos) {
570 newClock = "boot";
571 } else if (clockStr.find("mono") != std::string::npos) {
572 newClock = "mono";
573 } else {
574 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700575 }
576
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700577 size_t begin = clockStr.find('[') + 1;
578 size_t end = clockStr.find(']');
Carmen Jacksonea826792017-05-05 11:42:32 -0700579 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
580 return true;
581 }
582 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800583}
584
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700585static bool setPrintTgidEnableIfPresent(bool enable)
586{
John Reckedbf9ec2018-06-29 11:15:17 -0700587 // Pre-4.13 this was options/print-tgid as an android-specific option.
588 // In 4.13+ this is an upstream option called options/record-tgid
589 // Both options produce the same ftrace format change
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700590 if (fileExists(k_printTgidPath)) {
591 return setKernelOptionEnable(k_printTgidPath, enable);
592 }
John Recke757b1c2018-06-28 12:24:33 -0700593 if (fileExists(k_recordTgidPath)) {
594 return setKernelOptionEnable(k_recordTgidPath, enable);
595 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700596 return true;
597}
598
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800599// Set the trace tags that userland tracing uses, and poke the running
600// processes to pick up the new value.
601static bool setTagsProperty(uint64_t tags)
602{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700603 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
604 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800605 fprintf(stderr, "error setting trace tags system property\n");
606 return false;
607 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700608 return true;
609}
610
sergeyv4144eff2016-04-28 11:40:04 -0700611static void clearAppProperties()
612{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700613 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700614 fprintf(stderr, "failed to clear system property: %s",
615 k_traceAppsNumberProperty);
616 }
617}
618
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700619// Set the system property that indicates which apps should perform
620// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700621static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700622{
sergeyv4144eff2016-04-28 11:40:04 -0700623 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700624 char* start = cmdline;
Yi Kong19d5c002018-07-20 13:39:55 -0700625 while (start != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700626 char* end = strchr(start, ',');
Yi Kong19d5c002018-07-20 13:39:55 -0700627 if (end != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700628 *end = '\0';
629 end++;
630 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700631 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
632 if (!android::base::SetProperty(key, start)) {
633 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700634 clearAppProperties();
635 return false;
636 }
637 start = end;
638 i++;
639 }
640
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700641 std::string value = android::base::StringPrintf("%d", i);
642 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
643 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700644 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700645 return false;
646 }
647 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800648}
649
650// Disable all /sys/ enable files.
651static bool disableKernelTraceEvents() {
652 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700653 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800654 const TracingCategory &c = k_categories[i];
655 for (int j = 0; j < MAX_SYS_FILES; j++) {
656 const char* path = c.sysfiles[j].path;
Yi Kong19d5c002018-07-20 13:39:55 -0700657 if (path != nullptr && fileIsWritable(path)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800658 ok &= setKernelOptionEnable(path, false);
659 }
660 }
661 }
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +0000662 for (const TracingVendorFileCategory& c : g_vendorFileCategories) {
663 for (const std::string& path : c.ftrace_enable_paths) {
664 if (fileIsWritable(path.c_str())) {
665 ok &= setKernelOptionEnable(path.c_str(), false);
666 }
667 }
668 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800669 return ok;
670}
671
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700672// Verify that the comma separated list of functions are being traced by the
673// kernel.
674static bool verifyKernelTraceFuncs(const char* funcs)
675{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100676 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800677 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100678 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700679 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100680 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700681 }
682
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100683 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700684
685 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100686 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700687 bool ok = true;
688 char* myFuncs = strdup(funcs);
689 char* func = strtok(myFuncs, ",");
690 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100691 if (!strchr(func, '*')) {
692 String8 fancyFunc = String8::format("\n%s\n", func);
693 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
694 if (!found || func[0] == '\0') {
695 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
696 "to trace.\n", func);
697 ok = false;
698 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700699 }
Yi Kong19d5c002018-07-20 13:39:55 -0700700 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700701 }
702 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700703 return ok;
704}
705
706// Set the comma separated list of functions that the kernel is to trace.
707static bool setKernelTraceFuncs(const char* funcs)
708{
709 bool ok = true;
710
Yi Kong19d5c002018-07-20 13:39:55 -0700711 if (funcs == nullptr || funcs[0] == '\0') {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700712 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700713 if (fileIsWritable(k_currentTracerPath)) {
714 ok &= writeStr(k_currentTracerPath, "nop");
715 }
716 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700717 ok &= truncateFile(k_ftraceFilterPath);
718 }
719 } else {
720 // Enable kernel function tracing.
721 ok &= writeStr(k_currentTracerPath, "function_graph");
722 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
723 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
724 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700725
726 // Set the requested filter functions.
727 ok &= truncateFile(k_ftraceFilterPath);
728 char* myFuncs = strdup(funcs);
729 char* func = strtok(myFuncs, ",");
730 while (func) {
731 ok &= appendStr(k_ftraceFilterPath, func);
Yi Kong19d5c002018-07-20 13:39:55 -0700732 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700733 }
734 free(myFuncs);
735
736 // Verify that the set functions are being traced.
737 if (ok) {
738 ok &= verifyKernelTraceFuncs(funcs);
739 }
740 }
741
742 return ok;
743}
744
Wei Wang16a63a42018-09-21 15:47:45 -0700745static bool setCategoryEnable(const char* name)
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900746{
Wei Wang16a63a42018-09-21 15:47:45 -0700747 bool vendor_found = false;
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +0000748 for (auto& c : g_vendorFileCategories) {
749 if (strcmp(name, c.name.c_str()) == 0) {
750 c.enabled = true;
751 vendor_found = true;
752 }
753 }
754 for (auto& c : g_vendorHalCategories) {
Wei Wang16a63a42018-09-21 15:47:45 -0700755 if (strcmp(name, c.name.c_str()) == 0) {
756 c.enabled = true;
757 vendor_found = true;
758 }
759 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700760 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900761 const TracingCategory& c = k_categories[i];
762 if (strcmp(name, c.name) == 0) {
763 if (isCategorySupported(c)) {
Wei Wang16a63a42018-09-21 15:47:45 -0700764 g_categoryEnables[i] = true;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900765 return true;
766 } else {
767 if (isCategorySupportedForRoot(c)) {
768 fprintf(stderr, "error: category \"%s\" requires root "
769 "privileges.\n", name);
770 } else {
771 fprintf(stderr, "error: category \"%s\" is not supported "
772 "on this device.\n", name);
773 }
774 return false;
775 }
776 }
777 }
Wei Wang16a63a42018-09-21 15:47:45 -0700778 if (vendor_found) {
779 return true;
780 }
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900781 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
782 return false;
783}
784
785static bool setCategoriesEnableFromFile(const char* categories_file)
786{
787 if (!categories_file) {
788 return true;
789 }
Yi Kong19d5c002018-07-20 13:39:55 -0700790 Tokenizer* tokenizer = nullptr;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900791 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
792 return false;
793 }
794 bool ok = true;
795 while (!tokenizer->isEol()) {
796 String8 token = tokenizer->nextToken(" ");
797 if (token.isEmpty()) {
798 tokenizer->skipDelimiters(" ");
799 continue;
800 }
Wei Wang16a63a42018-09-21 15:47:45 -0700801 ok &= setCategoryEnable(token.string());
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900802 }
803 delete tokenizer;
804 return ok;
805}
806
Hector Dearman11845782018-03-08 14:35:44 +0000807static bool setUpUserspaceTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800808{
809 bool ok = true;
810
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800811 // Set up the tags property.
812 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700813 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800814 if (g_categoryEnables[i]) {
815 const TracingCategory &c = k_categories[i];
816 tags |= c.tags;
817 }
818 }
sergeyvdb404152016-05-02 19:26:07 -0700819
820 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700821 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700822 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
823 coreServicesTagEnabled = g_categoryEnables[i];
824 }
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700825
826 // Set whether to poke PDX services in this session.
827 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
828 g_tracePdx = g_categoryEnables[i];
829 }
sergeyvdb404152016-05-02 19:26:07 -0700830 }
831
832 std::string packageList(g_debugAppCmdLine);
833 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700834 if (!packageList.empty()) {
835 packageList += ",";
836 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700837 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700838 }
Dan Austin09a79872016-05-31 13:27:03 -0700839 ok &= setAppCmdlineProperty(&packageList[0]);
Florian Mayer6263b582019-12-10 13:28:45 +0000840 ok &= setTagsProperty(tags);
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700841 if (g_tracePdx) {
842 ok &= ServiceUtility::PokeServices();
843 }
844
Hector Dearman11845782018-03-08 14:35:44 +0000845 return ok;
846}
847
848static void cleanUpUserspaceTracing()
849{
850 setTagsProperty(0);
851 clearAppProperties();
Hector Dearman11845782018-03-08 14:35:44 +0000852
853 if (g_tracePdx) {
854 ServiceUtility::PokeServices();
855 }
856}
857
858
859// Set all the kernel tracing settings to the desired state for this trace
860// capture.
861static bool setUpKernelTracing()
862{
863 bool ok = true;
864
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700865 ok &= setUserInitiatedTraceProperty(true);
866
Hector Dearman11845782018-03-08 14:35:44 +0000867 // Set up the tracing options.
868 ok &= setCategoriesEnableFromFile(g_categoriesFile);
869 ok &= setTraceOverwriteEnable(g_traceOverwrite);
870 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
871 // TODO: Re-enable after stabilization
872 //ok &= setCmdlineSize();
873 ok &= setClock();
874 ok &= setPrintTgidEnableIfPresent(true);
875 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
876
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800877 // Disable all the sysfs enables. This is done as a separate loop from
878 // the enables to allow the same enable to exist in multiple categories.
879 ok &= disableKernelTraceEvents();
880
881 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700882 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800883 if (g_categoryEnables[i]) {
884 const TracingCategory &c = k_categories[i];
885 for (int j = 0; j < MAX_SYS_FILES; j++) {
886 const char* path = c.sysfiles[j].path;
887 bool required = c.sysfiles[j].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700888 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800889 if (fileIsWritable(path)) {
890 ok &= setKernelOptionEnable(path, true);
891 } else if (required) {
892 fprintf(stderr, "error writing file %s\n", path);
893 ok = false;
894 }
895 }
896 }
897 }
898 }
899
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +0000900 for (const TracingVendorFileCategory& c : g_vendorFileCategories) {
901 if (c.enabled) {
902 for (const std::string& path : c.ftrace_enable_paths) {
903 if (fileIsWritable(path.c_str())) {
904 ok &= setKernelOptionEnable(path.c_str(), true);
905 }
906 }
907 }
908 }
909
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800910 return ok;
911}
912
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700913// Reset all the kernel tracing settings to their default state.
Hector Dearman11845782018-03-08 14:35:44 +0000914static void cleanUpKernelTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800915{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800916 // Disable all tracing that we're able to.
917 disableKernelTraceEvents();
918
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800919 // Set the options back to their defaults.
920 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700921 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700922 setPrintTgidEnableIfPresent(false);
Yi Kong19d5c002018-07-20 13:39:55 -0700923 setKernelTraceFuncs(nullptr);
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700924 setUserInitiatedTraceProperty(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700925}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800926
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700927// Enable tracing in the kernel.
928static bool startTrace()
929{
930 return setTracingEnabled(true);
931}
932
933// Disable tracing in the kernel.
934static void stopTrace()
935{
936 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800937}
938
Martijn Coenend9535872015-11-26 10:00:55 +0100939// Read data from the tracing pipe and forward to stdout
940static void streamTrace()
941{
942 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800943 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100944 if (traceFD == -1) {
945 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
946 strerror(errno), errno);
947 return;
948 }
949 while (!g_traceAborted) {
950 ssize_t bytes_read = read(traceFD, trace_data, 4096);
951 if (bytes_read > 0) {
952 write(STDOUT_FILENO, trace_data, bytes_read);
953 fflush(stdout);
954 } else {
955 if (!g_traceAborted) {
956 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
957 bytes_read, errno, strerror(errno));
958 }
959 break;
960 }
961 }
962}
963
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800964// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700965static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800966{
John Reck6c8ac922016-03-28 11:25:30 -0700967 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800968 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800969 if (traceFD == -1) {
970 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
971 strerror(errno), errno);
972 return;
973 }
974
975 if (g_compress) {
976 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800977 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700978
979 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800980 if (result != Z_OK) {
981 fprintf(stderr, "error initializing zlib: %d\n", result);
982 close(traceFD);
983 return;
984 }
985
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700986 constexpr size_t bufSize = 64*1024;
987 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
988 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
989 if (!in || !out) {
990 fprintf(stderr, "couldn't allocate buffers\n");
991 close(traceFD);
992 return;
993 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800994
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700995 int flush = Z_NO_FLUSH;
996
997 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800998 zs.avail_out = bufSize;
999
1000 do {
1001
1002 if (zs.avail_in == 0) {
1003 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001004 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001005 if (result < 0) {
1006 fprintf(stderr, "error reading trace: %s (%d)\n",
1007 strerror(errno), errno);
1008 result = Z_STREAM_END;
1009 break;
1010 } else if (result == 0) {
1011 flush = Z_FINISH;
1012 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001013 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001014 zs.avail_in = result;
1015 }
1016 }
1017
1018 if (zs.avail_out == 0) {
1019 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -07001020 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001021 if ((size_t)result < bufSize) {
1022 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1023 strerror(errno), errno);
1024 result = Z_STREAM_END; // skip deflate error message
1025 zs.avail_out = bufSize; // skip the final write
1026 break;
1027 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001028 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001029 zs.avail_out = bufSize;
1030 }
1031
1032 } while ((result = deflate(&zs, flush)) == Z_OK);
1033
1034 if (result != Z_STREAM_END) {
1035 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
1036 }
1037
1038 if (zs.avail_out < bufSize) {
1039 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -07001040 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001041 if ((size_t)result < bytes) {
1042 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1043 strerror(errno), errno);
1044 }
1045 }
1046
1047 result = deflateEnd(&zs);
1048 if (result != Z_OK) {
1049 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1050 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001051 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001052 char buf[4096];
1053 ssize_t rc;
1054 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1055 if (!android::base::WriteFully(outFd, buf, rc)) {
1056 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1057 break;
1058 }
1059 }
1060 if (rc == -1) {
1061 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001062 }
1063 }
1064
1065 close(traceFD);
1066}
1067
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001068static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001069{
1070 if (!g_nohup) {
1071 g_traceAborted = true;
1072 }
1073}
1074
1075static void registerSigHandler()
1076{
1077 struct sigaction sa;
1078 sigemptyset(&sa.sa_mask);
1079 sa.sa_flags = 0;
1080 sa.sa_handler = handleSignal;
Yi Kong19d5c002018-07-20 13:39:55 -07001081 sigaction(SIGHUP, &sa, nullptr);
1082 sigaction(SIGINT, &sa, nullptr);
1083 sigaction(SIGQUIT, &sa, nullptr);
1084 sigaction(SIGTERM, &sa, nullptr);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001085}
1086
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001087static void listSupportedCategories()
1088{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001089 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001090 const TracingCategory& c = k_categories[i];
1091 if (isCategorySupported(c)) {
1092 printf(" %10s - %s\n", c.name, c.longname);
1093 }
1094 }
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +00001095 for (const auto& c : g_vendorFileCategories) {
1096 printf(" %10s - (VENDOR)\n", c.name.c_str());
1097 }
1098 for (const auto& c : g_vendorHalCategories) {
Wei Wang16a63a42018-09-21 15:47:45 -07001099 printf(" %10s - %s (HAL)\n", c.name.c_str(), c.description.c_str());
1100 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001101}
1102
1103// Print the command usage help to stderr.
1104static void showHelp(const char *cmd)
1105{
1106 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1107 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001108 " -a appname enable app-level tracing for a comma "
Daniel Colascione519a0792018-02-09 20:05:39 -08001109 "separated list of cmdlines; * is a wildcard matching any process\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001110 " -b N use a trace buffer size of N KB\n"
1111 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001112 " -f filename use the categories written in a file as space-separated\n"
1113 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001114 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001115 " -n ignore signals\n"
1116 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001117 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001118 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001119 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001120 " --async_dump dump the current contents of circular trace buffer\n"
1121 " --async_stop stop tracing and dump the current contents of circular\n"
1122 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001123 " --stream stream trace to stdout as it enters the trace buffer\n"
1124 " Note: this can take significant CPU time, and is best\n"
1125 " used for measuring things that are not affected by\n"
1126 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001127 " --list_categories\n"
1128 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001129 " -o filename write the trace to the specified file instead\n"
1130 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001131 );
1132}
1133
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001134bool findTraceFiles()
1135{
1136 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1137 static const std::string tracefs_path = "/sys/kernel/tracing/";
1138 static const std::string trace_file = "trace_marker";
1139
1140 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1141 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1142
1143 if (!tracefs && !debugfs) {
1144 fprintf(stderr, "Error: Did not find trace folder\n");
1145 return false;
1146 }
1147
1148 if (tracefs) {
1149 g_traceFolder = tracefs_path;
1150 } else {
1151 g_traceFolder = debugfs_path;
1152 }
1153
1154 return true;
1155}
1156
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +00001157void initVendorCategoriesFromFile() {
1158 std::ifstream is(kVendorCategoriesPath);
1159 for (std::string line; std::getline(is, line);) {
1160 if (line.empty()) {
1161 continue;
1162 }
1163 if (android::base::StartsWith(line, ' ') || android::base::StartsWith(line, '\t')) {
1164 if (g_vendorFileCategories.empty()) {
1165 fprintf(stderr, "Malformed vendor categories file\n");
1166 exit(1);
1167 return;
1168 }
1169 std::string_view path = std::string_view(line).substr(1);
1170 while (android::base::StartsWith(path, ' ') || android::base::StartsWith(path, '\t')) {
1171 path.remove_prefix(1);
1172 }
1173 if (path.empty()) {
1174 continue;
1175 }
1176 std::string enable_path = "events/";
1177 enable_path += path;
1178 enable_path += "/enable";
1179 g_vendorFileCategories.back().ftrace_enable_paths.push_back(std::move(enable_path));
1180 } else {
1181 TracingVendorFileCategory cat;
1182 cat.name = line;
1183 g_vendorFileCategories.push_back(std::move(cat));
1184 }
1185 }
1186}
1187
1188void initVendorCategoriesFromHal() {
Wei Wang16a63a42018-09-21 15:47:45 -07001189 g_atraceHal = IAtraceDevice::getService();
1190
1191 if (g_atraceHal == nullptr) {
1192 // No atrace HAL
1193 return;
1194 }
1195
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +00001196 Return<void> ret = g_atraceHal->listCategories([](const auto& list) {
1197 g_vendorHalCategories.reserve(list.size());
1198 for (const auto& category : list) {
1199 g_vendorHalCategories.emplace_back(category.name, category.description, false);
1200 }
1201 });
Wei Wang16a63a42018-09-21 15:47:45 -07001202 if (!ret.isOk()) {
1203 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1204 }
1205}
1206
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +00001207void initVendorCategories() {
1208 // If kVendorCategoriesPath exists on the filesystem, do not use the HAL.
1209 if (access(kVendorCategoriesPath, F_OK) != -1) {
1210 initVendorCategoriesFromFile();
1211 } else {
1212 initVendorCategoriesFromHal();
1213 }
1214}
1215
1216static bool setUpVendorTracingWithHal() {
Wei Wang16a63a42018-09-21 15:47:45 -07001217 if (g_atraceHal == nullptr) {
1218 // No atrace HAL
1219 return true;
1220 }
1221
1222 std::vector<hidl_string> categories;
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +00001223 for (const auto& c : g_vendorHalCategories) {
Wei Wang16a63a42018-09-21 15:47:45 -07001224 if (c.enabled) {
1225 categories.emplace_back(c.name);
1226 }
1227 }
1228
1229 if (!categories.size()) {
1230 return true;
1231 }
1232
1233 auto ret = g_atraceHal->enableCategories(categories);
1234 if (!ret.isOk()) {
1235 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1236 return false;
1237 } else if (ret != Status::SUCCESS) {
1238 fprintf(stderr, "calling atrace HAL failed: %s\n", toString(ret).c_str());
1239 return false;
1240 }
1241 return true;
1242}
1243
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +00001244static bool cleanUpVendorTracingWithHal() {
Wei Wang16a63a42018-09-21 15:47:45 -07001245 if (g_atraceHal == nullptr) {
1246 // No atrace HAL
1247 return true;
1248 }
1249
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +00001250 if (!g_vendorHalCategories.size()) {
1251 // No vendor HAL categories
Wei Wang16a63a42018-09-21 15:47:45 -07001252 return true;
1253 }
1254
1255 auto ret = g_atraceHal->disableAllCategories();
1256 if (!ret.isOk()) {
1257 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1258 return false;
1259 } else if (ret != Status::SUCCESS) {
1260 fprintf(stderr, "calling atrace HAL failed: %s\n", toString(ret).c_str());
1261 return false;
1262 }
1263 return true;
1264}
1265
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001266int main(int argc, char **argv)
1267{
1268 bool async = false;
1269 bool traceStart = true;
1270 bool traceStop = true;
1271 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001272 bool traceStream = false;
Hector Dearman11845782018-03-08 14:35:44 +00001273 bool onlyUserspace = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001274
1275 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1276 showHelp(argv[0]);
1277 exit(0);
1278 }
1279
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001280 if (!findTraceFiles()) {
1281 fprintf(stderr, "No trace folder found\n");
1282 exit(-1);
1283 }
1284
Wei Wang16a63a42018-09-21 15:47:45 -07001285 initVendorCategories();
1286
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001287 for (;;) {
1288 int ret;
1289 int option_index = 0;
1290 static struct option long_options[] = {
Yi Kong19d5c002018-07-20 13:39:55 -07001291 {"async_start", no_argument, nullptr, 0 },
1292 {"async_stop", no_argument, nullptr, 0 },
1293 {"async_dump", no_argument, nullptr, 0 },
1294 {"only_userspace", no_argument, nullptr, 0 },
1295 {"list_categories", no_argument, nullptr, 0 },
1296 {"stream", no_argument, nullptr, 0 },
1297 {nullptr, 0, nullptr, 0 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001298 };
1299
John Reck40b26b42016-03-30 09:44:36 -07001300 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001301 long_options, &option_index);
1302
1303 if (ret < 0) {
1304 for (int i = optind; i < argc; i++) {
Primiano Tucci3a26ff62022-03-15 18:53:46 +00001305 setCategoryEnable(argv[i]);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001306 }
1307 break;
1308 }
1309
1310 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001311 case 'a':
1312 g_debugAppCmdLine = optarg;
1313 break;
1314
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001315 case 'b':
1316 g_traceBufferSizeKB = atoi(optarg);
1317 break;
1318
1319 case 'c':
1320 g_traceOverwrite = true;
1321 break;
1322
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001323 case 'f':
1324 g_categoriesFile = optarg;
1325 break;
1326
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001327 case 'k':
1328 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001329 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001330
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001331 case 'n':
1332 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001333 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001334
1335 case 's':
1336 g_initialSleepSecs = atoi(optarg);
1337 break;
1338
1339 case 't':
1340 g_traceDurationSeconds = atoi(optarg);
1341 break;
1342
1343 case 'z':
1344 g_compress = true;
1345 break;
1346
John Reck40b26b42016-03-30 09:44:36 -07001347 case 'o':
1348 g_outputFile = optarg;
1349 break;
1350
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001351 case 0:
1352 if (!strcmp(long_options[option_index].name, "async_start")) {
1353 async = true;
1354 traceStop = false;
1355 traceDump = false;
1356 g_traceOverwrite = true;
1357 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1358 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001359 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001360 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1361 async = true;
1362 traceStart = false;
1363 traceStop = false;
Hector Dearman11845782018-03-08 14:35:44 +00001364 } else if (!strcmp(long_options[option_index].name, "only_userspace")) {
1365 onlyUserspace = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001366 } else if (!strcmp(long_options[option_index].name, "stream")) {
1367 traceStream = true;
1368 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001369 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1370 listSupportedCategories();
1371 exit(0);
1372 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001373 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001374
1375 default:
1376 fprintf(stderr, "\n");
1377 showHelp(argv[0]);
1378 exit(-1);
1379 break;
1380 }
1381 }
1382
Hector Dearman11845782018-03-08 14:35:44 +00001383 if (onlyUserspace) {
1384 if (!async || !(traceStart || traceStop)) {
1385 fprintf(stderr, "--only_userspace can only be used with "
1386 "--async_start or --async_stop\n");
1387 exit(1);
1388 }
1389 }
1390
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001391 registerSigHandler();
1392
1393 if (g_initialSleepSecs > 0) {
1394 sleep(g_initialSleepSecs);
1395 }
1396
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001397 bool ok = true;
Hector Dearman11845782018-03-08 14:35:44 +00001398
Wei Wang5b73b742018-03-08 13:33:12 -08001399 if (traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001400 ok &= setUpUserspaceTracing();
1401 }
1402
1403 if (ok && traceStart && !onlyUserspace) {
1404 ok &= setUpKernelTracing();
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +00001405 ok &= setUpVendorTracingWithHal();
Wei Wang5b73b742018-03-08 13:33:12 -08001406 ok &= startTrace();
1407 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001408
1409 if (ok && traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001410
1411 if (!traceStream && !onlyUserspace) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001412 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001413 fflush(stdout);
1414 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001415
1416 // We clear the trace after starting it because tracing gets enabled for
1417 // each CPU individually in the kernel. Having the beginning of the trace
1418 // contain entries from only one CPU can cause "begin" entries without a
1419 // matching "end" entry to show up if a task gets migrated from one CPU to
1420 // another.
Primiano Tucci929325d2022-03-15 20:26:21 +00001421 if (!onlyUserspace) {
Hector Dearman11845782018-03-08 14:35:44 +00001422 ok = clearTrace();
Primiano Tucci929325d2022-03-15 20:26:21 +00001423 writeClockSyncMarker();
1424 }
Martijn Coenend9535872015-11-26 10:00:55 +01001425 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001426 // Sleep to allow the trace to be captured.
1427 struct timespec timeLeft;
1428 timeLeft.tv_sec = g_traceDurationSeconds;
1429 timeLeft.tv_nsec = 0;
1430 do {
1431 if (g_traceAborted) {
1432 break;
1433 }
1434 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1435 }
Martijn Coenend9535872015-11-26 10:00:55 +01001436
1437 if (traceStream) {
1438 streamTrace();
1439 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001440 }
1441
1442 // Stop the trace and restore the default settings.
Hector Dearman11845782018-03-08 14:35:44 +00001443 if (traceStop && !onlyUserspace)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001444 stopTrace();
1445
Hector Dearman11845782018-03-08 14:35:44 +00001446 if (ok && traceDump && !onlyUserspace) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001447 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001448 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001449 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001450 int outFd = STDOUT_FILENO;
1451 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001452 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001453 }
1454 if (outFd == -1) {
1455 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1456 } else {
1457 dprintf(outFd, "TRACE:\n");
1458 dumpTrace(outFd);
1459 if (g_outputFile) {
1460 close(outFd);
1461 }
1462 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001463 } else {
1464 printf("\ntrace aborted.\n");
1465 fflush(stdout);
1466 }
1467 clearTrace();
1468 } else if (!ok) {
1469 fprintf(stderr, "unable to start tracing\n");
1470 }
1471
1472 // Reset the trace buffer size to 1.
Hector Dearman11845782018-03-08 14:35:44 +00001473 if (traceStop) {
1474 cleanUpUserspaceTracing();
Hector Dearmanada0a4a2019-04-09 14:13:14 +01001475 if (!onlyUserspace) {
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +00001476 cleanUpVendorTracingWithHal();
Hector Dearman11845782018-03-08 14:35:44 +00001477 cleanUpKernelTracing();
Hector Dearmanada0a4a2019-04-09 14:13:14 +01001478 }
Hector Dearman11845782018-03-08 14:35:44 +00001479 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001480
1481 return g_traceAborted ? 1 : 0;
1482}