blob: 888dc4ec0db398f39682037ea44fac39c1204008 [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
44#include <utils/String8.h>
John Reck469a1942015-03-26 15:31:35 -070045#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +090046#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080047#include <utils/Trace.h>
Stephane Gasparinid8419c22016-03-02 13:45:15 +010048#include <android-base/file.h>
Elliott Hughes5fd6ff62017-03-28 14:55:31 -070049#include <android-base/macros.h>
50#include <android-base/properties.h>
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +000051#include <android-base/strings.h>
Elliott Hughes5fd6ff62017-03-28 14:55:31 -070052#include <android-base/stringprintf.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080053
54using namespace android;
Wei Wang16a63a42018-09-21 15:47:45 -070055using hardware::hidl_vec;
56using hardware::hidl_string;
57using hardware::Return;
58using hardware::atrace::V1_0::IAtraceDevice;
59using hardware::atrace::V1_0::Status;
60using hardware::atrace::V1_0::toString;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080061
Martijn Coenenee9b97e2016-11-16 16:00:26 +010062using std::string;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080063
Daeho Jeonga91385b2022-12-05 14:11:10 -080064#define MAX_SYS_FILES 13
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080065
66const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
Carmen Jackson65ecfbb2018-05-22 10:29:47 -070067const char* k_userInitiatedTraceProperty = "debug.atrace.user_initiated";
sergeyv4144eff2016-04-28 11:40:04 -070068
Daniele Di Proietto983c4602024-04-15 18:18:01 +000069const char* k_tracePreferSdkProperty = "debug.atrace.prefer_sdk";
sergeyv4144eff2016-04-28 11:40:04 -070070const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
71const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070072const char* k_coreServiceCategory = "core_services";
73const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080074
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +000075const char* kVendorCategoriesPath = "/vendor/etc/atrace/atrace_categories.txt";
76
77typedef enum { OPT, REQ } requiredness;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080078
79struct TracingCategory {
80 // The name identifying the category.
81 const char* name;
82
83 // A longer description of the category.
84 const char* longname;
85
86 // The userland tracing tags that the category enables.
87 uint64_t tags;
88
89 // The fname==NULL terminated list of /sys/ files that the category
90 // enables.
91 struct {
92 // Whether the file must be writable in order to enable the tracing
93 // category.
94 requiredness required;
95
96 // The path to the enable file.
97 const char* path;
98 } sysfiles[MAX_SYS_FILES];
99};
100
101/* Tracing categories */
102static const TracingCategory k_categories[] = {
Yiwei Zhang63775062020-09-18 11:42:33 -0700103 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, {
104 { OPT, "events/gpu_mem/gpu_mem_total/enable" },
105 } },
MÃ¥rten Kongstad2d4f89b2018-12-03 12:58:56 +0100106 { "input", "Input", ATRACE_TAG_INPUT, { } },
107 { "view", "View System", ATRACE_TAG_VIEW, { } },
108 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
109 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
110 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
111 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
112 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
113 { "video", "Video", ATRACE_TAG_VIDEO, { } },
114 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
115 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
116 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
117 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
118 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
119 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
120 { "power", "Power Management", ATRACE_TAG_POWER, { } },
121 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
122 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
123 { "database", "Database", ATRACE_TAG_DATABASE, { } },
124 { "network", "Network", ATRACE_TAG_NETWORK, { } },
125 { "adb", "ADB", ATRACE_TAG_ADB, { } },
126 { "vibrator", "Vibrator", ATRACE_TAG_VIBRATOR, { } },
127 { "aidl", "AIDL calls", ATRACE_TAG_AIDL, { } },
128 { "nnapi", "NNAPI", ATRACE_TAG_NNAPI, { } },
129 { "rro", "Runtime Resource Overlay", ATRACE_TAG_RRO, { } },
sergeyvdb404152016-05-02 19:26:07 -0700130 { k_coreServiceCategory, "Core services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700131 { "sched", "CPU Scheduling", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800132 { REQ, "events/sched/sched_switch/enable" },
133 { REQ, "events/sched/sched_wakeup/enable" },
Joel Fernandesee593e22017-06-04 13:05:59 -0700134 { OPT, "events/sched/sched_waking/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800135 { OPT, "events/sched/sched_blocked_reason/enable" },
136 { OPT, "events/sched/sched_cpu_hotplug/enable" },
Wei Wangca49dfc2018-05-03 15:45:20 -0700137 { OPT, "events/sched/sched_pi_setprio/enable" },
Carmen Jackson63ea2912019-04-26 10:41:00 -0700138 { OPT, "events/sched/sched_process_exit/enable" },
Joel Fernandes4dfca7c2017-06-15 16:53:52 -0700139 { OPT, "events/cgroup/enable" },
Carmen Jackson63ea2912019-04-26 10:41:00 -0700140 { OPT, "events/oom/oom_score_adj_update/enable" },
141 { OPT, "events/task/task_rename/enable" },
142 { OPT, "events/task/task_newtask/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800143 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700144 { "irq", "IRQ Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800145 { REQ, "events/irq/enable" },
146 { OPT, "events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700147 } },
Joel Fernandes6ccad102017-08-31 08:35:05 -0700148 { "irqoff", "IRQ-disabled code section tracing", 0, {
149 { REQ, "events/preemptirq/irq_enable/enable" },
150 { REQ, "events/preemptirq/irq_disable/enable" },
151 } },
152 { "preemptoff", "Preempt-disabled code section tracing", 0, {
153 { REQ, "events/preemptirq/preempt_enable/enable" },
154 { REQ, "events/preemptirq/preempt_disable/enable" },
155 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100156 { "i2c", "I2C Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800157 { REQ, "events/i2c/enable" },
158 { REQ, "events/i2c/i2c_read/enable" },
159 { REQ, "events/i2c/i2c_write/enable" },
160 { REQ, "events/i2c/i2c_result/enable" },
161 { REQ, "events/i2c/i2c_reply/enable" },
162 { OPT, "events/i2c/smbus_read/enable" },
163 { OPT, "events/i2c/smbus_write/enable" },
164 { OPT, "events/i2c/smbus_result/enable" },
165 { OPT, "events/i2c/smbus_reply/enable" },
Michael Wright43fb6782016-08-18 19:56:43 +0100166 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700167 { "freq", "CPU Frequency", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800168 { REQ, "events/power/cpu_frequency/enable" },
169 { OPT, "events/power/clock_set_rate/enable" },
Kevin DuBois062e0b92017-11-03 15:44:08 -0700170 { OPT, "events/power/clock_disable/enable" },
171 { OPT, "events/power/clock_enable/enable" },
Wei Wang53305dd2018-02-22 11:40:07 -0800172 { OPT, "events/clk/clk_set_rate/enable" },
173 { OPT, "events/clk/clk_disable/enable" },
174 { OPT, "events/clk/clk_enable/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800175 { OPT, "events/power/cpu_frequency_limits/enable" },
Carmen Jackson5ab84322019-08-08 14:35:47 -0700176 { OPT, "events/power/suspend_resume/enable" },
Wei Wang2ded52d2020-07-31 01:13:58 -0700177 { OPT, "events/cpuhp/cpuhp_enter/enable" },
178 { OPT, "events/cpuhp/cpuhp_exit/enable" },
Wei Wang963999c2021-03-17 16:28:59 -0700179 { OPT, "events/cpuhp/cpuhp_pause/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800180 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700181 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800182 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800183 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700184 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800185 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800186 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700187 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800188 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
189 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
190 { OPT, "events/f2fs/f2fs_write_begin/enable" },
191 { OPT, "events/f2fs/f2fs_write_end/enable" },
Daeho Jeonga91385b2022-12-05 14:11:10 -0800192 { OPT, "events/f2fs/f2fs_iostat/enable" },
193 { OPT, "events/f2fs/f2fs_iostat_latency/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800194 { OPT, "events/ext4/ext4_da_write_begin/enable" },
195 { OPT, "events/ext4/ext4_da_write_end/enable" },
196 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
197 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
YH Linc08daed2022-10-01 09:43:06 +0800198 { OPT, "events/block/block_bio_queue/enable" },
199 { OPT, "events/block/block_bio_complete/enable" },
200 { OPT, "events/ufs/ufshcd_command/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800201 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700202 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800203 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700204 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700205 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800206 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800207 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700208 { "sync", "Synchronization", 0, {
Jesse Halla978cef2019-02-25 16:24:10 -0800209 // linux kernel < 4.9
Jesse Hallae001a32018-05-15 12:02:15 -0700210 { OPT, "events/sync/enable" },
Jesse Halla978cef2019-02-25 16:24:10 -0800211 // linux kernel == 4.9.x
Jesse Hallae001a32018-05-15 12:02:15 -0700212 { OPT, "events/fence/enable" },
Jesse Halla978cef2019-02-25 16:24:10 -0800213 // linux kernel > 4.9
214 { OPT, "events/dma_fence/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800215 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700216 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800217 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800218 } },
Colin Cross580407f2014-08-18 15:22:13 -0700219 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800220 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
221 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
222 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
223 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Carmen Jackson7a23eb72018-07-02 13:14:56 -0700224 { OPT, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700225 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800226 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800227 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800228 } },
Scott Bauerae473362015-06-08 16:32:36 -0700229 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800230 { REQ, "events/binder/binder_transaction/enable" },
231 { REQ, "events/binder/binder_transaction_received/enable" },
Mika Raento80c3e5d2018-06-25 16:47:24 +0100232 { REQ, "events/binder/binder_transaction_alloc_buf/enable" },
Martijn Coenen7f3d7a22017-05-26 09:50:55 -0700233 { OPT, "events/binder/binder_set_priority/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700234 } },
235 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800236 { OPT, "events/binder/binder_lock/enable" },
237 { OPT, "events/binder/binder_locked/enable" },
238 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700239 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200240 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800241 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200242 } },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700243 { "memory", "Memory", 0, {
Collin Fijalkovich08e3f4a2020-03-30 16:20:24 -0700244 { OPT, "events/mm_event/mm_event_record/enable" },
Primiano Tucci806ee9e2021-11-15 21:08:06 +0000245 { OPT, "events/synthetic/rss_stat_throttled/enable" },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700246 { OPT, "events/kmem/ion_heap_grow/enable" },
247 { OPT, "events/kmem/ion_heap_shrink/enable" },
Ioannis Ilkos88a85f32020-04-23 22:43:40 +0100248 { OPT, "events/ion/ion_stat/enable" },
Yiwei Zhang63775062020-09-18 11:42:33 -0700249 { OPT, "events/gpu_mem/gpu_mem_total/enable" },
Collin Fijalkovichd4db32b2021-05-21 11:41:40 -0700250 { OPT, "events/fastrpc/fastrpc_dma_stat/enable" },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700251 } },
TeYuan Wang377ca212022-02-14 10:25:00 +0800252 { "thermal", "Thermal event", ATRACE_TAG_THERMAL, {
Wei Wange3079a92020-07-08 15:33:20 -0700253 { REQ, "events/thermal/thermal_temperature/enable" },
254 { OPT, "events/thermal/cdev_update/enable" },
255 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800256};
257
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +0000258// A category in the vendor categories file.
259struct TracingVendorFileCategory {
260 // The name identifying the category.
261 std::string name;
262
263 // If the category is enabled through command.
264 bool enabled = false;
265
266 // Paths to the ftrace enable files (relative to g_traceFolder).
267 std::vector<std::string> ftrace_enable_paths;
268};
269
270// A category in the vendor HIDL HAL.
271struct TracingVendorHalCategory {
Wei Wang16a63a42018-09-21 15:47:45 -0700272 // The name identifying the category.
273 std::string name;
274
275 // A longer description of the category.
276 std::string description;
277
278 // If the category is enabled through command.
279 bool enabled;
280
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +0000281 TracingVendorHalCategory(string&& name, string&& description, bool enabled)
282 : name(std::move(name)), description(std::move(description)), enabled(enabled) {}
Wei Wang16a63a42018-09-21 15:47:45 -0700283};
284
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800285/* Command line options */
286static int g_traceDurationSeconds = 5;
287static bool g_traceOverwrite = false;
288static int g_traceBufferSizeKB = 2048;
289static bool g_compress = false;
290static bool g_nohup = false;
291static int g_initialSleepSecs = 0;
Yi Kong19d5c002018-07-20 13:39:55 -0700292static const char* g_categoriesFile = nullptr;
293static const char* g_kernelTraceFuncs = nullptr;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700294static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700295static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800296
297/* Global state */
298static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700299static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800300static std::string g_traceFolder;
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +0000301static std::vector<TracingVendorFileCategory> g_vendorFileCategories;
Wei Wang16a63a42018-09-21 15:47:45 -0700302static sp<IAtraceDevice> g_atraceHal;
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +0000303static std::vector<TracingVendorHalCategory> g_vendorHalCategories;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800304
305/* Sys file paths */
306static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800307 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800308
309static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800310 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800311
312static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800313 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800314
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700315static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800316 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700317
318static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800319 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700320
John Recke757b1c2018-06-28 12:24:33 -0700321static const char* k_recordTgidPath =
322 "options/record-tgid";
323
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700324static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800325 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700326
327static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800328 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700329
330static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800331 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700332
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700333static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800334 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700335
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800336static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800337 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800338
339static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800340 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800341
Martijn Coenend9535872015-11-26 10:00:55 +0100342static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800343 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100344
John Reck469a1942015-03-26 15:31:35 -0700345static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800346 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700347
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800348// Check whether a file exists.
349static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800350 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800351}
352
353// Check whether a file is writable.
354static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800355 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800356}
357
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700358// Truncate a file.
359static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800360{
Jamie Gennis43122e72013-03-21 14:06:31 -0700361 // This uses creat rather than truncate because some of the debug kernel
362 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
363 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800364 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700365 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800366 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700367 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700368 return false;
369 }
370
Jamie Gennis43122e72013-03-21 14:06:31 -0700371 close(traceFD);
372
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700373 return true;
374}
375
376static bool _writeStr(const char* filename, const char* str, int flags)
377{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800378 std::string fullFilename = g_traceFolder + filename;
379 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800380 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800381 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800382 strerror(errno), errno);
383 return false;
384 }
385
386 bool ok = true;
387 ssize_t len = strlen(str);
388 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800389 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800390 strerror(errno), errno);
391 ok = false;
392 }
393
394 close(fd);
395
396 return ok;
397}
398
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700399// Write a string to a file, returning true if the write was successful.
400static bool writeStr(const char* filename, const char* str)
401{
402 return _writeStr(filename, str, O_WRONLY);
403}
404
405// Append a string to a file, returning true if the write was successful.
406static bool appendStr(const char* filename, const char* str)
407{
408 return _writeStr(filename, str, O_APPEND|O_WRONLY);
409}
410
John Reck469a1942015-03-26 15:31:35 -0700411static void writeClockSyncMarker()
412{
413 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200414 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800415 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200416 if (fd == -1) {
417 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
418 strerror(errno), errno);
419 return;
420 }
John Reck469a1942015-03-26 15:31:35 -0700421 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200422
423 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
424 if (write(fd, buffer, len) != len) {
425 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
426 }
427
428 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
429 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
430 if (write(fd, buffer, len) != len) {
431 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
432 }
433
434 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700435}
436
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800437// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
438// file.
439static bool setKernelOptionEnable(const char* filename, bool enable)
440{
441 return writeStr(filename, enable ? "1" : "0");
442}
443
444// Check whether the category is supported on the device with the current
445// rootness. A category is supported only if all its required /sys/ files are
446// writable and if enabling the category will enable one or more tracing tags
447// or /sys/ files.
448static bool isCategorySupported(const TracingCategory& category)
449{
sergeyvdb404152016-05-02 19:26:07 -0700450 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700451 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700452 }
453
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800454 bool ok = category.tags != 0;
455 for (int i = 0; i < MAX_SYS_FILES; i++) {
456 const char* path = category.sysfiles[i].path;
457 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700458 if (path != nullptr) {
Carmen Jackson5bbc9a22018-12-06 13:47:18 -0800459 if (fileIsWritable(path)) {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800460 ok = true;
Carmen Jackson5bbc9a22018-12-06 13:47:18 -0800461 } else if (req) {
462 return false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800463 }
464 }
465 }
466 return ok;
467}
468
469// Check whether the category would be supported on the device if the user
470// were root. This function assumes that root is able to write to any file
471// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700472// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800473static bool isCategorySupportedForRoot(const TracingCategory& category)
474{
475 bool ok = category.tags != 0;
476 for (int i = 0; i < MAX_SYS_FILES; i++) {
477 const char* path = category.sysfiles[i].path;
478 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700479 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800480 if (req) {
481 if (!fileExists(path)) {
482 return false;
483 } else {
484 ok = true;
485 }
486 } else {
487 ok |= fileExists(path);
488 }
489 }
490 }
491 return ok;
492}
493
494// Enable or disable overwriting of the kernel trace buffers. Disabling this
495// will cause tracing to stop once the trace buffers have filled up.
496static bool setTraceOverwriteEnable(bool enable)
497{
498 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
499}
500
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700501// Set the user initiated trace property
502static bool setUserInitiatedTraceProperty(bool enable)
503{
504 if (!android::base::SetProperty(k_userInitiatedTraceProperty, enable ? "1" : "")) {
505 fprintf(stderr, "error setting user initiated strace system property\n");
506 return false;
507 }
508 return true;
509}
510
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800511// Enable or disable kernel tracing.
512static bool setTracingEnabled(bool enable)
513{
514 return setKernelOptionEnable(k_tracingOnPath, enable);
515}
516
517// Clear the contents of the kernel trace.
518static bool clearTrace()
519{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700520 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800521}
522
523// Set the size of the kernel's trace buffer in kilobytes.
524static bool setTraceBufferSizeKB(int size)
525{
526 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800527 if (size < 1) {
528 size = 1;
529 }
530 snprintf(str, 32, "%d", size);
531 return writeStr(k_traceBufferSizePath, str);
532}
533
Carmen Jacksonea826792017-05-05 11:42:32 -0700534// Set the clock to the best available option while tracing. Use 'boot' if it's
535// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700536// Any write to the trace_clock sysfs file will reset the buffer, so only
537// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700538static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800539{
Carmen Jacksonea826792017-05-05 11:42:32 -0700540 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
541 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
542 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700543
Carmen Jacksonea826792017-05-05 11:42:32 -0700544 std::string newClock;
545 if (clockStr.find("boot") != std::string::npos) {
546 newClock = "boot";
547 } else if (clockStr.find("mono") != std::string::npos) {
548 newClock = "mono";
549 } else {
550 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700551 }
552
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700553 size_t begin = clockStr.find('[') + 1;
554 size_t end = clockStr.find(']');
Carmen Jacksonea826792017-05-05 11:42:32 -0700555 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
556 return true;
557 }
558 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800559}
560
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700561static bool setPrintTgidEnableIfPresent(bool enable)
562{
John Reckedbf9ec2018-06-29 11:15:17 -0700563 // Pre-4.13 this was options/print-tgid as an android-specific option.
564 // In 4.13+ this is an upstream option called options/record-tgid
565 // Both options produce the same ftrace format change
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700566 if (fileExists(k_printTgidPath)) {
567 return setKernelOptionEnable(k_printTgidPath, enable);
568 }
John Recke757b1c2018-06-28 12:24:33 -0700569 if (fileExists(k_recordTgidPath)) {
570 return setKernelOptionEnable(k_recordTgidPath, enable);
571 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700572 return true;
573}
574
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800575// Set the trace tags that userland tracing uses, and poke the running
576// processes to pick up the new value.
577static bool setTagsProperty(uint64_t tags)
578{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700579 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
580 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800581 fprintf(stderr, "error setting trace tags system property\n");
582 return false;
583 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700584 return true;
585}
586
sergeyv4144eff2016-04-28 11:40:04 -0700587static void clearAppProperties()
588{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700589 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700590 fprintf(stderr, "failed to clear system property: %s",
591 k_traceAppsNumberProperty);
592 }
593}
594
Daniele Di Proietto983c4602024-04-15 18:18:01 +0000595// Set the property that's read by userspace to prefer the perfetto SDK.
596static bool setPreferSdkProperty(uint64_t tags)
597{
598 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
599 if (!android::base::SetProperty(k_tracePreferSdkProperty, value)) {
600 fprintf(stderr, "error setting prefer_sdk system property\n");
601 return false;
602 }
603 return true;
604}
605
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700606// Set the system property that indicates which apps should perform
607// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700608static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700609{
sergeyv4144eff2016-04-28 11:40:04 -0700610 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700611 char* start = cmdline;
Yi Kong19d5c002018-07-20 13:39:55 -0700612 while (start != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700613 char* end = strchr(start, ',');
Yi Kong19d5c002018-07-20 13:39:55 -0700614 if (end != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700615 *end = '\0';
616 end++;
617 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700618 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
619 if (!android::base::SetProperty(key, start)) {
620 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700621 clearAppProperties();
622 return false;
623 }
624 start = end;
625 i++;
626 }
627
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700628 std::string value = android::base::StringPrintf("%d", i);
629 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
630 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700631 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700632 return false;
633 }
634 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800635}
636
637// Disable all /sys/ enable files.
638static bool disableKernelTraceEvents() {
639 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700640 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800641 const TracingCategory &c = k_categories[i];
642 for (int j = 0; j < MAX_SYS_FILES; j++) {
643 const char* path = c.sysfiles[j].path;
Yi Kong19d5c002018-07-20 13:39:55 -0700644 if (path != nullptr && fileIsWritable(path)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800645 ok &= setKernelOptionEnable(path, false);
646 }
647 }
648 }
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +0000649 for (const TracingVendorFileCategory& c : g_vendorFileCategories) {
650 for (const std::string& path : c.ftrace_enable_paths) {
651 if (fileIsWritable(path.c_str())) {
652 ok &= setKernelOptionEnable(path.c_str(), false);
653 }
654 }
655 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800656 return ok;
657}
658
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700659// Verify that the comma separated list of functions are being traced by the
660// kernel.
661static bool verifyKernelTraceFuncs(const char* funcs)
662{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100663 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800664 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100665 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700666 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100667 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700668 }
669
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100670 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700671
672 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100673 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700674 bool ok = true;
675 char* myFuncs = strdup(funcs);
676 char* func = strtok(myFuncs, ",");
677 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100678 if (!strchr(func, '*')) {
679 String8 fancyFunc = String8::format("\n%s\n", func);
Tomasz Wasilczyk95000d02023-08-23 18:40:27 +0000680 bool found = funcList.find(fancyFunc.c_str(), 0) >= 0;
Thomas Buhota2c22872016-01-27 09:44:31 +0100681 if (!found || func[0] == '\0') {
682 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
683 "to trace.\n", func);
684 ok = false;
685 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700686 }
Yi Kong19d5c002018-07-20 13:39:55 -0700687 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700688 }
689 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700690 return ok;
691}
692
693// Set the comma separated list of functions that the kernel is to trace.
694static bool setKernelTraceFuncs(const char* funcs)
695{
696 bool ok = true;
697
Yi Kong19d5c002018-07-20 13:39:55 -0700698 if (funcs == nullptr || funcs[0] == '\0') {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700699 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700700 if (fileIsWritable(k_currentTracerPath)) {
701 ok &= writeStr(k_currentTracerPath, "nop");
702 }
703 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700704 ok &= truncateFile(k_ftraceFilterPath);
705 }
706 } else {
707 // Enable kernel function tracing.
708 ok &= writeStr(k_currentTracerPath, "function_graph");
709 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
710 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
711 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700712
713 // Set the requested filter functions.
714 ok &= truncateFile(k_ftraceFilterPath);
715 char* myFuncs = strdup(funcs);
716 char* func = strtok(myFuncs, ",");
717 while (func) {
718 ok &= appendStr(k_ftraceFilterPath, func);
Yi Kong19d5c002018-07-20 13:39:55 -0700719 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700720 }
721 free(myFuncs);
722
723 // Verify that the set functions are being traced.
724 if (ok) {
725 ok &= verifyKernelTraceFuncs(funcs);
726 }
727 }
728
729 return ok;
730}
731
Wei Wang16a63a42018-09-21 15:47:45 -0700732static bool setCategoryEnable(const char* name)
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900733{
Wei Wang16a63a42018-09-21 15:47:45 -0700734 bool vendor_found = false;
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +0000735 for (auto& c : g_vendorFileCategories) {
736 if (strcmp(name, c.name.c_str()) == 0) {
737 c.enabled = true;
738 vendor_found = true;
739 }
740 }
741 for (auto& c : g_vendorHalCategories) {
Wei Wang16a63a42018-09-21 15:47:45 -0700742 if (strcmp(name, c.name.c_str()) == 0) {
743 c.enabled = true;
744 vendor_found = true;
745 }
746 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700747 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900748 const TracingCategory& c = k_categories[i];
749 if (strcmp(name, c.name) == 0) {
750 if (isCategorySupported(c)) {
Wei Wang16a63a42018-09-21 15:47:45 -0700751 g_categoryEnables[i] = true;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900752 return true;
753 } else {
754 if (isCategorySupportedForRoot(c)) {
755 fprintf(stderr, "error: category \"%s\" requires root "
756 "privileges.\n", name);
757 } else {
758 fprintf(stderr, "error: category \"%s\" is not supported "
759 "on this device.\n", name);
760 }
761 return false;
762 }
763 }
764 }
Wei Wang16a63a42018-09-21 15:47:45 -0700765 if (vendor_found) {
766 return true;
767 }
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900768 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
769 return false;
770}
771
772static bool setCategoriesEnableFromFile(const char* categories_file)
773{
774 if (!categories_file) {
775 return true;
776 }
Yi Kong19d5c002018-07-20 13:39:55 -0700777 Tokenizer* tokenizer = nullptr;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900778 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
779 return false;
780 }
781 bool ok = true;
782 while (!tokenizer->isEol()) {
783 String8 token = tokenizer->nextToken(" ");
Tomasz Wasilczyk8a0e3522023-08-14 18:03:09 +0000784 if (token.empty()) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900785 tokenizer->skipDelimiters(" ");
786 continue;
787 }
Tomasz Wasilczyk95000d02023-08-23 18:40:27 +0000788 ok &= setCategoryEnable(token.c_str());
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900789 }
790 delete tokenizer;
791 return ok;
792}
793
Hector Dearman11845782018-03-08 14:35:44 +0000794static bool setUpUserspaceTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800795{
796 bool ok = true;
797
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800798 // Set up the tags property.
799 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700800 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800801 if (g_categoryEnables[i]) {
802 const TracingCategory &c = k_categories[i];
803 tags |= c.tags;
804 }
805 }
sergeyvdb404152016-05-02 19:26:07 -0700806
807 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700808 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700809 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
810 coreServicesTagEnabled = g_categoryEnables[i];
811 }
812 }
813
814 std::string packageList(g_debugAppCmdLine);
815 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700816 if (!packageList.empty()) {
817 packageList += ",";
818 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700819 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700820 }
Dan Austin09a79872016-05-31 13:27:03 -0700821 ok &= setAppCmdlineProperty(&packageList[0]);
Florian Mayer6263b582019-12-10 13:28:45 +0000822 ok &= setTagsProperty(tags);
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700823
Hector Dearman11845782018-03-08 14:35:44 +0000824 return ok;
825}
826
827static void cleanUpUserspaceTracing()
828{
829 setTagsProperty(0);
830 clearAppProperties();
Hector Dearman11845782018-03-08 14:35:44 +0000831}
832
833
834// Set all the kernel tracing settings to the desired state for this trace
835// capture.
836static bool setUpKernelTracing()
837{
838 bool ok = true;
839
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700840 ok &= setUserInitiatedTraceProperty(true);
841
Hector Dearman11845782018-03-08 14:35:44 +0000842 // Set up the tracing options.
843 ok &= setCategoriesEnableFromFile(g_categoriesFile);
844 ok &= setTraceOverwriteEnable(g_traceOverwrite);
845 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
Hector Dearman11845782018-03-08 14:35:44 +0000846 ok &= setClock();
847 ok &= setPrintTgidEnableIfPresent(true);
848 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
849
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800850 // Disable all the sysfs enables. This is done as a separate loop from
851 // the enables to allow the same enable to exist in multiple categories.
852 ok &= disableKernelTraceEvents();
853
854 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700855 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800856 if (g_categoryEnables[i]) {
857 const TracingCategory &c = k_categories[i];
858 for (int j = 0; j < MAX_SYS_FILES; j++) {
859 const char* path = c.sysfiles[j].path;
860 bool required = c.sysfiles[j].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700861 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800862 if (fileIsWritable(path)) {
863 ok &= setKernelOptionEnable(path, true);
864 } else if (required) {
865 fprintf(stderr, "error writing file %s\n", path);
866 ok = false;
867 }
868 }
869 }
870 }
871 }
872
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +0000873 for (const TracingVendorFileCategory& c : g_vendorFileCategories) {
874 if (c.enabled) {
875 for (const std::string& path : c.ftrace_enable_paths) {
876 if (fileIsWritable(path.c_str())) {
877 ok &= setKernelOptionEnable(path.c_str(), true);
878 }
879 }
880 }
881 }
882
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800883 return ok;
884}
885
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700886// Reset all the kernel tracing settings to their default state.
Hector Dearman11845782018-03-08 14:35:44 +0000887static void cleanUpKernelTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800888{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800889 // Disable all tracing that we're able to.
890 disableKernelTraceEvents();
891
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800892 // Set the options back to their defaults.
893 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700894 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700895 setPrintTgidEnableIfPresent(false);
Yi Kong19d5c002018-07-20 13:39:55 -0700896 setKernelTraceFuncs(nullptr);
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700897 setUserInitiatedTraceProperty(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700898}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800899
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700900// Enable tracing in the kernel.
901static bool startTrace()
902{
903 return setTracingEnabled(true);
904}
905
906// Disable tracing in the kernel.
907static void stopTrace()
908{
909 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800910}
911
Daniele Di Proietto983c4602024-04-15 18:18:01 +0000912static bool preferSdkCategories() {
913 uint64_t tags = 0;
914 for (size_t i = 0; i < arraysize(k_categories); i++) {
915 if (g_categoryEnables[i]) {
916 const TracingCategory& c = k_categories[i];
917 tags |= c.tags;
918 }
919 }
920 return setPreferSdkProperty(tags);
921}
922
Martijn Coenend9535872015-11-26 10:00:55 +0100923// Read data from the tracing pipe and forward to stdout
924static void streamTrace()
925{
926 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800927 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100928 if (traceFD == -1) {
929 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
930 strerror(errno), errno);
931 return;
932 }
933 while (!g_traceAborted) {
934 ssize_t bytes_read = read(traceFD, trace_data, 4096);
935 if (bytes_read > 0) {
936 write(STDOUT_FILENO, trace_data, bytes_read);
937 fflush(stdout);
938 } else {
939 if (!g_traceAborted) {
940 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
941 bytes_read, errno, strerror(errno));
942 }
943 break;
944 }
945 }
946}
947
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800948// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700949static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800950{
John Reck6c8ac922016-03-28 11:25:30 -0700951 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800952 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800953 if (traceFD == -1) {
954 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
955 strerror(errno), errno);
956 return;
957 }
958
959 if (g_compress) {
960 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800961 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700962
963 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800964 if (result != Z_OK) {
965 fprintf(stderr, "error initializing zlib: %d\n", result);
966 close(traceFD);
967 return;
968 }
969
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700970 constexpr size_t bufSize = 64*1024;
971 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
972 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
973 if (!in || !out) {
974 fprintf(stderr, "couldn't allocate buffers\n");
975 close(traceFD);
976 return;
977 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800978
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700979 int flush = Z_NO_FLUSH;
980
981 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800982 zs.avail_out = bufSize;
983
984 do {
985
986 if (zs.avail_in == 0) {
987 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700988 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800989 if (result < 0) {
990 fprintf(stderr, "error reading trace: %s (%d)\n",
991 strerror(errno), errno);
992 result = Z_STREAM_END;
993 break;
994 } else if (result == 0) {
995 flush = Z_FINISH;
996 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700997 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800998 zs.avail_in = result;
999 }
1000 }
1001
1002 if (zs.avail_out == 0) {
1003 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -07001004 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001005 if ((size_t)result < bufSize) {
1006 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1007 strerror(errno), errno);
1008 result = Z_STREAM_END; // skip deflate error message
1009 zs.avail_out = bufSize; // skip the final write
1010 break;
1011 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001012 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001013 zs.avail_out = bufSize;
1014 }
1015
1016 } while ((result = deflate(&zs, flush)) == Z_OK);
1017
1018 if (result != Z_STREAM_END) {
1019 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
1020 }
1021
1022 if (zs.avail_out < bufSize) {
1023 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -07001024 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001025 if ((size_t)result < bytes) {
1026 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1027 strerror(errno), errno);
1028 }
1029 }
1030
1031 result = deflateEnd(&zs);
1032 if (result != Z_OK) {
1033 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1034 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001035 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001036 char buf[4096];
1037 ssize_t rc;
1038 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1039 if (!android::base::WriteFully(outFd, buf, rc)) {
1040 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1041 break;
1042 }
1043 }
1044 if (rc == -1) {
1045 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001046 }
1047 }
1048
1049 close(traceFD);
1050}
1051
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001052static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001053{
1054 if (!g_nohup) {
1055 g_traceAborted = true;
1056 }
1057}
1058
1059static void registerSigHandler()
1060{
1061 struct sigaction sa;
1062 sigemptyset(&sa.sa_mask);
1063 sa.sa_flags = 0;
1064 sa.sa_handler = handleSignal;
Yi Kong19d5c002018-07-20 13:39:55 -07001065 sigaction(SIGHUP, &sa, nullptr);
1066 sigaction(SIGINT, &sa, nullptr);
1067 sigaction(SIGQUIT, &sa, nullptr);
1068 sigaction(SIGTERM, &sa, nullptr);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001069}
1070
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001071static void listSupportedCategories()
1072{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001073 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001074 const TracingCategory& c = k_categories[i];
1075 if (isCategorySupported(c)) {
1076 printf(" %10s - %s\n", c.name, c.longname);
1077 }
1078 }
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +00001079 for (const auto& c : g_vendorFileCategories) {
1080 printf(" %10s - (VENDOR)\n", c.name.c_str());
1081 }
1082 for (const auto& c : g_vendorHalCategories) {
Wei Wang16a63a42018-09-21 15:47:45 -07001083 printf(" %10s - %s (HAL)\n", c.name.c_str(), c.description.c_str());
1084 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001085}
1086
1087// Print the command usage help to stderr.
1088static void showHelp(const char *cmd)
1089{
1090 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1091 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001092 " -a appname enable app-level tracing for a comma "
Daniel Colascione519a0792018-02-09 20:05:39 -08001093 "separated list of cmdlines; * is a wildcard matching any process\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001094 " -b N use a trace buffer size of N KB\n"
1095 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001096 " -f filename use the categories written in a file as space-separated\n"
1097 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001098 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001099 " -n ignore signals\n"
1100 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001101 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001102 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001103 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001104 " --async_dump dump the current contents of circular trace buffer\n"
1105 " --async_stop stop tracing and dump the current contents of circular\n"
1106 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001107 " --stream stream trace to stdout as it enters the trace buffer\n"
1108 " Note: this can take significant CPU time, and is best\n"
1109 " used for measuring things that are not affected by\n"
1110 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001111 " --list_categories\n"
1112 " list the available tracing categories\n"
Daniele Di Proietto983c4602024-04-15 18:18:01 +00001113 " --prefer_sdk\n"
1114 " prefer the perfetto sdk over legacy atrace for\n"
1115 " categories and exits immediately\n"
John Reck40b26b42016-03-30 09:44:36 -07001116 " -o filename write the trace to the specified file instead\n"
1117 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001118 );
1119}
1120
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001121bool findTraceFiles()
1122{
1123 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1124 static const std::string tracefs_path = "/sys/kernel/tracing/";
1125 static const std::string trace_file = "trace_marker";
1126
1127 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1128 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1129
1130 if (!tracefs && !debugfs) {
1131 fprintf(stderr, "Error: Did not find trace folder\n");
1132 return false;
1133 }
1134
1135 if (tracefs) {
1136 g_traceFolder = tracefs_path;
1137 } else {
1138 g_traceFolder = debugfs_path;
1139 }
1140
1141 return true;
1142}
1143
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +00001144void initVendorCategoriesFromFile() {
1145 std::ifstream is(kVendorCategoriesPath);
1146 for (std::string line; std::getline(is, line);) {
1147 if (line.empty()) {
1148 continue;
1149 }
1150 if (android::base::StartsWith(line, ' ') || android::base::StartsWith(line, '\t')) {
1151 if (g_vendorFileCategories.empty()) {
1152 fprintf(stderr, "Malformed vendor categories file\n");
1153 exit(1);
1154 return;
1155 }
1156 std::string_view path = std::string_view(line).substr(1);
1157 while (android::base::StartsWith(path, ' ') || android::base::StartsWith(path, '\t')) {
1158 path.remove_prefix(1);
1159 }
1160 if (path.empty()) {
1161 continue;
1162 }
1163 std::string enable_path = "events/";
1164 enable_path += path;
1165 enable_path += "/enable";
1166 g_vendorFileCategories.back().ftrace_enable_paths.push_back(std::move(enable_path));
1167 } else {
1168 TracingVendorFileCategory cat;
1169 cat.name = line;
1170 g_vendorFileCategories.push_back(std::move(cat));
1171 }
1172 }
1173}
1174
1175void initVendorCategoriesFromHal() {
Wei Wang16a63a42018-09-21 15:47:45 -07001176 g_atraceHal = IAtraceDevice::getService();
1177
1178 if (g_atraceHal == nullptr) {
1179 // No atrace HAL
1180 return;
1181 }
1182
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +00001183 Return<void> ret = g_atraceHal->listCategories([](const auto& list) {
1184 g_vendorHalCategories.reserve(list.size());
1185 for (const auto& category : list) {
1186 g_vendorHalCategories.emplace_back(category.name, category.description, false);
1187 }
1188 });
Wei Wang16a63a42018-09-21 15:47:45 -07001189 if (!ret.isOk()) {
1190 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1191 }
1192}
1193
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +00001194void initVendorCategories() {
1195 // If kVendorCategoriesPath exists on the filesystem, do not use the HAL.
1196 if (access(kVendorCategoriesPath, F_OK) != -1) {
1197 initVendorCategoriesFromFile();
1198 } else {
1199 initVendorCategoriesFromHal();
1200 }
1201}
1202
1203static bool setUpVendorTracingWithHal() {
Wei Wang16a63a42018-09-21 15:47:45 -07001204 if (g_atraceHal == nullptr) {
1205 // No atrace HAL
1206 return true;
1207 }
1208
1209 std::vector<hidl_string> categories;
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +00001210 for (const auto& c : g_vendorHalCategories) {
Wei Wang16a63a42018-09-21 15:47:45 -07001211 if (c.enabled) {
1212 categories.emplace_back(c.name);
1213 }
1214 }
1215
1216 if (!categories.size()) {
1217 return true;
1218 }
1219
1220 auto ret = g_atraceHal->enableCategories(categories);
1221 if (!ret.isOk()) {
1222 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1223 return false;
1224 } else if (ret != Status::SUCCESS) {
1225 fprintf(stderr, "calling atrace HAL failed: %s\n", toString(ret).c_str());
1226 return false;
1227 }
1228 return true;
1229}
1230
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +00001231static bool cleanUpVendorTracingWithHal() {
Wei Wang16a63a42018-09-21 15:47:45 -07001232 if (g_atraceHal == nullptr) {
1233 // No atrace HAL
1234 return true;
1235 }
1236
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +00001237 if (!g_vendorHalCategories.size()) {
1238 // No vendor HAL categories
Wei Wang16a63a42018-09-21 15:47:45 -07001239 return true;
1240 }
1241
1242 auto ret = g_atraceHal->disableAllCategories();
1243 if (!ret.isOk()) {
1244 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1245 return false;
1246 } else if (ret != Status::SUCCESS) {
1247 fprintf(stderr, "calling atrace HAL failed: %s\n", toString(ret).c_str());
1248 return false;
1249 }
1250 return true;
1251}
1252
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001253int main(int argc, char **argv)
1254{
1255 bool async = false;
1256 bool traceStart = true;
1257 bool traceStop = true;
1258 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001259 bool traceStream = false;
Daniele Di Proietto983c4602024-04-15 18:18:01 +00001260 bool preferSdk = false;
Hector Dearman11845782018-03-08 14:35:44 +00001261 bool onlyUserspace = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001262
1263 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1264 showHelp(argv[0]);
1265 exit(0);
1266 }
1267
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001268 if (!findTraceFiles()) {
1269 fprintf(stderr, "No trace folder found\n");
1270 exit(-1);
1271 }
1272
Wei Wang16a63a42018-09-21 15:47:45 -07001273 initVendorCategories();
1274
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001275 for (;;) {
1276 int ret;
1277 int option_index = 0;
1278 static struct option long_options[] = {
Yi Kong19d5c002018-07-20 13:39:55 -07001279 {"async_start", no_argument, nullptr, 0 },
1280 {"async_stop", no_argument, nullptr, 0 },
1281 {"async_dump", no_argument, nullptr, 0 },
1282 {"only_userspace", no_argument, nullptr, 0 },
1283 {"list_categories", no_argument, nullptr, 0 },
1284 {"stream", no_argument, nullptr, 0 },
Daniele Di Proietto983c4602024-04-15 18:18:01 +00001285 {"prefer_sdk", no_argument, nullptr, 0 },
Yi Kong19d5c002018-07-20 13:39:55 -07001286 {nullptr, 0, nullptr, 0 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001287 };
1288
John Reck40b26b42016-03-30 09:44:36 -07001289 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001290 long_options, &option_index);
1291
1292 if (ret < 0) {
1293 for (int i = optind; i < argc; i++) {
Primiano Tucci3a26ff62022-03-15 18:53:46 +00001294 setCategoryEnable(argv[i]);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001295 }
1296 break;
1297 }
1298
1299 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001300 case 'a':
1301 g_debugAppCmdLine = optarg;
1302 break;
1303
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001304 case 'b':
1305 g_traceBufferSizeKB = atoi(optarg);
1306 break;
1307
1308 case 'c':
1309 g_traceOverwrite = true;
1310 break;
1311
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001312 case 'f':
1313 g_categoriesFile = optarg;
1314 break;
1315
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001316 case 'k':
1317 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001318 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001319
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001320 case 'n':
1321 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001322 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001323
1324 case 's':
1325 g_initialSleepSecs = atoi(optarg);
1326 break;
1327
1328 case 't':
1329 g_traceDurationSeconds = atoi(optarg);
1330 break;
1331
1332 case 'z':
1333 g_compress = true;
1334 break;
1335
John Reck40b26b42016-03-30 09:44:36 -07001336 case 'o':
1337 g_outputFile = optarg;
1338 break;
1339
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001340 case 0:
1341 if (!strcmp(long_options[option_index].name, "async_start")) {
1342 async = true;
1343 traceStop = false;
1344 traceDump = false;
1345 g_traceOverwrite = true;
1346 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1347 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001348 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001349 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1350 async = true;
1351 traceStart = false;
1352 traceStop = false;
Hector Dearman11845782018-03-08 14:35:44 +00001353 } else if (!strcmp(long_options[option_index].name, "only_userspace")) {
1354 onlyUserspace = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001355 } else if (!strcmp(long_options[option_index].name, "stream")) {
1356 traceStream = true;
1357 traceDump = false;
Daniele Di Proietto983c4602024-04-15 18:18:01 +00001358 } else if (!strcmp(long_options[option_index].name, "prefer_sdk")) {
1359 preferSdk = true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001360 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1361 listSupportedCategories();
1362 exit(0);
1363 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001364 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001365
1366 default:
1367 fprintf(stderr, "\n");
1368 showHelp(argv[0]);
1369 exit(-1);
1370 break;
1371 }
1372 }
1373
Daniele Di Proietto983c4602024-04-15 18:18:01 +00001374 if (preferSdk) {
1375 bool res = preferSdkCategories();
1376 exit(res ? 0 : 1);
1377 }
1378
Hector Dearman11845782018-03-08 14:35:44 +00001379 if (onlyUserspace) {
1380 if (!async || !(traceStart || traceStop)) {
1381 fprintf(stderr, "--only_userspace can only be used with "
1382 "--async_start or --async_stop\n");
1383 exit(1);
1384 }
1385 }
1386
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001387 registerSigHandler();
1388
1389 if (g_initialSleepSecs > 0) {
1390 sleep(g_initialSleepSecs);
1391 }
1392
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001393 bool ok = true;
Hector Dearman11845782018-03-08 14:35:44 +00001394
Wei Wang5b73b742018-03-08 13:33:12 -08001395 if (traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001396 ok &= setUpUserspaceTracing();
1397 }
1398
1399 if (ok && traceStart && !onlyUserspace) {
1400 ok &= setUpKernelTracing();
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +00001401 ok &= setUpVendorTracingWithHal();
Wei Wang5b73b742018-03-08 13:33:12 -08001402 ok &= startTrace();
1403 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001404
1405 if (ok && traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001406
1407 if (!traceStream && !onlyUserspace) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001408 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001409 fflush(stdout);
1410 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001411
1412 // We clear the trace after starting it because tracing gets enabled for
1413 // each CPU individually in the kernel. Having the beginning of the trace
1414 // contain entries from only one CPU can cause "begin" entries without a
1415 // matching "end" entry to show up if a task gets migrated from one CPU to
1416 // another.
Primiano Tucci929325d2022-03-15 20:26:21 +00001417 if (!onlyUserspace) {
Hector Dearman11845782018-03-08 14:35:44 +00001418 ok = clearTrace();
Primiano Tucci929325d2022-03-15 20:26:21 +00001419 writeClockSyncMarker();
1420 }
Martijn Coenend9535872015-11-26 10:00:55 +01001421 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001422 // Sleep to allow the trace to be captured.
1423 struct timespec timeLeft;
1424 timeLeft.tv_sec = g_traceDurationSeconds;
1425 timeLeft.tv_nsec = 0;
1426 do {
1427 if (g_traceAborted) {
1428 break;
1429 }
1430 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1431 }
Martijn Coenend9535872015-11-26 10:00:55 +01001432
1433 if (traceStream) {
1434 streamTrace();
1435 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001436 }
1437
1438 // Stop the trace and restore the default settings.
Hector Dearman11845782018-03-08 14:35:44 +00001439 if (traceStop && !onlyUserspace)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001440 stopTrace();
1441
Hector Dearman11845782018-03-08 14:35:44 +00001442 if (ok && traceDump && !onlyUserspace) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001443 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001444 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001445 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001446 int outFd = STDOUT_FILENO;
1447 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001448 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001449 }
1450 if (outFd == -1) {
1451 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1452 } else {
1453 dprintf(outFd, "TRACE:\n");
1454 dumpTrace(outFd);
1455 if (g_outputFile) {
1456 close(outFd);
1457 }
1458 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001459 } else {
1460 printf("\ntrace aborted.\n");
1461 fflush(stdout);
1462 }
1463 clearTrace();
1464 } else if (!ok) {
1465 fprintf(stderr, "unable to start tracing\n");
1466 }
1467
1468 // Reset the trace buffer size to 1.
Hector Dearman11845782018-03-08 14:35:44 +00001469 if (traceStop) {
1470 cleanUpUserspaceTracing();
Hector Dearmanada0a4a2019-04-09 14:13:14 +01001471 if (!onlyUserspace) {
Daniele Di Proietto2e9166e2022-09-15 17:04:11 +00001472 cleanUpVendorTracingWithHal();
Hector Dearman11845782018-03-08 14:35:44 +00001473 cleanUpKernelTracing();
Hector Dearmanada0a4a2019-04-09 14:13:14 +01001474 }
Hector Dearman11845782018-03-08 14:35:44 +00001475 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001476
1477 return g_traceAborted ? 1 : 0;
1478}