blob: 4160a72e83377596d34304263b957d24552c3158 [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
Daeho Jeonga91385b2022-12-05 14:11:10 -080066#define MAX_SYS_FILES 13
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
Daniele Di Proietto983c4602024-04-15 18:18:01 +000071const char* k_tracePreferSdkProperty = "debug.atrace.prefer_sdk";
sergeyv4144eff2016-04-28 11:40:04 -070072const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
73const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070074const char* k_coreServiceCategory = "core_services";
Corey Tabakaa6c0a722017-05-31 16:37:40 -070075const char* k_pdxServiceCategory = "pdx";
sergeyvdb404152016-05-02 19:26:07 -070076const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080077
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +000078const char* kVendorCategoriesPath = "/vendor/etc/atrace/atrace_categories.txt";
79
80typedef enum { OPT, REQ } requiredness;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080081
82struct TracingCategory {
83 // The name identifying the category.
84 const char* name;
85
86 // A longer description of the category.
87 const char* longname;
88
89 // The userland tracing tags that the category enables.
90 uint64_t tags;
91
92 // The fname==NULL terminated list of /sys/ files that the category
93 // enables.
94 struct {
95 // Whether the file must be writable in order to enable the tracing
96 // category.
97 requiredness required;
98
99 // The path to the enable file.
100 const char* path;
101 } sysfiles[MAX_SYS_FILES];
102};
103
104/* Tracing categories */
105static const TracingCategory k_categories[] = {
Yiwei Zhang63775062020-09-18 11:42:33 -0700106 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, {
107 { OPT, "events/gpu_mem/gpu_mem_total/enable" },
108 } },
MÃ¥rten Kongstad2d4f89b2018-12-03 12:58:56 +0100109 { "input", "Input", ATRACE_TAG_INPUT, { } },
110 { "view", "View System", ATRACE_TAG_VIEW, { } },
111 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
112 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
113 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
114 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
115 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
116 { "video", "Video", ATRACE_TAG_VIDEO, { } },
117 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
118 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
119 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
120 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
121 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
122 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
123 { "power", "Power Management", ATRACE_TAG_POWER, { } },
124 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
125 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
126 { "database", "Database", ATRACE_TAG_DATABASE, { } },
127 { "network", "Network", ATRACE_TAG_NETWORK, { } },
128 { "adb", "ADB", ATRACE_TAG_ADB, { } },
129 { "vibrator", "Vibrator", ATRACE_TAG_VIBRATOR, { } },
130 { "aidl", "AIDL calls", ATRACE_TAG_AIDL, { } },
131 { "nnapi", "NNAPI", ATRACE_TAG_NNAPI, { } },
132 { "rro", "Runtime Resource Overlay", ATRACE_TAG_RRO, { } },
sergeyvdb404152016-05-02 19:26:07 -0700133 { k_coreServiceCategory, "Core services", 0, { } },
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700134 { k_pdxServiceCategory, "PDX services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700135 { "sched", "CPU Scheduling", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800136 { REQ, "events/sched/sched_switch/enable" },
137 { REQ, "events/sched/sched_wakeup/enable" },
Joel Fernandesee593e22017-06-04 13:05:59 -0700138 { OPT, "events/sched/sched_waking/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800139 { OPT, "events/sched/sched_blocked_reason/enable" },
140 { OPT, "events/sched/sched_cpu_hotplug/enable" },
Wei Wangca49dfc2018-05-03 15:45:20 -0700141 { OPT, "events/sched/sched_pi_setprio/enable" },
Carmen Jackson63ea2912019-04-26 10:41:00 -0700142 { OPT, "events/sched/sched_process_exit/enable" },
Joel Fernandes4dfca7c2017-06-15 16:53:52 -0700143 { OPT, "events/cgroup/enable" },
Carmen Jackson63ea2912019-04-26 10:41:00 -0700144 { OPT, "events/oom/oom_score_adj_update/enable" },
145 { OPT, "events/task/task_rename/enable" },
146 { OPT, "events/task/task_newtask/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800147 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700148 { "irq", "IRQ Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800149 { REQ, "events/irq/enable" },
150 { OPT, "events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700151 } },
Joel Fernandes6ccad102017-08-31 08:35:05 -0700152 { "irqoff", "IRQ-disabled code section tracing", 0, {
153 { REQ, "events/preemptirq/irq_enable/enable" },
154 { REQ, "events/preemptirq/irq_disable/enable" },
155 } },
156 { "preemptoff", "Preempt-disabled code section tracing", 0, {
157 { REQ, "events/preemptirq/preempt_enable/enable" },
158 { REQ, "events/preemptirq/preempt_disable/enable" },
159 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100160 { "i2c", "I2C Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800161 { REQ, "events/i2c/enable" },
162 { REQ, "events/i2c/i2c_read/enable" },
163 { REQ, "events/i2c/i2c_write/enable" },
164 { REQ, "events/i2c/i2c_result/enable" },
165 { REQ, "events/i2c/i2c_reply/enable" },
166 { OPT, "events/i2c/smbus_read/enable" },
167 { OPT, "events/i2c/smbus_write/enable" },
168 { OPT, "events/i2c/smbus_result/enable" },
169 { OPT, "events/i2c/smbus_reply/enable" },
Michael Wright43fb6782016-08-18 19:56:43 +0100170 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700171 { "freq", "CPU Frequency", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800172 { REQ, "events/power/cpu_frequency/enable" },
173 { OPT, "events/power/clock_set_rate/enable" },
Kevin DuBois062e0b92017-11-03 15:44:08 -0700174 { OPT, "events/power/clock_disable/enable" },
175 { OPT, "events/power/clock_enable/enable" },
Wei Wang53305dd2018-02-22 11:40:07 -0800176 { OPT, "events/clk/clk_set_rate/enable" },
177 { OPT, "events/clk/clk_disable/enable" },
178 { OPT, "events/clk/clk_enable/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800179 { OPT, "events/power/cpu_frequency_limits/enable" },
Carmen Jackson5ab84322019-08-08 14:35:47 -0700180 { OPT, "events/power/suspend_resume/enable" },
Wei Wang2ded52d2020-07-31 01:13:58 -0700181 { OPT, "events/cpuhp/cpuhp_enter/enable" },
182 { OPT, "events/cpuhp/cpuhp_exit/enable" },
Wei Wang963999c2021-03-17 16:28:59 -0700183 { OPT, "events/cpuhp/cpuhp_pause/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800184 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700185 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800186 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800187 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700188 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800189 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800190 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700191 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800192 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
193 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
194 { OPT, "events/f2fs/f2fs_write_begin/enable" },
195 { OPT, "events/f2fs/f2fs_write_end/enable" },
Daeho Jeonga91385b2022-12-05 14:11:10 -0800196 { OPT, "events/f2fs/f2fs_iostat/enable" },
197 { OPT, "events/f2fs/f2fs_iostat_latency/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800198 { OPT, "events/ext4/ext4_da_write_begin/enable" },
199 { OPT, "events/ext4/ext4_da_write_end/enable" },
200 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
201 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
YH Linc08daed2022-10-01 09:43:06 +0800202 { OPT, "events/block/block_bio_queue/enable" },
203 { OPT, "events/block/block_bio_complete/enable" },
204 { OPT, "events/ufs/ufshcd_command/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800205 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700206 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800207 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700208 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700209 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800210 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800211 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700212 { "sync", "Synchronization", 0, {
Jesse Halla978cef2019-02-25 16:24:10 -0800213 // linux kernel < 4.9
Jesse Hallae001a32018-05-15 12:02:15 -0700214 { OPT, "events/sync/enable" },
Jesse Halla978cef2019-02-25 16:24:10 -0800215 // linux kernel == 4.9.x
Jesse Hallae001a32018-05-15 12:02:15 -0700216 { OPT, "events/fence/enable" },
Jesse Halla978cef2019-02-25 16:24:10 -0800217 // linux kernel > 4.9
218 { OPT, "events/dma_fence/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800219 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700220 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800221 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800222 } },
Colin Cross580407f2014-08-18 15:22:13 -0700223 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800224 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
225 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
226 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
227 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Carmen Jackson7a23eb72018-07-02 13:14:56 -0700228 { OPT, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700229 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800230 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800231 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800232 } },
Scott Bauerae473362015-06-08 16:32:36 -0700233 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800234 { REQ, "events/binder/binder_transaction/enable" },
235 { REQ, "events/binder/binder_transaction_received/enable" },
Mika Raento80c3e5d2018-06-25 16:47:24 +0100236 { REQ, "events/binder/binder_transaction_alloc_buf/enable" },
Martijn Coenen7f3d7a22017-05-26 09:50:55 -0700237 { OPT, "events/binder/binder_set_priority/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700238 } },
239 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800240 { OPT, "events/binder/binder_lock/enable" },
241 { OPT, "events/binder/binder_locked/enable" },
242 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700243 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200244 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800245 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200246 } },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700247 { "memory", "Memory", 0, {
Collin Fijalkovich08e3f4a2020-03-30 16:20:24 -0700248 { OPT, "events/mm_event/mm_event_record/enable" },
Primiano Tucci806ee9e2021-11-15 21:08:06 +0000249 { OPT, "events/synthetic/rss_stat_throttled/enable" },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700250 { OPT, "events/kmem/ion_heap_grow/enable" },
251 { OPT, "events/kmem/ion_heap_shrink/enable" },
Ioannis Ilkos88a85f32020-04-23 22:43:40 +0100252 { OPT, "events/ion/ion_stat/enable" },
Yiwei Zhang63775062020-09-18 11:42:33 -0700253 { OPT, "events/gpu_mem/gpu_mem_total/enable" },
Collin Fijalkovichd4db32b2021-05-21 11:41:40 -0700254 { OPT, "events/fastrpc/fastrpc_dma_stat/enable" },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700255 } },
TeYuan Wang377ca212022-02-14 10:25:00 +0800256 { "thermal", "Thermal event", ATRACE_TAG_THERMAL, {
Wei Wange3079a92020-07-08 15:33:20 -0700257 { REQ, "events/thermal/thermal_temperature/enable" },
258 { OPT, "events/thermal/cdev_update/enable" },
259 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800260};
261
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +0000262// A category in the vendor categories file.
263struct TracingVendorFileCategory {
264 // The name identifying the category.
265 std::string name;
266
267 // If the category is enabled through command.
268 bool enabled = false;
269
270 // Paths to the ftrace enable files (relative to g_traceFolder).
271 std::vector<std::string> ftrace_enable_paths;
272};
273
274// A category in the vendor HIDL HAL.
275struct TracingVendorHalCategory {
Wei Wang16a63a42018-09-21 15:47:45 -0700276 // The name identifying the category.
277 std::string name;
278
279 // A longer description of the category.
280 std::string description;
281
282 // If the category is enabled through command.
283 bool enabled;
284
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +0000285 TracingVendorHalCategory(string&& name, string&& description, bool enabled)
286 : name(std::move(name)), description(std::move(description)), enabled(enabled) {}
Wei Wang16a63a42018-09-21 15:47:45 -0700287};
288
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800289/* Command line options */
290static int g_traceDurationSeconds = 5;
291static bool g_traceOverwrite = false;
292static int g_traceBufferSizeKB = 2048;
293static bool g_compress = false;
294static bool g_nohup = false;
295static int g_initialSleepSecs = 0;
Yi Kong19d5c002018-07-20 13:39:55 -0700296static const char* g_categoriesFile = nullptr;
297static const char* g_kernelTraceFuncs = nullptr;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700298static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700299static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800300
301/* Global state */
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700302static bool g_tracePdx = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800303static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700304static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800305static std::string g_traceFolder;
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +0000306static std::vector<TracingVendorFileCategory> g_vendorFileCategories;
Wei Wang16a63a42018-09-21 15:47:45 -0700307static sp<IAtraceDevice> g_atraceHal;
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +0000308static std::vector<TracingVendorHalCategory> g_vendorHalCategories;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800309
310/* Sys file paths */
311static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800312 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800313
314static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800315 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800316
317static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800318 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800319
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700320static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800321 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700322
323static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800324 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700325
John Recke757b1c2018-06-28 12:24:33 -0700326static const char* k_recordTgidPath =
327 "options/record-tgid";
328
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700329static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800330 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700331
332static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800333 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700334
335static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800336 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700337
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700338static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800339 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700340
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800341static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800342 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800343
344static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800345 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800346
Martijn Coenend9535872015-11-26 10:00:55 +0100347static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800348 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100349
John Reck469a1942015-03-26 15:31:35 -0700350static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800351 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700352
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800353// Check whether a file exists.
354static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800355 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800356}
357
358// Check whether a file is writable.
359static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800360 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800361}
362
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700363// Truncate a file.
364static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800365{
Jamie Gennis43122e72013-03-21 14:06:31 -0700366 // This uses creat rather than truncate because some of the debug kernel
367 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
368 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800369 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700370 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800371 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700372 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700373 return false;
374 }
375
Jamie Gennis43122e72013-03-21 14:06:31 -0700376 close(traceFD);
377
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700378 return true;
379}
380
381static bool _writeStr(const char* filename, const char* str, int flags)
382{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800383 std::string fullFilename = g_traceFolder + filename;
384 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800385 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800386 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800387 strerror(errno), errno);
388 return false;
389 }
390
391 bool ok = true;
392 ssize_t len = strlen(str);
393 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800394 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800395 strerror(errno), errno);
396 ok = false;
397 }
398
399 close(fd);
400
401 return ok;
402}
403
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700404// Write a string to a file, returning true if the write was successful.
405static bool writeStr(const char* filename, const char* str)
406{
407 return _writeStr(filename, str, O_WRONLY);
408}
409
410// Append a string to a file, returning true if the write was successful.
411static bool appendStr(const char* filename, const char* str)
412{
413 return _writeStr(filename, str, O_APPEND|O_WRONLY);
414}
415
John Reck469a1942015-03-26 15:31:35 -0700416static void writeClockSyncMarker()
417{
418 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200419 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800420 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200421 if (fd == -1) {
422 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
423 strerror(errno), errno);
424 return;
425 }
John Reck469a1942015-03-26 15:31:35 -0700426 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200427
428 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
429 if (write(fd, buffer, len) != len) {
430 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
431 }
432
433 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
434 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
435 if (write(fd, buffer, len) != len) {
436 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
437 }
438
439 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700440}
441
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800442// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
443// file.
444static bool setKernelOptionEnable(const char* filename, bool enable)
445{
446 return writeStr(filename, enable ? "1" : "0");
447}
448
449// Check whether the category is supported on the device with the current
450// rootness. A category is supported only if all its required /sys/ files are
451// writable and if enabling the category will enable one or more tracing tags
452// or /sys/ files.
453static bool isCategorySupported(const TracingCategory& category)
454{
sergeyvdb404152016-05-02 19:26:07 -0700455 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700456 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700457 }
458
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700459 if (strcmp(category.name, k_pdxServiceCategory) == 0) {
460 return true;
461 }
462
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800463 bool ok = category.tags != 0;
464 for (int i = 0; i < MAX_SYS_FILES; i++) {
465 const char* path = category.sysfiles[i].path;
466 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700467 if (path != nullptr) {
Carmen Jackson5bbc9a22018-12-06 13:47:18 -0800468 if (fileIsWritable(path)) {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800469 ok = true;
Carmen Jackson5bbc9a22018-12-06 13:47:18 -0800470 } else if (req) {
471 return false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800472 }
473 }
474 }
475 return ok;
476}
477
478// Check whether the category would be supported on the device if the user
479// were root. This function assumes that root is able to write to any file
480// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700481// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800482static bool isCategorySupportedForRoot(const TracingCategory& category)
483{
484 bool ok = category.tags != 0;
485 for (int i = 0; i < MAX_SYS_FILES; i++) {
486 const char* path = category.sysfiles[i].path;
487 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700488 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800489 if (req) {
490 if (!fileExists(path)) {
491 return false;
492 } else {
493 ok = true;
494 }
495 } else {
496 ok |= fileExists(path);
497 }
498 }
499 }
500 return ok;
501}
502
503// Enable or disable overwriting of the kernel trace buffers. Disabling this
504// will cause tracing to stop once the trace buffers have filled up.
505static bool setTraceOverwriteEnable(bool enable)
506{
507 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
508}
509
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700510// Set the user initiated trace property
511static bool setUserInitiatedTraceProperty(bool enable)
512{
513 if (!android::base::SetProperty(k_userInitiatedTraceProperty, enable ? "1" : "")) {
514 fprintf(stderr, "error setting user initiated strace system property\n");
515 return false;
516 }
517 return true;
518}
519
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800520// Enable or disable kernel tracing.
521static bool setTracingEnabled(bool enable)
522{
523 return setKernelOptionEnable(k_tracingOnPath, enable);
524}
525
526// Clear the contents of the kernel trace.
527static bool clearTrace()
528{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700529 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800530}
531
532// Set the size of the kernel's trace buffer in kilobytes.
533static bool setTraceBufferSizeKB(int size)
534{
535 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800536 if (size < 1) {
537 size = 1;
538 }
539 snprintf(str, 32, "%d", size);
540 return writeStr(k_traceBufferSizePath, str);
541}
542
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
Daniele Di Proietto983c4602024-04-15 18:18:01 +0000604// Set the property that's read by userspace to prefer the perfetto SDK.
605static bool setPreferSdkProperty(uint64_t tags)
606{
607 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
608 if (!android::base::SetProperty(k_tracePreferSdkProperty, value)) {
609 fprintf(stderr, "error setting prefer_sdk system property\n");
610 return false;
611 }
612 return true;
613}
614
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700615// Set the system property that indicates which apps should perform
616// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700617static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700618{
sergeyv4144eff2016-04-28 11:40:04 -0700619 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700620 char* start = cmdline;
Yi Kong19d5c002018-07-20 13:39:55 -0700621 while (start != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700622 char* end = strchr(start, ',');
Yi Kong19d5c002018-07-20 13:39:55 -0700623 if (end != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700624 *end = '\0';
625 end++;
626 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700627 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
628 if (!android::base::SetProperty(key, start)) {
629 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700630 clearAppProperties();
631 return false;
632 }
633 start = end;
634 i++;
635 }
636
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700637 std::string value = android::base::StringPrintf("%d", i);
638 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
639 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700640 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700641 return false;
642 }
643 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800644}
645
646// Disable all /sys/ enable files.
647static bool disableKernelTraceEvents() {
648 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700649 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800650 const TracingCategory &c = k_categories[i];
651 for (int j = 0; j < MAX_SYS_FILES; j++) {
652 const char* path = c.sysfiles[j].path;
Yi Kong19d5c002018-07-20 13:39:55 -0700653 if (path != nullptr && fileIsWritable(path)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800654 ok &= setKernelOptionEnable(path, false);
655 }
656 }
657 }
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +0000658 for (const TracingVendorFileCategory& c : g_vendorFileCategories) {
659 for (const std::string& path : c.ftrace_enable_paths) {
660 if (fileIsWritable(path.c_str())) {
661 ok &= setKernelOptionEnable(path.c_str(), false);
662 }
663 }
664 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800665 return ok;
666}
667
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700668// Verify that the comma separated list of functions are being traced by the
669// kernel.
670static bool verifyKernelTraceFuncs(const char* funcs)
671{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100672 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800673 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100674 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700675 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100676 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700677 }
678
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100679 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700680
681 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100682 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700683 bool ok = true;
684 char* myFuncs = strdup(funcs);
685 char* func = strtok(myFuncs, ",");
686 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100687 if (!strchr(func, '*')) {
688 String8 fancyFunc = String8::format("\n%s\n", func);
Tomasz Wasilczyk95000d02023-08-23 18:40:27 +0000689 bool found = funcList.find(fancyFunc.c_str(), 0) >= 0;
Thomas Buhota2c22872016-01-27 09:44:31 +0100690 if (!found || func[0] == '\0') {
691 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
692 "to trace.\n", func);
693 ok = false;
694 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700695 }
Yi Kong19d5c002018-07-20 13:39:55 -0700696 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700697 }
698 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700699 return ok;
700}
701
702// Set the comma separated list of functions that the kernel is to trace.
703static bool setKernelTraceFuncs(const char* funcs)
704{
705 bool ok = true;
706
Yi Kong19d5c002018-07-20 13:39:55 -0700707 if (funcs == nullptr || funcs[0] == '\0') {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700708 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700709 if (fileIsWritable(k_currentTracerPath)) {
710 ok &= writeStr(k_currentTracerPath, "nop");
711 }
712 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700713 ok &= truncateFile(k_ftraceFilterPath);
714 }
715 } else {
716 // Enable kernel function tracing.
717 ok &= writeStr(k_currentTracerPath, "function_graph");
718 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
719 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
720 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700721
722 // Set the requested filter functions.
723 ok &= truncateFile(k_ftraceFilterPath);
724 char* myFuncs = strdup(funcs);
725 char* func = strtok(myFuncs, ",");
726 while (func) {
727 ok &= appendStr(k_ftraceFilterPath, func);
Yi Kong19d5c002018-07-20 13:39:55 -0700728 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700729 }
730 free(myFuncs);
731
732 // Verify that the set functions are being traced.
733 if (ok) {
734 ok &= verifyKernelTraceFuncs(funcs);
735 }
736 }
737
738 return ok;
739}
740
Wei Wang16a63a42018-09-21 15:47:45 -0700741static bool setCategoryEnable(const char* name)
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900742{
Wei Wang16a63a42018-09-21 15:47:45 -0700743 bool vendor_found = false;
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +0000744 for (auto& c : g_vendorFileCategories) {
745 if (strcmp(name, c.name.c_str()) == 0) {
746 c.enabled = true;
747 vendor_found = true;
748 }
749 }
750 for (auto& c : g_vendorHalCategories) {
Wei Wang16a63a42018-09-21 15:47:45 -0700751 if (strcmp(name, c.name.c_str()) == 0) {
752 c.enabled = true;
753 vendor_found = true;
754 }
755 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700756 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900757 const TracingCategory& c = k_categories[i];
758 if (strcmp(name, c.name) == 0) {
759 if (isCategorySupported(c)) {
Wei Wang16a63a42018-09-21 15:47:45 -0700760 g_categoryEnables[i] = true;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900761 return true;
762 } else {
763 if (isCategorySupportedForRoot(c)) {
764 fprintf(stderr, "error: category \"%s\" requires root "
765 "privileges.\n", name);
766 } else {
767 fprintf(stderr, "error: category \"%s\" is not supported "
768 "on this device.\n", name);
769 }
770 return false;
771 }
772 }
773 }
Wei Wang16a63a42018-09-21 15:47:45 -0700774 if (vendor_found) {
775 return true;
776 }
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900777 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
778 return false;
779}
780
781static bool setCategoriesEnableFromFile(const char* categories_file)
782{
783 if (!categories_file) {
784 return true;
785 }
Yi Kong19d5c002018-07-20 13:39:55 -0700786 Tokenizer* tokenizer = nullptr;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900787 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
788 return false;
789 }
790 bool ok = true;
791 while (!tokenizer->isEol()) {
792 String8 token = tokenizer->nextToken(" ");
Tomasz Wasilczyk8a0e3522023-08-14 18:03:09 +0000793 if (token.empty()) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900794 tokenizer->skipDelimiters(" ");
795 continue;
796 }
Tomasz Wasilczyk95000d02023-08-23 18:40:27 +0000797 ok &= setCategoryEnable(token.c_str());
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900798 }
799 delete tokenizer;
800 return ok;
801}
802
Hector Dearman11845782018-03-08 14:35:44 +0000803static bool setUpUserspaceTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800804{
805 bool ok = true;
806
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800807 // Set up the tags property.
808 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700809 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800810 if (g_categoryEnables[i]) {
811 const TracingCategory &c = k_categories[i];
812 tags |= c.tags;
813 }
814 }
sergeyvdb404152016-05-02 19:26:07 -0700815
816 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700817 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700818 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
819 coreServicesTagEnabled = g_categoryEnables[i];
820 }
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700821
822 // Set whether to poke PDX services in this session.
823 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
824 g_tracePdx = g_categoryEnables[i];
825 }
sergeyvdb404152016-05-02 19:26:07 -0700826 }
827
828 std::string packageList(g_debugAppCmdLine);
829 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700830 if (!packageList.empty()) {
831 packageList += ",";
832 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700833 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700834 }
Dan Austin09a79872016-05-31 13:27:03 -0700835 ok &= setAppCmdlineProperty(&packageList[0]);
Florian Mayer6263b582019-12-10 13:28:45 +0000836 ok &= setTagsProperty(tags);
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700837 if (g_tracePdx) {
838 ok &= ServiceUtility::PokeServices();
839 }
840
Hector Dearman11845782018-03-08 14:35:44 +0000841 return ok;
842}
843
844static void cleanUpUserspaceTracing()
845{
846 setTagsProperty(0);
847 clearAppProperties();
Hector Dearman11845782018-03-08 14:35:44 +0000848
849 if (g_tracePdx) {
850 ServiceUtility::PokeServices();
851 }
852}
853
854
855// Set all the kernel tracing settings to the desired state for this trace
856// capture.
857static bool setUpKernelTracing()
858{
859 bool ok = true;
860
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700861 ok &= setUserInitiatedTraceProperty(true);
862
Hector Dearman11845782018-03-08 14:35:44 +0000863 // Set up the tracing options.
864 ok &= setCategoriesEnableFromFile(g_categoriesFile);
865 ok &= setTraceOverwriteEnable(g_traceOverwrite);
866 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
Hector Dearman11845782018-03-08 14:35:44 +0000867 ok &= setClock();
868 ok &= setPrintTgidEnableIfPresent(true);
869 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
870
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800871 // Disable all the sysfs enables. This is done as a separate loop from
872 // the enables to allow the same enable to exist in multiple categories.
873 ok &= disableKernelTraceEvents();
874
875 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700876 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800877 if (g_categoryEnables[i]) {
878 const TracingCategory &c = k_categories[i];
879 for (int j = 0; j < MAX_SYS_FILES; j++) {
880 const char* path = c.sysfiles[j].path;
881 bool required = c.sysfiles[j].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700882 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800883 if (fileIsWritable(path)) {
884 ok &= setKernelOptionEnable(path, true);
885 } else if (required) {
886 fprintf(stderr, "error writing file %s\n", path);
887 ok = false;
888 }
889 }
890 }
891 }
892 }
893
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +0000894 for (const TracingVendorFileCategory& c : g_vendorFileCategories) {
895 if (c.enabled) {
896 for (const std::string& path : c.ftrace_enable_paths) {
897 if (fileIsWritable(path.c_str())) {
898 ok &= setKernelOptionEnable(path.c_str(), true);
899 }
900 }
901 }
902 }
903
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800904 return ok;
905}
906
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700907// Reset all the kernel tracing settings to their default state.
Hector Dearman11845782018-03-08 14:35:44 +0000908static void cleanUpKernelTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800909{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800910 // Disable all tracing that we're able to.
911 disableKernelTraceEvents();
912
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800913 // Set the options back to their defaults.
914 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700915 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700916 setPrintTgidEnableIfPresent(false);
Yi Kong19d5c002018-07-20 13:39:55 -0700917 setKernelTraceFuncs(nullptr);
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700918 setUserInitiatedTraceProperty(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700919}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800920
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700921// Enable tracing in the kernel.
922static bool startTrace()
923{
924 return setTracingEnabled(true);
925}
926
927// Disable tracing in the kernel.
928static void stopTrace()
929{
930 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800931}
932
Daniele Di Proietto983c4602024-04-15 18:18:01 +0000933static bool preferSdkCategories() {
934 uint64_t tags = 0;
935 for (size_t i = 0; i < arraysize(k_categories); i++) {
936 if (g_categoryEnables[i]) {
937 const TracingCategory& c = k_categories[i];
938 tags |= c.tags;
939 }
940 }
941 return setPreferSdkProperty(tags);
942}
943
Martijn Coenend9535872015-11-26 10:00:55 +0100944// Read data from the tracing pipe and forward to stdout
945static void streamTrace()
946{
947 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800948 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100949 if (traceFD == -1) {
950 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
951 strerror(errno), errno);
952 return;
953 }
954 while (!g_traceAborted) {
955 ssize_t bytes_read = read(traceFD, trace_data, 4096);
956 if (bytes_read > 0) {
957 write(STDOUT_FILENO, trace_data, bytes_read);
958 fflush(stdout);
959 } else {
960 if (!g_traceAborted) {
961 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
962 bytes_read, errno, strerror(errno));
963 }
964 break;
965 }
966 }
967}
968
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800969// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700970static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800971{
John Reck6c8ac922016-03-28 11:25:30 -0700972 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800973 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800974 if (traceFD == -1) {
975 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
976 strerror(errno), errno);
977 return;
978 }
979
980 if (g_compress) {
981 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800982 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700983
984 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800985 if (result != Z_OK) {
986 fprintf(stderr, "error initializing zlib: %d\n", result);
987 close(traceFD);
988 return;
989 }
990
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700991 constexpr size_t bufSize = 64*1024;
992 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
993 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
994 if (!in || !out) {
995 fprintf(stderr, "couldn't allocate buffers\n");
996 close(traceFD);
997 return;
998 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800999
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001000 int flush = Z_NO_FLUSH;
1001
1002 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001003 zs.avail_out = bufSize;
1004
1005 do {
1006
1007 if (zs.avail_in == 0) {
1008 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001009 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001010 if (result < 0) {
1011 fprintf(stderr, "error reading trace: %s (%d)\n",
1012 strerror(errno), errno);
1013 result = Z_STREAM_END;
1014 break;
1015 } else if (result == 0) {
1016 flush = Z_FINISH;
1017 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001018 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001019 zs.avail_in = result;
1020 }
1021 }
1022
1023 if (zs.avail_out == 0) {
1024 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -07001025 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001026 if ((size_t)result < bufSize) {
1027 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1028 strerror(errno), errno);
1029 result = Z_STREAM_END; // skip deflate error message
1030 zs.avail_out = bufSize; // skip the final write
1031 break;
1032 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001033 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001034 zs.avail_out = bufSize;
1035 }
1036
1037 } while ((result = deflate(&zs, flush)) == Z_OK);
1038
1039 if (result != Z_STREAM_END) {
1040 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
1041 }
1042
1043 if (zs.avail_out < bufSize) {
1044 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -07001045 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001046 if ((size_t)result < bytes) {
1047 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1048 strerror(errno), errno);
1049 }
1050 }
1051
1052 result = deflateEnd(&zs);
1053 if (result != Z_OK) {
1054 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1055 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001056 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001057 char buf[4096];
1058 ssize_t rc;
1059 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1060 if (!android::base::WriteFully(outFd, buf, rc)) {
1061 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1062 break;
1063 }
1064 }
1065 if (rc == -1) {
1066 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001067 }
1068 }
1069
1070 close(traceFD);
1071}
1072
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001073static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001074{
1075 if (!g_nohup) {
1076 g_traceAborted = true;
1077 }
1078}
1079
1080static void registerSigHandler()
1081{
1082 struct sigaction sa;
1083 sigemptyset(&sa.sa_mask);
1084 sa.sa_flags = 0;
1085 sa.sa_handler = handleSignal;
Yi Kong19d5c002018-07-20 13:39:55 -07001086 sigaction(SIGHUP, &sa, nullptr);
1087 sigaction(SIGINT, &sa, nullptr);
1088 sigaction(SIGQUIT, &sa, nullptr);
1089 sigaction(SIGTERM, &sa, nullptr);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001090}
1091
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001092static void listSupportedCategories()
1093{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001094 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001095 const TracingCategory& c = k_categories[i];
1096 if (isCategorySupported(c)) {
1097 printf(" %10s - %s\n", c.name, c.longname);
1098 }
1099 }
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +00001100 for (const auto& c : g_vendorFileCategories) {
1101 printf(" %10s - (VENDOR)\n", c.name.c_str());
1102 }
1103 for (const auto& c : g_vendorHalCategories) {
Wei Wang16a63a42018-09-21 15:47:45 -07001104 printf(" %10s - %s (HAL)\n", c.name.c_str(), c.description.c_str());
1105 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001106}
1107
1108// Print the command usage help to stderr.
1109static void showHelp(const char *cmd)
1110{
1111 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1112 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001113 " -a appname enable app-level tracing for a comma "
Daniel Colascione519a0792018-02-09 20:05:39 -08001114 "separated list of cmdlines; * is a wildcard matching any process\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001115 " -b N use a trace buffer size of N KB\n"
1116 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001117 " -f filename use the categories written in a file as space-separated\n"
1118 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001119 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001120 " -n ignore signals\n"
1121 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001122 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001123 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001124 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001125 " --async_dump dump the current contents of circular trace buffer\n"
1126 " --async_stop stop tracing and dump the current contents of circular\n"
1127 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001128 " --stream stream trace to stdout as it enters the trace buffer\n"
1129 " Note: this can take significant CPU time, and is best\n"
1130 " used for measuring things that are not affected by\n"
1131 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001132 " --list_categories\n"
1133 " list the available tracing categories\n"
Daniele Di Proietto983c4602024-04-15 18:18:01 +00001134 " --prefer_sdk\n"
1135 " prefer the perfetto sdk over legacy atrace for\n"
1136 " categories and exits immediately\n"
John Reck40b26b42016-03-30 09:44:36 -07001137 " -o filename write the trace to the specified file instead\n"
1138 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001139 );
1140}
1141
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001142bool findTraceFiles()
1143{
1144 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1145 static const std::string tracefs_path = "/sys/kernel/tracing/";
1146 static const std::string trace_file = "trace_marker";
1147
1148 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1149 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1150
1151 if (!tracefs && !debugfs) {
1152 fprintf(stderr, "Error: Did not find trace folder\n");
1153 return false;
1154 }
1155
1156 if (tracefs) {
1157 g_traceFolder = tracefs_path;
1158 } else {
1159 g_traceFolder = debugfs_path;
1160 }
1161
1162 return true;
1163}
1164
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +00001165void initVendorCategoriesFromFile() {
1166 std::ifstream is(kVendorCategoriesPath);
1167 for (std::string line; std::getline(is, line);) {
1168 if (line.empty()) {
1169 continue;
1170 }
1171 if (android::base::StartsWith(line, ' ') || android::base::StartsWith(line, '\t')) {
1172 if (g_vendorFileCategories.empty()) {
1173 fprintf(stderr, "Malformed vendor categories file\n");
1174 exit(1);
1175 return;
1176 }
1177 std::string_view path = std::string_view(line).substr(1);
1178 while (android::base::StartsWith(path, ' ') || android::base::StartsWith(path, '\t')) {
1179 path.remove_prefix(1);
1180 }
1181 if (path.empty()) {
1182 continue;
1183 }
1184 std::string enable_path = "events/";
1185 enable_path += path;
1186 enable_path += "/enable";
1187 g_vendorFileCategories.back().ftrace_enable_paths.push_back(std::move(enable_path));
1188 } else {
1189 TracingVendorFileCategory cat;
1190 cat.name = line;
1191 g_vendorFileCategories.push_back(std::move(cat));
1192 }
1193 }
1194}
1195
1196void initVendorCategoriesFromHal() {
Wei Wang16a63a42018-09-21 15:47:45 -07001197 g_atraceHal = IAtraceDevice::getService();
1198
1199 if (g_atraceHal == nullptr) {
1200 // No atrace HAL
1201 return;
1202 }
1203
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +00001204 Return<void> ret = g_atraceHal->listCategories([](const auto& list) {
1205 g_vendorHalCategories.reserve(list.size());
1206 for (const auto& category : list) {
1207 g_vendorHalCategories.emplace_back(category.name, category.description, false);
1208 }
1209 });
Wei Wang16a63a42018-09-21 15:47:45 -07001210 if (!ret.isOk()) {
1211 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1212 }
1213}
1214
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +00001215void initVendorCategories() {
1216 // If kVendorCategoriesPath exists on the filesystem, do not use the HAL.
1217 if (access(kVendorCategoriesPath, F_OK) != -1) {
1218 initVendorCategoriesFromFile();
1219 } else {
1220 initVendorCategoriesFromHal();
1221 }
1222}
1223
1224static bool setUpVendorTracingWithHal() {
Wei Wang16a63a42018-09-21 15:47:45 -07001225 if (g_atraceHal == nullptr) {
1226 // No atrace HAL
1227 return true;
1228 }
1229
1230 std::vector<hidl_string> categories;
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +00001231 for (const auto& c : g_vendorHalCategories) {
Wei Wang16a63a42018-09-21 15:47:45 -07001232 if (c.enabled) {
1233 categories.emplace_back(c.name);
1234 }
1235 }
1236
1237 if (!categories.size()) {
1238 return true;
1239 }
1240
1241 auto ret = g_atraceHal->enableCategories(categories);
1242 if (!ret.isOk()) {
1243 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1244 return false;
1245 } else if (ret != Status::SUCCESS) {
1246 fprintf(stderr, "calling atrace HAL failed: %s\n", toString(ret).c_str());
1247 return false;
1248 }
1249 return true;
1250}
1251
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +00001252static bool cleanUpVendorTracingWithHal() {
Wei Wang16a63a42018-09-21 15:47:45 -07001253 if (g_atraceHal == nullptr) {
1254 // No atrace HAL
1255 return true;
1256 }
1257
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +00001258 if (!g_vendorHalCategories.size()) {
1259 // No vendor HAL categories
Wei Wang16a63a42018-09-21 15:47:45 -07001260 return true;
1261 }
1262
1263 auto ret = g_atraceHal->disableAllCategories();
1264 if (!ret.isOk()) {
1265 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1266 return false;
1267 } else if (ret != Status::SUCCESS) {
1268 fprintf(stderr, "calling atrace HAL failed: %s\n", toString(ret).c_str());
1269 return false;
1270 }
1271 return true;
1272}
1273
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001274int main(int argc, char **argv)
1275{
1276 bool async = false;
1277 bool traceStart = true;
1278 bool traceStop = true;
1279 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001280 bool traceStream = false;
Daniele Di Proietto983c4602024-04-15 18:18:01 +00001281 bool preferSdk = false;
Hector Dearman11845782018-03-08 14:35:44 +00001282 bool onlyUserspace = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001283
1284 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1285 showHelp(argv[0]);
1286 exit(0);
1287 }
1288
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001289 if (!findTraceFiles()) {
1290 fprintf(stderr, "No trace folder found\n");
1291 exit(-1);
1292 }
1293
Wei Wang16a63a42018-09-21 15:47:45 -07001294 initVendorCategories();
1295
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001296 for (;;) {
1297 int ret;
1298 int option_index = 0;
1299 static struct option long_options[] = {
Yi Kong19d5c002018-07-20 13:39:55 -07001300 {"async_start", no_argument, nullptr, 0 },
1301 {"async_stop", no_argument, nullptr, 0 },
1302 {"async_dump", no_argument, nullptr, 0 },
1303 {"only_userspace", no_argument, nullptr, 0 },
1304 {"list_categories", no_argument, nullptr, 0 },
1305 {"stream", no_argument, nullptr, 0 },
Daniele Di Proietto983c4602024-04-15 18:18:01 +00001306 {"prefer_sdk", no_argument, nullptr, 0 },
Yi Kong19d5c002018-07-20 13:39:55 -07001307 {nullptr, 0, nullptr, 0 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001308 };
1309
John Reck40b26b42016-03-30 09:44:36 -07001310 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001311 long_options, &option_index);
1312
1313 if (ret < 0) {
1314 for (int i = optind; i < argc; i++) {
Primiano Tucci3a26ff62022-03-15 18:53:46 +00001315 setCategoryEnable(argv[i]);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001316 }
1317 break;
1318 }
1319
1320 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001321 case 'a':
1322 g_debugAppCmdLine = optarg;
1323 break;
1324
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001325 case 'b':
1326 g_traceBufferSizeKB = atoi(optarg);
1327 break;
1328
1329 case 'c':
1330 g_traceOverwrite = true;
1331 break;
1332
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001333 case 'f':
1334 g_categoriesFile = optarg;
1335 break;
1336
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001337 case 'k':
1338 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001339 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001340
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001341 case 'n':
1342 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001343 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001344
1345 case 's':
1346 g_initialSleepSecs = atoi(optarg);
1347 break;
1348
1349 case 't':
1350 g_traceDurationSeconds = atoi(optarg);
1351 break;
1352
1353 case 'z':
1354 g_compress = true;
1355 break;
1356
John Reck40b26b42016-03-30 09:44:36 -07001357 case 'o':
1358 g_outputFile = optarg;
1359 break;
1360
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001361 case 0:
1362 if (!strcmp(long_options[option_index].name, "async_start")) {
1363 async = true;
1364 traceStop = false;
1365 traceDump = false;
1366 g_traceOverwrite = true;
1367 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1368 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001369 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001370 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1371 async = true;
1372 traceStart = false;
1373 traceStop = false;
Hector Dearman11845782018-03-08 14:35:44 +00001374 } else if (!strcmp(long_options[option_index].name, "only_userspace")) {
1375 onlyUserspace = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001376 } else if (!strcmp(long_options[option_index].name, "stream")) {
1377 traceStream = true;
1378 traceDump = false;
Daniele Di Proietto983c4602024-04-15 18:18:01 +00001379 } else if (!strcmp(long_options[option_index].name, "prefer_sdk")) {
1380 preferSdk = true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001381 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1382 listSupportedCategories();
1383 exit(0);
1384 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001385 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001386
1387 default:
1388 fprintf(stderr, "\n");
1389 showHelp(argv[0]);
1390 exit(-1);
1391 break;
1392 }
1393 }
1394
Daniele Di Proietto983c4602024-04-15 18:18:01 +00001395 if (preferSdk) {
1396 bool res = preferSdkCategories();
1397 exit(res ? 0 : 1);
1398 }
1399
Hector Dearman11845782018-03-08 14:35:44 +00001400 if (onlyUserspace) {
1401 if (!async || !(traceStart || traceStop)) {
1402 fprintf(stderr, "--only_userspace can only be used with "
1403 "--async_start or --async_stop\n");
1404 exit(1);
1405 }
1406 }
1407
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001408 registerSigHandler();
1409
1410 if (g_initialSleepSecs > 0) {
1411 sleep(g_initialSleepSecs);
1412 }
1413
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001414 bool ok = true;
Hector Dearman11845782018-03-08 14:35:44 +00001415
Wei Wang5b73b742018-03-08 13:33:12 -08001416 if (traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001417 ok &= setUpUserspaceTracing();
1418 }
1419
1420 if (ok && traceStart && !onlyUserspace) {
1421 ok &= setUpKernelTracing();
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +00001422 ok &= setUpVendorTracingWithHal();
Wei Wang5b73b742018-03-08 13:33:12 -08001423 ok &= startTrace();
1424 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001425
1426 if (ok && traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001427
1428 if (!traceStream && !onlyUserspace) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001429 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001430 fflush(stdout);
1431 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001432
1433 // We clear the trace after starting it because tracing gets enabled for
1434 // each CPU individually in the kernel. Having the beginning of the trace
1435 // contain entries from only one CPU can cause "begin" entries without a
1436 // matching "end" entry to show up if a task gets migrated from one CPU to
1437 // another.
Primiano Tucci929325d2022-03-15 20:26:21 +00001438 if (!onlyUserspace) {
Hector Dearman11845782018-03-08 14:35:44 +00001439 ok = clearTrace();
Primiano Tucci929325d2022-03-15 20:26:21 +00001440 writeClockSyncMarker();
1441 }
Martijn Coenend9535872015-11-26 10:00:55 +01001442 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001443 // Sleep to allow the trace to be captured.
1444 struct timespec timeLeft;
1445 timeLeft.tv_sec = g_traceDurationSeconds;
1446 timeLeft.tv_nsec = 0;
1447 do {
1448 if (g_traceAborted) {
1449 break;
1450 }
1451 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1452 }
Martijn Coenend9535872015-11-26 10:00:55 +01001453
1454 if (traceStream) {
1455 streamTrace();
1456 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001457 }
1458
1459 // Stop the trace and restore the default settings.
Hector Dearman11845782018-03-08 14:35:44 +00001460 if (traceStop && !onlyUserspace)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001461 stopTrace();
1462
Hector Dearman11845782018-03-08 14:35:44 +00001463 if (ok && traceDump && !onlyUserspace) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001464 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001465 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001466 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001467 int outFd = STDOUT_FILENO;
1468 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001469 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001470 }
1471 if (outFd == -1) {
1472 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1473 } else {
1474 dprintf(outFd, "TRACE:\n");
1475 dumpTrace(outFd);
1476 if (g_outputFile) {
1477 close(outFd);
1478 }
1479 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001480 } else {
1481 printf("\ntrace aborted.\n");
1482 fflush(stdout);
1483 }
1484 clearTrace();
1485 } else if (!ok) {
1486 fprintf(stderr, "unable to start tracing\n");
1487 }
1488
1489 // Reset the trace buffer size to 1.
Hector Dearman11845782018-03-08 14:35:44 +00001490 if (traceStop) {
1491 cleanUpUserspaceTracing();
Hector Dearmanada0a4a2019-04-09 14:13:14 +01001492 if (!onlyUserspace) {
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +00001493 cleanUpVendorTracingWithHal();
Hector Dearman11845782018-03-08 14:35:44 +00001494 cleanUpKernelTracing();
Hector Dearmanada0a4a2019-04-09 14:13:14 +01001495 }
Hector Dearman11845782018-03-08 14:35:44 +00001496 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001497
1498 return g_traceAborted ? 1 : 0;
1499}