blob: 46859a2ace485061bbc6dd6a04cafa0d50e29562 [file] [log] [blame]
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Paul Lawrence2cd93cc2017-01-17 09:50:18 -080017#define LOG_TAG "atrace"
John Reck40b26b42016-03-30 09:44:36 -070018
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080019#include <errno.h>
20#include <fcntl.h>
21#include <getopt.h>
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070022#include <inttypes.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080023#include <signal.h>
24#include <stdarg.h>
25#include <stdbool.h>
26#include <stdio.h>
27#include <stdlib.h>
Elliott Hughes3da5d232015-01-25 08:35:20 -080028#include <string.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080029#include <time.h>
Martijn Coenend9535872015-11-26 10:00:55 +010030#include <unistd.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080031#include <zlib.h>
32
Carmen Jacksonea826792017-05-05 11:42:32 -070033#include <fstream>
Elliott Hughesa252f4d2016-07-21 17:12:15 -070034#include <memory>
35
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080036#include <binder/IBinder.h>
37#include <binder/IServiceManager.h>
38#include <binder/Parcel.h>
39
Wei Wang16a63a42018-09-21 15:47:45 -070040#include <android/hardware/atrace/1.0/IAtraceDevice.h>
Martijn Coenenee9b97e2016-11-16 16:00:26 +010041#include <android/hidl/manager/1.0/IServiceManager.h>
42#include <hidl/ServiceManagement.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080043
Corey Tabakaa6c0a722017-05-31 16:37:40 -070044#include <pdx/default_transport/service_utility.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080045#include <utils/String8.h>
John Reck469a1942015-03-26 15:31:35 -070046#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +090047#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080048#include <utils/Trace.h>
Stephane Gasparinid8419c22016-03-02 13:45:15 +010049#include <android-base/file.h>
Elliott Hughes5fd6ff62017-03-28 14:55:31 -070050#include <android-base/macros.h>
51#include <android-base/properties.h>
52#include <android-base/stringprintf.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080053
54using namespace android;
Corey Tabakaa6c0a722017-05-31 16:37:40 -070055using pdx::default_transport::ServiceUtility;
Wei Wang16a63a42018-09-21 15:47:45 -070056using hardware::hidl_vec;
57using hardware::hidl_string;
58using hardware::Return;
59using hardware::atrace::V1_0::IAtraceDevice;
60using hardware::atrace::V1_0::Status;
61using hardware::atrace::V1_0::toString;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080062
Martijn Coenenee9b97e2016-11-16 16:00:26 +010063using std::string;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080064
Daeho Jeonga91385b2022-12-05 14:11:10 -080065#define MAX_SYS_FILES 13
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080066
67const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
Carmen Jackson65ecfbb2018-05-22 10:29:47 -070068const char* k_userInitiatedTraceProperty = "debug.atrace.user_initiated";
sergeyv4144eff2016-04-28 11:40:04 -070069
70const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
71const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070072const char* k_coreServiceCategory = "core_services";
Corey Tabakaa6c0a722017-05-31 16:37:40 -070073const char* k_pdxServiceCategory = "pdx";
sergeyvdb404152016-05-02 19:26:07 -070074const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080075
76typedef enum { OPT, REQ } requiredness ;
77
78struct TracingCategory {
79 // The name identifying the category.
80 const char* name;
81
82 // A longer description of the category.
83 const char* longname;
84
85 // The userland tracing tags that the category enables.
86 uint64_t tags;
87
88 // The fname==NULL terminated list of /sys/ files that the category
89 // enables.
90 struct {
91 // Whether the file must be writable in order to enable the tracing
92 // category.
93 requiredness required;
94
95 // The path to the enable file.
96 const char* path;
97 } sysfiles[MAX_SYS_FILES];
98};
99
100/* Tracing categories */
101static const TracingCategory k_categories[] = {
Yiwei Zhang63775062020-09-18 11:42:33 -0700102 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, {
103 { OPT, "events/gpu_mem/gpu_mem_total/enable" },
104 } },
MÃ¥rten Kongstad2d4f89b2018-12-03 12:58:56 +0100105 { "input", "Input", ATRACE_TAG_INPUT, { } },
106 { "view", "View System", ATRACE_TAG_VIEW, { } },
107 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
108 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
109 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
110 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
111 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
112 { "video", "Video", ATRACE_TAG_VIDEO, { } },
113 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
114 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
115 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
116 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
117 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
118 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
119 { "power", "Power Management", ATRACE_TAG_POWER, { } },
120 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
121 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
122 { "database", "Database", ATRACE_TAG_DATABASE, { } },
123 { "network", "Network", ATRACE_TAG_NETWORK, { } },
124 { "adb", "ADB", ATRACE_TAG_ADB, { } },
125 { "vibrator", "Vibrator", ATRACE_TAG_VIBRATOR, { } },
126 { "aidl", "AIDL calls", ATRACE_TAG_AIDL, { } },
127 { "nnapi", "NNAPI", ATRACE_TAG_NNAPI, { } },
128 { "rro", "Runtime Resource Overlay", ATRACE_TAG_RRO, { } },
sergeyvdb404152016-05-02 19:26:07 -0700129 { k_coreServiceCategory, "Core services", 0, { } },
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700130 { k_pdxServiceCategory, "PDX 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
Wei Wang16a63a42018-09-21 15:47:45 -0700258struct TracingVendorCategory {
259 // The name identifying the category.
260 std::string name;
261
262 // A longer description of the category.
263 std::string description;
264
265 // If the category is enabled through command.
266 bool enabled;
267
268 TracingVendorCategory(string &&name, string &&description, bool enabled)
269 : name(std::move(name))
270 , description(std::move(description))
271 , enabled(enabled)
272 {}
273};
274
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800275/* Command line options */
276static int g_traceDurationSeconds = 5;
277static bool g_traceOverwrite = false;
278static int g_traceBufferSizeKB = 2048;
279static bool g_compress = false;
280static bool g_nohup = false;
281static int g_initialSleepSecs = 0;
Yi Kong19d5c002018-07-20 13:39:55 -0700282static const char* g_categoriesFile = nullptr;
283static const char* g_kernelTraceFuncs = nullptr;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700284static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700285static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800286
287/* Global state */
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700288static bool g_tracePdx = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800289static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700290static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800291static std::string g_traceFolder;
Wei Wang16a63a42018-09-21 15:47:45 -0700292static sp<IAtraceDevice> g_atraceHal;
293static std::vector<TracingVendorCategory> g_vendorCategories;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800294
295/* Sys file paths */
296static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800297 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800298
299static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800300 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800301
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700302#if 0
303// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700304static const char* k_traceCmdlineSizePath =
305 "saved_cmdlines_size";
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700306#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700307
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800308static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800309 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800310
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700311static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800312 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700313
314static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800315 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700316
John Recke757b1c2018-06-28 12:24:33 -0700317static const char* k_recordTgidPath =
318 "options/record-tgid";
319
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700320static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800321 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700322
323static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800324 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700325
326static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800327 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700328
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700329static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800330 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700331
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800332static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800333 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800334
335static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800336 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800337
Martijn Coenend9535872015-11-26 10:00:55 +0100338static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800339 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100340
John Reck469a1942015-03-26 15:31:35 -0700341static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800342 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700343
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800344// Check whether a file exists.
345static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800346 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800347}
348
349// Check whether a file is writable.
350static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800351 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800352}
353
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700354// Truncate a file.
355static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800356{
Jamie Gennis43122e72013-03-21 14:06:31 -0700357 // This uses creat rather than truncate because some of the debug kernel
358 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
359 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800360 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700361 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800362 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700363 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700364 return false;
365 }
366
Jamie Gennis43122e72013-03-21 14:06:31 -0700367 close(traceFD);
368
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700369 return true;
370}
371
372static bool _writeStr(const char* filename, const char* str, int flags)
373{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800374 std::string fullFilename = g_traceFolder + filename;
375 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800376 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800377 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800378 strerror(errno), errno);
379 return false;
380 }
381
382 bool ok = true;
383 ssize_t len = strlen(str);
384 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800385 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800386 strerror(errno), errno);
387 ok = false;
388 }
389
390 close(fd);
391
392 return ok;
393}
394
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700395// Write a string to a file, returning true if the write was successful.
396static bool writeStr(const char* filename, const char* str)
397{
398 return _writeStr(filename, str, O_WRONLY);
399}
400
401// Append a string to a file, returning true if the write was successful.
402static bool appendStr(const char* filename, const char* str)
403{
404 return _writeStr(filename, str, O_APPEND|O_WRONLY);
405}
406
John Reck469a1942015-03-26 15:31:35 -0700407static void writeClockSyncMarker()
408{
409 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200410 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800411 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200412 if (fd == -1) {
413 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
414 strerror(errno), errno);
415 return;
416 }
John Reck469a1942015-03-26 15:31:35 -0700417 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200418
419 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
420 if (write(fd, buffer, len) != len) {
421 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
422 }
423
424 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
425 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
426 if (write(fd, buffer, len) != len) {
427 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
428 }
429
430 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700431}
432
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800433// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
434// file.
435static bool setKernelOptionEnable(const char* filename, bool enable)
436{
437 return writeStr(filename, enable ? "1" : "0");
438}
439
440// Check whether the category is supported on the device with the current
441// rootness. A category is supported only if all its required /sys/ files are
442// writable and if enabling the category will enable one or more tracing tags
443// or /sys/ files.
444static bool isCategorySupported(const TracingCategory& category)
445{
sergeyvdb404152016-05-02 19:26:07 -0700446 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700447 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700448 }
449
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700450 if (strcmp(category.name, k_pdxServiceCategory) == 0) {
451 return true;
452 }
453
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800454 bool ok = category.tags != 0;
455 for (int i = 0; i < MAX_SYS_FILES; i++) {
456 const char* path = category.sysfiles[i].path;
457 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700458 if (path != nullptr) {
Carmen Jackson5bbc9a22018-12-06 13:47:18 -0800459 if (fileIsWritable(path)) {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800460 ok = true;
Carmen Jackson5bbc9a22018-12-06 13:47:18 -0800461 } else if (req) {
462 return false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800463 }
464 }
465 }
466 return ok;
467}
468
469// Check whether the category would be supported on the device if the user
470// were root. This function assumes that root is able to write to any file
471// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700472// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800473static bool isCategorySupportedForRoot(const TracingCategory& category)
474{
475 bool ok = category.tags != 0;
476 for (int i = 0; i < MAX_SYS_FILES; i++) {
477 const char* path = category.sysfiles[i].path;
478 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700479 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800480 if (req) {
481 if (!fileExists(path)) {
482 return false;
483 } else {
484 ok = true;
485 }
486 } else {
487 ok |= fileExists(path);
488 }
489 }
490 }
491 return ok;
492}
493
494// Enable or disable overwriting of the kernel trace buffers. Disabling this
495// will cause tracing to stop once the trace buffers have filled up.
496static bool setTraceOverwriteEnable(bool enable)
497{
498 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
499}
500
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700501// Set the user initiated trace property
502static bool setUserInitiatedTraceProperty(bool enable)
503{
504 if (!android::base::SetProperty(k_userInitiatedTraceProperty, enable ? "1" : "")) {
505 fprintf(stderr, "error setting user initiated strace system property\n");
506 return false;
507 }
508 return true;
509}
510
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800511// Enable or disable kernel tracing.
512static bool setTracingEnabled(bool enable)
513{
514 return setKernelOptionEnable(k_tracingOnPath, enable);
515}
516
517// Clear the contents of the kernel trace.
518static bool clearTrace()
519{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700520 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800521}
522
523// Set the size of the kernel's trace buffer in kilobytes.
524static bool setTraceBufferSizeKB(int size)
525{
526 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800527 if (size < 1) {
528 size = 1;
529 }
530 snprintf(str, 32, "%d", size);
531 return writeStr(k_traceBufferSizePath, str);
532}
533
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700534#if 0
535// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700536// Set the default size of cmdline hashtable
537static bool setCmdlineSize()
538{
Joel Fernandesce964f22017-06-06 12:20:29 -0700539 if (fileExists(k_traceCmdlineSizePath)) {
540 return writeStr(k_traceCmdlineSizePath, "8192");
541 }
542 return true;
Joel Fernandesed80bd02017-06-02 10:19:28 -0700543}
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700544#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700545
Carmen Jacksonea826792017-05-05 11:42:32 -0700546// Set the clock to the best available option while tracing. Use 'boot' if it's
547// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700548// Any write to the trace_clock sysfs file will reset the buffer, so only
549// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700550static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800551{
Carmen Jacksonea826792017-05-05 11:42:32 -0700552 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
553 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
554 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700555
Carmen Jacksonea826792017-05-05 11:42:32 -0700556 std::string newClock;
557 if (clockStr.find("boot") != std::string::npos) {
558 newClock = "boot";
559 } else if (clockStr.find("mono") != std::string::npos) {
560 newClock = "mono";
561 } else {
562 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700563 }
564
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700565 size_t begin = clockStr.find('[') + 1;
566 size_t end = clockStr.find(']');
Carmen Jacksonea826792017-05-05 11:42:32 -0700567 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
568 return true;
569 }
570 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800571}
572
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700573static bool setPrintTgidEnableIfPresent(bool enable)
574{
John Reckedbf9ec2018-06-29 11:15:17 -0700575 // Pre-4.13 this was options/print-tgid as an android-specific option.
576 // In 4.13+ this is an upstream option called options/record-tgid
577 // Both options produce the same ftrace format change
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700578 if (fileExists(k_printTgidPath)) {
579 return setKernelOptionEnable(k_printTgidPath, enable);
580 }
John Recke757b1c2018-06-28 12:24:33 -0700581 if (fileExists(k_recordTgidPath)) {
582 return setKernelOptionEnable(k_recordTgidPath, enable);
583 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700584 return true;
585}
586
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800587// Set the trace tags that userland tracing uses, and poke the running
588// processes to pick up the new value.
589static bool setTagsProperty(uint64_t tags)
590{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700591 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
592 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800593 fprintf(stderr, "error setting trace tags system property\n");
594 return false;
595 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700596 return true;
597}
598
sergeyv4144eff2016-04-28 11:40:04 -0700599static void clearAppProperties()
600{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700601 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700602 fprintf(stderr, "failed to clear system property: %s",
603 k_traceAppsNumberProperty);
604 }
605}
606
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700607// Set the system property that indicates which apps should perform
608// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700609static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700610{
sergeyv4144eff2016-04-28 11:40:04 -0700611 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700612 char* start = cmdline;
Yi Kong19d5c002018-07-20 13:39:55 -0700613 while (start != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700614 char* end = strchr(start, ',');
Yi Kong19d5c002018-07-20 13:39:55 -0700615 if (end != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700616 *end = '\0';
617 end++;
618 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700619 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
620 if (!android::base::SetProperty(key, start)) {
621 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700622 clearAppProperties();
623 return false;
624 }
625 start = end;
626 i++;
627 }
628
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700629 std::string value = android::base::StringPrintf("%d", i);
630 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
631 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700632 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700633 return false;
634 }
635 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800636}
637
638// Disable all /sys/ enable files.
639static bool disableKernelTraceEvents() {
640 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700641 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800642 const TracingCategory &c = k_categories[i];
643 for (int j = 0; j < MAX_SYS_FILES; j++) {
644 const char* path = c.sysfiles[j].path;
Yi Kong19d5c002018-07-20 13:39:55 -0700645 if (path != nullptr && fileIsWritable(path)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800646 ok &= setKernelOptionEnable(path, false);
647 }
648 }
649 }
650 return ok;
651}
652
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700653// Verify that the comma separated list of functions are being traced by the
654// kernel.
655static bool verifyKernelTraceFuncs(const char* funcs)
656{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100657 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800658 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100659 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700660 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100661 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700662 }
663
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100664 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700665
666 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100667 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700668 bool ok = true;
669 char* myFuncs = strdup(funcs);
670 char* func = strtok(myFuncs, ",");
671 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100672 if (!strchr(func, '*')) {
673 String8 fancyFunc = String8::format("\n%s\n", func);
674 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
675 if (!found || func[0] == '\0') {
676 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
677 "to trace.\n", func);
678 ok = false;
679 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700680 }
Yi Kong19d5c002018-07-20 13:39:55 -0700681 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700682 }
683 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700684 return ok;
685}
686
687// Set the comma separated list of functions that the kernel is to trace.
688static bool setKernelTraceFuncs(const char* funcs)
689{
690 bool ok = true;
691
Yi Kong19d5c002018-07-20 13:39:55 -0700692 if (funcs == nullptr || funcs[0] == '\0') {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700693 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700694 if (fileIsWritable(k_currentTracerPath)) {
695 ok &= writeStr(k_currentTracerPath, "nop");
696 }
697 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700698 ok &= truncateFile(k_ftraceFilterPath);
699 }
700 } else {
701 // Enable kernel function tracing.
702 ok &= writeStr(k_currentTracerPath, "function_graph");
703 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
704 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
705 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700706
707 // Set the requested filter functions.
708 ok &= truncateFile(k_ftraceFilterPath);
709 char* myFuncs = strdup(funcs);
710 char* func = strtok(myFuncs, ",");
711 while (func) {
712 ok &= appendStr(k_ftraceFilterPath, func);
Yi Kong19d5c002018-07-20 13:39:55 -0700713 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700714 }
715 free(myFuncs);
716
717 // Verify that the set functions are being traced.
718 if (ok) {
719 ok &= verifyKernelTraceFuncs(funcs);
720 }
721 }
722
723 return ok;
724}
725
Wei Wang16a63a42018-09-21 15:47:45 -0700726static bool setCategoryEnable(const char* name)
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900727{
Wei Wang16a63a42018-09-21 15:47:45 -0700728 bool vendor_found = false;
729 for (auto &c : g_vendorCategories) {
730 if (strcmp(name, c.name.c_str()) == 0) {
731 c.enabled = true;
732 vendor_found = true;
733 }
734 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700735 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900736 const TracingCategory& c = k_categories[i];
737 if (strcmp(name, c.name) == 0) {
738 if (isCategorySupported(c)) {
Wei Wang16a63a42018-09-21 15:47:45 -0700739 g_categoryEnables[i] = true;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900740 return true;
741 } else {
742 if (isCategorySupportedForRoot(c)) {
743 fprintf(stderr, "error: category \"%s\" requires root "
744 "privileges.\n", name);
745 } else {
746 fprintf(stderr, "error: category \"%s\" is not supported "
747 "on this device.\n", name);
748 }
749 return false;
750 }
751 }
752 }
Wei Wang16a63a42018-09-21 15:47:45 -0700753 if (vendor_found) {
754 return true;
755 }
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900756 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
757 return false;
758}
759
760static bool setCategoriesEnableFromFile(const char* categories_file)
761{
762 if (!categories_file) {
763 return true;
764 }
Yi Kong19d5c002018-07-20 13:39:55 -0700765 Tokenizer* tokenizer = nullptr;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900766 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
767 return false;
768 }
769 bool ok = true;
770 while (!tokenizer->isEol()) {
771 String8 token = tokenizer->nextToken(" ");
772 if (token.isEmpty()) {
773 tokenizer->skipDelimiters(" ");
774 continue;
775 }
Wei Wang16a63a42018-09-21 15:47:45 -0700776 ok &= setCategoryEnable(token.string());
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900777 }
778 delete tokenizer;
779 return ok;
780}
781
Hector Dearman11845782018-03-08 14:35:44 +0000782static bool setUpUserspaceTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800783{
784 bool ok = true;
785
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800786 // Set up the tags property.
787 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700788 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800789 if (g_categoryEnables[i]) {
790 const TracingCategory &c = k_categories[i];
791 tags |= c.tags;
792 }
793 }
sergeyvdb404152016-05-02 19:26:07 -0700794
795 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700796 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700797 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
798 coreServicesTagEnabled = g_categoryEnables[i];
799 }
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700800
801 // Set whether to poke PDX services in this session.
802 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
803 g_tracePdx = g_categoryEnables[i];
804 }
sergeyvdb404152016-05-02 19:26:07 -0700805 }
806
807 std::string packageList(g_debugAppCmdLine);
808 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700809 if (!packageList.empty()) {
810 packageList += ",";
811 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700812 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700813 }
Dan Austin09a79872016-05-31 13:27:03 -0700814 ok &= setAppCmdlineProperty(&packageList[0]);
Florian Mayer6263b582019-12-10 13:28:45 +0000815 ok &= setTagsProperty(tags);
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700816 if (g_tracePdx) {
817 ok &= ServiceUtility::PokeServices();
818 }
819
Hector Dearman11845782018-03-08 14:35:44 +0000820 return ok;
821}
822
823static void cleanUpUserspaceTracing()
824{
825 setTagsProperty(0);
826 clearAppProperties();
Hector Dearman11845782018-03-08 14:35:44 +0000827
828 if (g_tracePdx) {
829 ServiceUtility::PokeServices();
830 }
831}
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);
846 // TODO: Re-enable after stabilization
847 //ok &= setCmdlineSize();
848 ok &= setClock();
849 ok &= setPrintTgidEnableIfPresent(true);
850 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
851
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800852 // Disable all the sysfs enables. This is done as a separate loop from
853 // the enables to allow the same enable to exist in multiple categories.
854 ok &= disableKernelTraceEvents();
855
856 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700857 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800858 if (g_categoryEnables[i]) {
859 const TracingCategory &c = k_categories[i];
860 for (int j = 0; j < MAX_SYS_FILES; j++) {
861 const char* path = c.sysfiles[j].path;
862 bool required = c.sysfiles[j].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700863 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800864 if (fileIsWritable(path)) {
865 ok &= setKernelOptionEnable(path, true);
866 } else if (required) {
867 fprintf(stderr, "error writing file %s\n", path);
868 ok = false;
869 }
870 }
871 }
872 }
873 }
874
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800875 return ok;
876}
877
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700878// Reset all the kernel tracing settings to their default state.
Hector Dearman11845782018-03-08 14:35:44 +0000879static void cleanUpKernelTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800880{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800881 // Disable all tracing that we're able to.
882 disableKernelTraceEvents();
883
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800884 // Set the options back to their defaults.
885 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700886 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700887 setPrintTgidEnableIfPresent(false);
Yi Kong19d5c002018-07-20 13:39:55 -0700888 setKernelTraceFuncs(nullptr);
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700889 setUserInitiatedTraceProperty(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700890}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800891
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700892// Enable tracing in the kernel.
893static bool startTrace()
894{
895 return setTracingEnabled(true);
896}
897
898// Disable tracing in the kernel.
899static void stopTrace()
900{
901 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800902}
903
Martijn Coenend9535872015-11-26 10:00:55 +0100904// Read data from the tracing pipe and forward to stdout
905static void streamTrace()
906{
907 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800908 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100909 if (traceFD == -1) {
910 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
911 strerror(errno), errno);
912 return;
913 }
914 while (!g_traceAborted) {
915 ssize_t bytes_read = read(traceFD, trace_data, 4096);
916 if (bytes_read > 0) {
917 write(STDOUT_FILENO, trace_data, bytes_read);
918 fflush(stdout);
919 } else {
920 if (!g_traceAborted) {
921 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
922 bytes_read, errno, strerror(errno));
923 }
924 break;
925 }
926 }
927}
928
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800929// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700930static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800931{
John Reck6c8ac922016-03-28 11:25:30 -0700932 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800933 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800934 if (traceFD == -1) {
935 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
936 strerror(errno), errno);
937 return;
938 }
939
940 if (g_compress) {
941 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800942 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700943
944 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800945 if (result != Z_OK) {
946 fprintf(stderr, "error initializing zlib: %d\n", result);
947 close(traceFD);
948 return;
949 }
950
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700951 constexpr size_t bufSize = 64*1024;
952 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
953 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
954 if (!in || !out) {
955 fprintf(stderr, "couldn't allocate buffers\n");
956 close(traceFD);
957 return;
958 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800959
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700960 int flush = Z_NO_FLUSH;
961
962 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800963 zs.avail_out = bufSize;
964
965 do {
966
967 if (zs.avail_in == 0) {
968 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700969 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800970 if (result < 0) {
971 fprintf(stderr, "error reading trace: %s (%d)\n",
972 strerror(errno), errno);
973 result = Z_STREAM_END;
974 break;
975 } else if (result == 0) {
976 flush = Z_FINISH;
977 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700978 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800979 zs.avail_in = result;
980 }
981 }
982
983 if (zs.avail_out == 0) {
984 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700985 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800986 if ((size_t)result < bufSize) {
987 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
988 strerror(errno), errno);
989 result = Z_STREAM_END; // skip deflate error message
990 zs.avail_out = bufSize; // skip the final write
991 break;
992 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700993 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800994 zs.avail_out = bufSize;
995 }
996
997 } while ((result = deflate(&zs, flush)) == Z_OK);
998
999 if (result != Z_STREAM_END) {
1000 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
1001 }
1002
1003 if (zs.avail_out < bufSize) {
1004 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -07001005 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001006 if ((size_t)result < bytes) {
1007 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1008 strerror(errno), errno);
1009 }
1010 }
1011
1012 result = deflateEnd(&zs);
1013 if (result != Z_OK) {
1014 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1015 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001016 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001017 char buf[4096];
1018 ssize_t rc;
1019 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1020 if (!android::base::WriteFully(outFd, buf, rc)) {
1021 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1022 break;
1023 }
1024 }
1025 if (rc == -1) {
1026 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001027 }
1028 }
1029
1030 close(traceFD);
1031}
1032
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001033static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001034{
1035 if (!g_nohup) {
1036 g_traceAborted = true;
1037 }
1038}
1039
1040static void registerSigHandler()
1041{
1042 struct sigaction sa;
1043 sigemptyset(&sa.sa_mask);
1044 sa.sa_flags = 0;
1045 sa.sa_handler = handleSignal;
Yi Kong19d5c002018-07-20 13:39:55 -07001046 sigaction(SIGHUP, &sa, nullptr);
1047 sigaction(SIGINT, &sa, nullptr);
1048 sigaction(SIGQUIT, &sa, nullptr);
1049 sigaction(SIGTERM, &sa, nullptr);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001050}
1051
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001052static void listSupportedCategories()
1053{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001054 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001055 const TracingCategory& c = k_categories[i];
1056 if (isCategorySupported(c)) {
1057 printf(" %10s - %s\n", c.name, c.longname);
1058 }
1059 }
Wei Wang16a63a42018-09-21 15:47:45 -07001060 for (const auto &c : g_vendorCategories) {
1061 printf(" %10s - %s (HAL)\n", c.name.c_str(), c.description.c_str());
1062 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001063}
1064
1065// Print the command usage help to stderr.
1066static void showHelp(const char *cmd)
1067{
1068 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1069 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001070 " -a appname enable app-level tracing for a comma "
Daniel Colascione519a0792018-02-09 20:05:39 -08001071 "separated list of cmdlines; * is a wildcard matching any process\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001072 " -b N use a trace buffer size of N KB\n"
1073 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001074 " -f filename use the categories written in a file as space-separated\n"
1075 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001076 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001077 " -n ignore signals\n"
1078 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001079 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001080 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001081 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001082 " --async_dump dump the current contents of circular trace buffer\n"
1083 " --async_stop stop tracing and dump the current contents of circular\n"
1084 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001085 " --stream stream trace to stdout as it enters the trace buffer\n"
1086 " Note: this can take significant CPU time, and is best\n"
1087 " used for measuring things that are not affected by\n"
1088 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001089 " --list_categories\n"
1090 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001091 " -o filename write the trace to the specified file instead\n"
1092 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001093 );
1094}
1095
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001096bool findTraceFiles()
1097{
1098 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1099 static const std::string tracefs_path = "/sys/kernel/tracing/";
1100 static const std::string trace_file = "trace_marker";
1101
1102 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1103 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1104
1105 if (!tracefs && !debugfs) {
1106 fprintf(stderr, "Error: Did not find trace folder\n");
1107 return false;
1108 }
1109
1110 if (tracefs) {
1111 g_traceFolder = tracefs_path;
1112 } else {
1113 g_traceFolder = debugfs_path;
1114 }
1115
1116 return true;
1117}
1118
Wei Wang16a63a42018-09-21 15:47:45 -07001119void initVendorCategories()
1120{
1121 g_atraceHal = IAtraceDevice::getService();
1122
1123 if (g_atraceHal == nullptr) {
1124 // No atrace HAL
1125 return;
1126 }
1127
1128 Return<void> ret = g_atraceHal->listCategories(
1129 [](const auto& list) {
1130 g_vendorCategories.reserve(list.size());
1131 for (const auto& category : list) {
1132 g_vendorCategories.emplace_back(category.name, category.description, false);
1133 }
1134 });
1135 if (!ret.isOk()) {
1136 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1137 }
1138}
1139
1140static bool setUpVendorTracing()
1141{
1142 if (g_atraceHal == nullptr) {
1143 // No atrace HAL
1144 return true;
1145 }
1146
1147 std::vector<hidl_string> categories;
1148 for (const auto &c : g_vendorCategories) {
1149 if (c.enabled) {
1150 categories.emplace_back(c.name);
1151 }
1152 }
1153
1154 if (!categories.size()) {
1155 return true;
1156 }
1157
1158 auto ret = g_atraceHal->enableCategories(categories);
1159 if (!ret.isOk()) {
1160 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1161 return false;
1162 } else if (ret != Status::SUCCESS) {
1163 fprintf(stderr, "calling atrace HAL failed: %s\n", toString(ret).c_str());
1164 return false;
1165 }
1166 return true;
1167}
1168
1169static bool cleanUpVendorTracing()
1170{
1171 if (g_atraceHal == nullptr) {
1172 // No atrace HAL
1173 return true;
1174 }
1175
1176 if (!g_vendorCategories.size()) {
1177 // No vendor categories
1178 return true;
1179 }
1180
1181 auto ret = g_atraceHal->disableAllCategories();
1182 if (!ret.isOk()) {
1183 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1184 return false;
1185 } else if (ret != Status::SUCCESS) {
1186 fprintf(stderr, "calling atrace HAL failed: %s\n", toString(ret).c_str());
1187 return false;
1188 }
1189 return true;
1190}
1191
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001192int main(int argc, char **argv)
1193{
1194 bool async = false;
1195 bool traceStart = true;
1196 bool traceStop = true;
1197 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001198 bool traceStream = false;
Hector Dearman11845782018-03-08 14:35:44 +00001199 bool onlyUserspace = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001200
1201 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1202 showHelp(argv[0]);
1203 exit(0);
1204 }
1205
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001206 if (!findTraceFiles()) {
1207 fprintf(stderr, "No trace folder found\n");
1208 exit(-1);
1209 }
1210
Wei Wang16a63a42018-09-21 15:47:45 -07001211 initVendorCategories();
1212
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001213 for (;;) {
1214 int ret;
1215 int option_index = 0;
1216 static struct option long_options[] = {
Yi Kong19d5c002018-07-20 13:39:55 -07001217 {"async_start", no_argument, nullptr, 0 },
1218 {"async_stop", no_argument, nullptr, 0 },
1219 {"async_dump", no_argument, nullptr, 0 },
1220 {"only_userspace", no_argument, nullptr, 0 },
1221 {"list_categories", no_argument, nullptr, 0 },
1222 {"stream", no_argument, nullptr, 0 },
1223 {nullptr, 0, nullptr, 0 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001224 };
1225
John Reck40b26b42016-03-30 09:44:36 -07001226 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001227 long_options, &option_index);
1228
1229 if (ret < 0) {
1230 for (int i = optind; i < argc; i++) {
Primiano Tucci3a26ff62022-03-15 18:53:46 +00001231 setCategoryEnable(argv[i]);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001232 }
1233 break;
1234 }
1235
1236 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001237 case 'a':
1238 g_debugAppCmdLine = optarg;
1239 break;
1240
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001241 case 'b':
1242 g_traceBufferSizeKB = atoi(optarg);
1243 break;
1244
1245 case 'c':
1246 g_traceOverwrite = true;
1247 break;
1248
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001249 case 'f':
1250 g_categoriesFile = optarg;
1251 break;
1252
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001253 case 'k':
1254 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001255 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001256
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001257 case 'n':
1258 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001259 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001260
1261 case 's':
1262 g_initialSleepSecs = atoi(optarg);
1263 break;
1264
1265 case 't':
1266 g_traceDurationSeconds = atoi(optarg);
1267 break;
1268
1269 case 'z':
1270 g_compress = true;
1271 break;
1272
John Reck40b26b42016-03-30 09:44:36 -07001273 case 'o':
1274 g_outputFile = optarg;
1275 break;
1276
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001277 case 0:
1278 if (!strcmp(long_options[option_index].name, "async_start")) {
1279 async = true;
1280 traceStop = false;
1281 traceDump = false;
1282 g_traceOverwrite = true;
1283 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1284 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001285 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001286 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1287 async = true;
1288 traceStart = false;
1289 traceStop = false;
Hector Dearman11845782018-03-08 14:35:44 +00001290 } else if (!strcmp(long_options[option_index].name, "only_userspace")) {
1291 onlyUserspace = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001292 } else if (!strcmp(long_options[option_index].name, "stream")) {
1293 traceStream = true;
1294 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001295 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1296 listSupportedCategories();
1297 exit(0);
1298 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001299 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001300
1301 default:
1302 fprintf(stderr, "\n");
1303 showHelp(argv[0]);
1304 exit(-1);
1305 break;
1306 }
1307 }
1308
Hector Dearman11845782018-03-08 14:35:44 +00001309 if (onlyUserspace) {
1310 if (!async || !(traceStart || traceStop)) {
1311 fprintf(stderr, "--only_userspace can only be used with "
1312 "--async_start or --async_stop\n");
1313 exit(1);
1314 }
1315 }
1316
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001317 registerSigHandler();
1318
1319 if (g_initialSleepSecs > 0) {
1320 sleep(g_initialSleepSecs);
1321 }
1322
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001323 bool ok = true;
Hector Dearman11845782018-03-08 14:35:44 +00001324
Wei Wang5b73b742018-03-08 13:33:12 -08001325 if (traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001326 ok &= setUpUserspaceTracing();
1327 }
1328
1329 if (ok && traceStart && !onlyUserspace) {
1330 ok &= setUpKernelTracing();
Wei Wang16a63a42018-09-21 15:47:45 -07001331 ok &= setUpVendorTracing();
Wei Wang5b73b742018-03-08 13:33:12 -08001332 ok &= startTrace();
1333 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001334
1335 if (ok && traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001336
1337 if (!traceStream && !onlyUserspace) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001338 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001339 fflush(stdout);
1340 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001341
1342 // We clear the trace after starting it because tracing gets enabled for
1343 // each CPU individually in the kernel. Having the beginning of the trace
1344 // contain entries from only one CPU can cause "begin" entries without a
1345 // matching "end" entry to show up if a task gets migrated from one CPU to
1346 // another.
Primiano Tucci929325d2022-03-15 20:26:21 +00001347 if (!onlyUserspace) {
Hector Dearman11845782018-03-08 14:35:44 +00001348 ok = clearTrace();
Primiano Tucci929325d2022-03-15 20:26:21 +00001349 writeClockSyncMarker();
1350 }
Martijn Coenend9535872015-11-26 10:00:55 +01001351 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001352 // Sleep to allow the trace to be captured.
1353 struct timespec timeLeft;
1354 timeLeft.tv_sec = g_traceDurationSeconds;
1355 timeLeft.tv_nsec = 0;
1356 do {
1357 if (g_traceAborted) {
1358 break;
1359 }
1360 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1361 }
Martijn Coenend9535872015-11-26 10:00:55 +01001362
1363 if (traceStream) {
1364 streamTrace();
1365 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001366 }
1367
1368 // Stop the trace and restore the default settings.
Hector Dearman11845782018-03-08 14:35:44 +00001369 if (traceStop && !onlyUserspace)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001370 stopTrace();
1371
Hector Dearman11845782018-03-08 14:35:44 +00001372 if (ok && traceDump && !onlyUserspace) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001373 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001374 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001375 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001376 int outFd = STDOUT_FILENO;
1377 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001378 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001379 }
1380 if (outFd == -1) {
1381 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1382 } else {
1383 dprintf(outFd, "TRACE:\n");
1384 dumpTrace(outFd);
1385 if (g_outputFile) {
1386 close(outFd);
1387 }
1388 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001389 } else {
1390 printf("\ntrace aborted.\n");
1391 fflush(stdout);
1392 }
1393 clearTrace();
1394 } else if (!ok) {
1395 fprintf(stderr, "unable to start tracing\n");
1396 }
1397
1398 // Reset the trace buffer size to 1.
Hector Dearman11845782018-03-08 14:35:44 +00001399 if (traceStop) {
1400 cleanUpUserspaceTracing();
Hector Dearmanada0a4a2019-04-09 14:13:14 +01001401 if (!onlyUserspace) {
1402 cleanUpVendorTracing();
Hector Dearman11845782018-03-08 14:35:44 +00001403 cleanUpKernelTracing();
Hector Dearmanada0a4a2019-04-09 14:13:14 +01001404 }
Hector Dearman11845782018-03-08 14:35:44 +00001405 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001406
1407 return g_traceAborted ? 1 : 0;
1408}