blob: 021fdb53b2829cff88dcf59a0047b071ba37cf25 [file] [log] [blame]
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Paul Lawrence2cd93cc2017-01-17 09:50:18 -080017#define LOG_TAG "atrace"
John Reck40b26b42016-03-30 09:44:36 -070018
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080019#include <errno.h>
20#include <fcntl.h>
21#include <getopt.h>
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070022#include <inttypes.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080023#include <signal.h>
24#include <stdarg.h>
25#include <stdbool.h>
26#include <stdio.h>
27#include <stdlib.h>
Elliott Hughes3da5d232015-01-25 08:35:20 -080028#include <string.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080029#include <time.h>
Martijn Coenend9535872015-11-26 10:00:55 +010030#include <unistd.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080031#include <zlib.h>
32
Carmen Jacksonea826792017-05-05 11:42:32 -070033#include <fstream>
Elliott Hughesa252f4d2016-07-21 17:12:15 -070034#include <memory>
35
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080036#include <binder/IBinder.h>
37#include <binder/IServiceManager.h>
38#include <binder/Parcel.h>
39
Wei Wang16a63a42018-09-21 15:47:45 -070040#include <android/hardware/atrace/1.0/IAtraceDevice.h>
Martijn Coenenee9b97e2016-11-16 16:00:26 +010041#include <android/hidl/manager/1.0/IServiceManager.h>
42#include <hidl/ServiceManagement.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080043
Corey Tabakaa6c0a722017-05-31 16:37:40 -070044#include <pdx/default_transport/service_utility.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080045#include <utils/String8.h>
John Reck469a1942015-03-26 15:31:35 -070046#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +090047#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080048#include <utils/Trace.h>
Stephane Gasparinid8419c22016-03-02 13:45:15 +010049#include <android-base/file.h>
Elliott Hughes5fd6ff62017-03-28 14:55:31 -070050#include <android-base/macros.h>
51#include <android-base/properties.h>
52#include <android-base/stringprintf.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080053
54using namespace android;
Corey Tabakaa6c0a722017-05-31 16:37:40 -070055using pdx::default_transport::ServiceUtility;
Wei Wang16a63a42018-09-21 15:47:45 -070056using hardware::hidl_vec;
57using hardware::hidl_string;
58using hardware::Return;
59using hardware::atrace::V1_0::IAtraceDevice;
60using hardware::atrace::V1_0::Status;
61using hardware::atrace::V1_0::toString;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080062
Martijn Coenenee9b97e2016-11-16 16:00:26 +010063using std::string;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080064
Wei Wang963999c2021-03-17 16:28:59 -070065#define MAX_SYS_FILES 12
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080066
67const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
Carmen Jackson65ecfbb2018-05-22 10:29:47 -070068const char* k_userInitiatedTraceProperty = "debug.atrace.user_initiated";
sergeyv4144eff2016-04-28 11:40:04 -070069
70const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
71const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070072const char* k_coreServiceCategory = "core_services";
Corey Tabakaa6c0a722017-05-31 16:37:40 -070073const char* k_pdxServiceCategory = "pdx";
sergeyvdb404152016-05-02 19:26:07 -070074const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080075
76typedef enum { OPT, REQ } requiredness ;
77
78struct TracingCategory {
79 // The name identifying the category.
80 const char* name;
81
82 // A longer description of the category.
83 const char* longname;
84
85 // The userland tracing tags that the category enables.
86 uint64_t tags;
87
88 // The fname==NULL terminated list of /sys/ files that the category
89 // enables.
90 struct {
91 // Whether the file must be writable in order to enable the tracing
92 // category.
93 requiredness required;
94
95 // The path to the enable file.
96 const char* path;
97 } sysfiles[MAX_SYS_FILES];
98};
99
100/* Tracing categories */
101static const TracingCategory k_categories[] = {
Yiwei Zhang63775062020-09-18 11:42:33 -0700102 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, {
103 { OPT, "events/gpu_mem/gpu_mem_total/enable" },
104 } },
MÃ¥rten Kongstad2d4f89b2018-12-03 12:58:56 +0100105 { "input", "Input", ATRACE_TAG_INPUT, { } },
106 { "view", "View System", ATRACE_TAG_VIEW, { } },
107 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
108 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
109 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
110 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
111 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
112 { "video", "Video", ATRACE_TAG_VIDEO, { } },
113 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
114 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
115 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
116 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
117 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
118 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
119 { "power", "Power Management", ATRACE_TAG_POWER, { } },
120 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
121 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
122 { "database", "Database", ATRACE_TAG_DATABASE, { } },
123 { "network", "Network", ATRACE_TAG_NETWORK, { } },
124 { "adb", "ADB", ATRACE_TAG_ADB, { } },
125 { "vibrator", "Vibrator", ATRACE_TAG_VIBRATOR, { } },
126 { "aidl", "AIDL calls", ATRACE_TAG_AIDL, { } },
127 { "nnapi", "NNAPI", ATRACE_TAG_NNAPI, { } },
128 { "rro", "Runtime Resource Overlay", ATRACE_TAG_RRO, { } },
Chienyuan Huang53a8b412020-08-20 08:42:31 +0000129 { "sysprop", "System Property", ATRACE_TAG_SYSPROP, { } },
sergeyvdb404152016-05-02 19:26:07 -0700130 { k_coreServiceCategory, "Core services", 0, { } },
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700131 { k_pdxServiceCategory, "PDX services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700132 { "sched", "CPU Scheduling", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800133 { REQ, "events/sched/sched_switch/enable" },
134 { REQ, "events/sched/sched_wakeup/enable" },
Joel Fernandesee593e22017-06-04 13:05:59 -0700135 { OPT, "events/sched/sched_waking/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800136 { OPT, "events/sched/sched_blocked_reason/enable" },
137 { OPT, "events/sched/sched_cpu_hotplug/enable" },
Wei Wangca49dfc2018-05-03 15:45:20 -0700138 { OPT, "events/sched/sched_pi_setprio/enable" },
Carmen Jackson63ea2912019-04-26 10:41:00 -0700139 { OPT, "events/sched/sched_process_exit/enable" },
Joel Fernandes4dfca7c2017-06-15 16:53:52 -0700140 { OPT, "events/cgroup/enable" },
Carmen Jackson63ea2912019-04-26 10:41:00 -0700141 { OPT, "events/oom/oom_score_adj_update/enable" },
142 { OPT, "events/task/task_rename/enable" },
143 { OPT, "events/task/task_newtask/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800144 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700145 { "irq", "IRQ Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800146 { REQ, "events/irq/enable" },
147 { OPT, "events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700148 } },
Joel Fernandes6ccad102017-08-31 08:35:05 -0700149 { "irqoff", "IRQ-disabled code section tracing", 0, {
150 { REQ, "events/preemptirq/irq_enable/enable" },
151 { REQ, "events/preemptirq/irq_disable/enable" },
152 } },
153 { "preemptoff", "Preempt-disabled code section tracing", 0, {
154 { REQ, "events/preemptirq/preempt_enable/enable" },
155 { REQ, "events/preemptirq/preempt_disable/enable" },
156 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100157 { "i2c", "I2C Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800158 { REQ, "events/i2c/enable" },
159 { REQ, "events/i2c/i2c_read/enable" },
160 { REQ, "events/i2c/i2c_write/enable" },
161 { REQ, "events/i2c/i2c_result/enable" },
162 { REQ, "events/i2c/i2c_reply/enable" },
163 { OPT, "events/i2c/smbus_read/enable" },
164 { OPT, "events/i2c/smbus_write/enable" },
165 { OPT, "events/i2c/smbus_result/enable" },
166 { OPT, "events/i2c/smbus_reply/enable" },
Michael Wright43fb6782016-08-18 19:56:43 +0100167 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700168 { "freq", "CPU Frequency", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800169 { REQ, "events/power/cpu_frequency/enable" },
170 { OPT, "events/power/clock_set_rate/enable" },
Kevin DuBois062e0b92017-11-03 15:44:08 -0700171 { OPT, "events/power/clock_disable/enable" },
172 { OPT, "events/power/clock_enable/enable" },
Wei Wang53305dd2018-02-22 11:40:07 -0800173 { OPT, "events/clk/clk_set_rate/enable" },
174 { OPT, "events/clk/clk_disable/enable" },
175 { OPT, "events/clk/clk_enable/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800176 { OPT, "events/power/cpu_frequency_limits/enable" },
Carmen Jackson5ab84322019-08-08 14:35:47 -0700177 { OPT, "events/power/suspend_resume/enable" },
Wei Wang2ded52d2020-07-31 01:13:58 -0700178 { OPT, "events/cpuhp/cpuhp_enter/enable" },
179 { OPT, "events/cpuhp/cpuhp_exit/enable" },
Wei Wang963999c2021-03-17 16:28:59 -0700180 { OPT, "events/cpuhp/cpuhp_pause/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800181 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700182 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800183 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800184 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700185 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800186 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800187 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700188 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800189 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
190 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
191 { OPT, "events/f2fs/f2fs_write_begin/enable" },
192 { OPT, "events/f2fs/f2fs_write_end/enable" },
193 { OPT, "events/ext4/ext4_da_write_begin/enable" },
194 { OPT, "events/ext4/ext4_da_write_end/enable" },
195 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
196 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
197 { REQ, "events/block/block_rq_issue/enable" },
198 { REQ, "events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800199 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700200 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800201 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700202 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700203 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800204 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800205 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700206 { "sync", "Synchronization", 0, {
Jesse Halla978cef2019-02-25 16:24:10 -0800207 // linux kernel < 4.9
Jesse Hallae001a32018-05-15 12:02:15 -0700208 { OPT, "events/sync/enable" },
Jesse Halla978cef2019-02-25 16:24:10 -0800209 // linux kernel == 4.9.x
Jesse Hallae001a32018-05-15 12:02:15 -0700210 { OPT, "events/fence/enable" },
Jesse Halla978cef2019-02-25 16:24:10 -0800211 // linux kernel > 4.9
212 { OPT, "events/dma_fence/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800213 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700214 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800215 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800216 } },
Colin Cross580407f2014-08-18 15:22:13 -0700217 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800218 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
219 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
220 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
221 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Carmen Jackson7a23eb72018-07-02 13:14:56 -0700222 { OPT, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700223 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800224 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800225 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800226 } },
Scott Bauerae473362015-06-08 16:32:36 -0700227 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800228 { REQ, "events/binder/binder_transaction/enable" },
229 { REQ, "events/binder/binder_transaction_received/enable" },
Mika Raento80c3e5d2018-06-25 16:47:24 +0100230 { REQ, "events/binder/binder_transaction_alloc_buf/enable" },
Martijn Coenen7f3d7a22017-05-26 09:50:55 -0700231 { OPT, "events/binder/binder_set_priority/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700232 } },
233 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800234 { OPT, "events/binder/binder_lock/enable" },
235 { OPT, "events/binder/binder_locked/enable" },
236 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700237 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200238 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800239 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200240 } },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700241 { "memory", "Memory", 0, {
Collin Fijalkovich08e3f4a2020-03-30 16:20:24 -0700242 { OPT, "events/mm_event/mm_event_record/enable" },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700243 { OPT, "events/kmem/rss_stat/enable" },
244 { OPT, "events/kmem/ion_heap_grow/enable" },
245 { OPT, "events/kmem/ion_heap_shrink/enable" },
Ioannis Ilkos88a85f32020-04-23 22:43:40 +0100246 { OPT, "events/ion/ion_stat/enable" },
Yiwei Zhang63775062020-09-18 11:42:33 -0700247 { OPT, "events/gpu_mem/gpu_mem_total/enable" },
Collin Fijalkovichd4db32b2021-05-21 11:41:40 -0700248 { OPT, "events/fastrpc/fastrpc_dma_stat/enable" },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700249 } },
Wei Wange3079a92020-07-08 15:33:20 -0700250 { "thermal", "Thermal event", 0, {
251 { REQ, "events/thermal/thermal_temperature/enable" },
252 { OPT, "events/thermal/cdev_update/enable" },
253 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800254};
255
Wei Wang16a63a42018-09-21 15:47:45 -0700256struct TracingVendorCategory {
257 // The name identifying the category.
258 std::string name;
259
260 // A longer description of the category.
261 std::string description;
262
263 // If the category is enabled through command.
264 bool enabled;
265
266 TracingVendorCategory(string &&name, string &&description, bool enabled)
267 : name(std::move(name))
268 , description(std::move(description))
269 , enabled(enabled)
270 {}
271};
272
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800273/* Command line options */
274static int g_traceDurationSeconds = 5;
275static bool g_traceOverwrite = false;
276static int g_traceBufferSizeKB = 2048;
277static bool g_compress = false;
278static bool g_nohup = false;
279static int g_initialSleepSecs = 0;
Yi Kong19d5c002018-07-20 13:39:55 -0700280static const char* g_categoriesFile = nullptr;
281static const char* g_kernelTraceFuncs = nullptr;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700282static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700283static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800284
285/* Global state */
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700286static bool g_tracePdx = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800287static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700288static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800289static std::string g_traceFolder;
Wei Wang16a63a42018-09-21 15:47:45 -0700290static sp<IAtraceDevice> g_atraceHal;
291static std::vector<TracingVendorCategory> g_vendorCategories;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800292
293/* Sys file paths */
294static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800295 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800296
297static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800298 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800299
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700300#if 0
301// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700302static const char* k_traceCmdlineSizePath =
303 "saved_cmdlines_size";
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700304#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700305
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800306static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800307 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800308
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700309static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800310 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700311
312static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800313 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700314
John Recke757b1c2018-06-28 12:24:33 -0700315static const char* k_recordTgidPath =
316 "options/record-tgid";
317
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700318static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800319 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700320
321static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800322 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700323
324static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800325 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700326
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700327static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800328 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700329
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800330static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800331 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800332
333static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800334 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800335
Martijn Coenend9535872015-11-26 10:00:55 +0100336static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800337 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100338
John Reck469a1942015-03-26 15:31:35 -0700339static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800340 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700341
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800342// Check whether a file exists.
343static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800344 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800345}
346
347// Check whether a file is writable.
348static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800349 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800350}
351
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700352// Truncate a file.
353static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800354{
Jamie Gennis43122e72013-03-21 14:06:31 -0700355 // This uses creat rather than truncate because some of the debug kernel
356 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
357 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800358 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700359 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800360 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700361 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700362 return false;
363 }
364
Jamie Gennis43122e72013-03-21 14:06:31 -0700365 close(traceFD);
366
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700367 return true;
368}
369
370static bool _writeStr(const char* filename, const char* str, int flags)
371{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800372 std::string fullFilename = g_traceFolder + filename;
373 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800374 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800375 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800376 strerror(errno), errno);
377 return false;
378 }
379
380 bool ok = true;
381 ssize_t len = strlen(str);
382 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800383 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800384 strerror(errno), errno);
385 ok = false;
386 }
387
388 close(fd);
389
390 return ok;
391}
392
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700393// Write a string to a file, returning true if the write was successful.
394static bool writeStr(const char* filename, const char* str)
395{
396 return _writeStr(filename, str, O_WRONLY);
397}
398
399// Append a string to a file, returning true if the write was successful.
400static bool appendStr(const char* filename, const char* str)
401{
402 return _writeStr(filename, str, O_APPEND|O_WRONLY);
403}
404
John Reck469a1942015-03-26 15:31:35 -0700405static void writeClockSyncMarker()
406{
407 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200408 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800409 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200410 if (fd == -1) {
411 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
412 strerror(errno), errno);
413 return;
414 }
John Reck469a1942015-03-26 15:31:35 -0700415 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200416
417 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
418 if (write(fd, buffer, len) != len) {
419 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
420 }
421
422 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
423 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
424 if (write(fd, buffer, len) != len) {
425 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
426 }
427
428 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700429}
430
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800431// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
432// file.
433static bool setKernelOptionEnable(const char* filename, bool enable)
434{
435 return writeStr(filename, enable ? "1" : "0");
436}
437
438// Check whether the category is supported on the device with the current
439// rootness. A category is supported only if all its required /sys/ files are
440// writable and if enabling the category will enable one or more tracing tags
441// or /sys/ files.
442static bool isCategorySupported(const TracingCategory& category)
443{
sergeyvdb404152016-05-02 19:26:07 -0700444 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700445 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700446 }
447
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700448 if (strcmp(category.name, k_pdxServiceCategory) == 0) {
449 return true;
450 }
451
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800452 bool ok = category.tags != 0;
453 for (int i = 0; i < MAX_SYS_FILES; i++) {
454 const char* path = category.sysfiles[i].path;
455 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700456 if (path != nullptr) {
Carmen Jackson5bbc9a22018-12-06 13:47:18 -0800457 if (fileIsWritable(path)) {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800458 ok = true;
Carmen Jackson5bbc9a22018-12-06 13:47:18 -0800459 } else if (req) {
460 return false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800461 }
462 }
463 }
464 return ok;
465}
466
467// Check whether the category would be supported on the device if the user
468// were root. This function assumes that root is able to write to any file
469// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700470// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800471static bool isCategorySupportedForRoot(const TracingCategory& category)
472{
473 bool ok = category.tags != 0;
474 for (int i = 0; i < MAX_SYS_FILES; i++) {
475 const char* path = category.sysfiles[i].path;
476 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700477 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800478 if (req) {
479 if (!fileExists(path)) {
480 return false;
481 } else {
482 ok = true;
483 }
484 } else {
485 ok |= fileExists(path);
486 }
487 }
488 }
489 return ok;
490}
491
492// Enable or disable overwriting of the kernel trace buffers. Disabling this
493// will cause tracing to stop once the trace buffers have filled up.
494static bool setTraceOverwriteEnable(bool enable)
495{
496 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
497}
498
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700499// Set the user initiated trace property
500static bool setUserInitiatedTraceProperty(bool enable)
501{
502 if (!android::base::SetProperty(k_userInitiatedTraceProperty, enable ? "1" : "")) {
503 fprintf(stderr, "error setting user initiated strace system property\n");
504 return false;
505 }
506 return true;
507}
508
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800509// Enable or disable kernel tracing.
510static bool setTracingEnabled(bool enable)
511{
512 return setKernelOptionEnable(k_tracingOnPath, enable);
513}
514
515// Clear the contents of the kernel trace.
516static bool clearTrace()
517{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700518 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800519}
520
521// Set the size of the kernel's trace buffer in kilobytes.
522static bool setTraceBufferSizeKB(int size)
523{
524 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800525 if (size < 1) {
526 size = 1;
527 }
528 snprintf(str, 32, "%d", size);
529 return writeStr(k_traceBufferSizePath, str);
530}
531
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700532#if 0
533// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700534// Set the default size of cmdline hashtable
535static bool setCmdlineSize()
536{
Joel Fernandesce964f22017-06-06 12:20:29 -0700537 if (fileExists(k_traceCmdlineSizePath)) {
538 return writeStr(k_traceCmdlineSizePath, "8192");
539 }
540 return true;
Joel Fernandesed80bd02017-06-02 10:19:28 -0700541}
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700542#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700543
Carmen Jacksonea826792017-05-05 11:42:32 -0700544// Set the clock to the best available option while tracing. Use 'boot' if it's
545// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700546// Any write to the trace_clock sysfs file will reset the buffer, so only
547// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700548static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800549{
Carmen Jacksonea826792017-05-05 11:42:32 -0700550 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
551 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
552 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700553
Carmen Jacksonea826792017-05-05 11:42:32 -0700554 std::string newClock;
555 if (clockStr.find("boot") != std::string::npos) {
556 newClock = "boot";
557 } else if (clockStr.find("mono") != std::string::npos) {
558 newClock = "mono";
559 } else {
560 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700561 }
562
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700563 size_t begin = clockStr.find('[') + 1;
564 size_t end = clockStr.find(']');
Carmen Jacksonea826792017-05-05 11:42:32 -0700565 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
566 return true;
567 }
568 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800569}
570
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700571static bool setPrintTgidEnableIfPresent(bool enable)
572{
John Reckedbf9ec2018-06-29 11:15:17 -0700573 // Pre-4.13 this was options/print-tgid as an android-specific option.
574 // In 4.13+ this is an upstream option called options/record-tgid
575 // Both options produce the same ftrace format change
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700576 if (fileExists(k_printTgidPath)) {
577 return setKernelOptionEnable(k_printTgidPath, enable);
578 }
John Recke757b1c2018-06-28 12:24:33 -0700579 if (fileExists(k_recordTgidPath)) {
580 return setKernelOptionEnable(k_recordTgidPath, enable);
581 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700582 return true;
583}
584
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800585// Set the trace tags that userland tracing uses, and poke the running
586// processes to pick up the new value.
587static bool setTagsProperty(uint64_t tags)
588{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700589 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
590 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800591 fprintf(stderr, "error setting trace tags system property\n");
592 return false;
593 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700594 return true;
595}
596
sergeyv4144eff2016-04-28 11:40:04 -0700597static void clearAppProperties()
598{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700599 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700600 fprintf(stderr, "failed to clear system property: %s",
601 k_traceAppsNumberProperty);
602 }
603}
604
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700605// Set the system property that indicates which apps should perform
606// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700607static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700608{
sergeyv4144eff2016-04-28 11:40:04 -0700609 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700610 char* start = cmdline;
Yi Kong19d5c002018-07-20 13:39:55 -0700611 while (start != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700612 char* end = strchr(start, ',');
Yi Kong19d5c002018-07-20 13:39:55 -0700613 if (end != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700614 *end = '\0';
615 end++;
616 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700617 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
618 if (!android::base::SetProperty(key, start)) {
619 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700620 clearAppProperties();
621 return false;
622 }
623 start = end;
624 i++;
625 }
626
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700627 std::string value = android::base::StringPrintf("%d", i);
628 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
629 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700630 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700631 return false;
632 }
633 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800634}
635
636// Disable all /sys/ enable files.
637static bool disableKernelTraceEvents() {
638 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700639 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800640 const TracingCategory &c = k_categories[i];
641 for (int j = 0; j < MAX_SYS_FILES; j++) {
642 const char* path = c.sysfiles[j].path;
Yi Kong19d5c002018-07-20 13:39:55 -0700643 if (path != nullptr && fileIsWritable(path)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800644 ok &= setKernelOptionEnable(path, false);
645 }
646 }
647 }
648 return ok;
649}
650
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700651// Verify that the comma separated list of functions are being traced by the
652// kernel.
653static bool verifyKernelTraceFuncs(const char* funcs)
654{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100655 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800656 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100657 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700658 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100659 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700660 }
661
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100662 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700663
664 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100665 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700666 bool ok = true;
667 char* myFuncs = strdup(funcs);
668 char* func = strtok(myFuncs, ",");
669 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100670 if (!strchr(func, '*')) {
671 String8 fancyFunc = String8::format("\n%s\n", func);
672 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
673 if (!found || func[0] == '\0') {
674 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
675 "to trace.\n", func);
676 ok = false;
677 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700678 }
Yi Kong19d5c002018-07-20 13:39:55 -0700679 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700680 }
681 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700682 return ok;
683}
684
685// Set the comma separated list of functions that the kernel is to trace.
686static bool setKernelTraceFuncs(const char* funcs)
687{
688 bool ok = true;
689
Yi Kong19d5c002018-07-20 13:39:55 -0700690 if (funcs == nullptr || funcs[0] == '\0') {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700691 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700692 if (fileIsWritable(k_currentTracerPath)) {
693 ok &= writeStr(k_currentTracerPath, "nop");
694 }
695 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700696 ok &= truncateFile(k_ftraceFilterPath);
697 }
698 } else {
699 // Enable kernel function tracing.
700 ok &= writeStr(k_currentTracerPath, "function_graph");
701 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
702 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
703 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700704
705 // Set the requested filter functions.
706 ok &= truncateFile(k_ftraceFilterPath);
707 char* myFuncs = strdup(funcs);
708 char* func = strtok(myFuncs, ",");
709 while (func) {
710 ok &= appendStr(k_ftraceFilterPath, func);
Yi Kong19d5c002018-07-20 13:39:55 -0700711 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700712 }
713 free(myFuncs);
714
715 // Verify that the set functions are being traced.
716 if (ok) {
717 ok &= verifyKernelTraceFuncs(funcs);
718 }
719 }
720
721 return ok;
722}
723
Wei Wang16a63a42018-09-21 15:47:45 -0700724static bool setCategoryEnable(const char* name)
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900725{
Wei Wang16a63a42018-09-21 15:47:45 -0700726 bool vendor_found = false;
727 for (auto &c : g_vendorCategories) {
728 if (strcmp(name, c.name.c_str()) == 0) {
729 c.enabled = true;
730 vendor_found = true;
731 }
732 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700733 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900734 const TracingCategory& c = k_categories[i];
735 if (strcmp(name, c.name) == 0) {
736 if (isCategorySupported(c)) {
Wei Wang16a63a42018-09-21 15:47:45 -0700737 g_categoryEnables[i] = true;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900738 return true;
739 } else {
740 if (isCategorySupportedForRoot(c)) {
741 fprintf(stderr, "error: category \"%s\" requires root "
742 "privileges.\n", name);
743 } else {
744 fprintf(stderr, "error: category \"%s\" is not supported "
745 "on this device.\n", name);
746 }
747 return false;
748 }
749 }
750 }
Wei Wang16a63a42018-09-21 15:47:45 -0700751 if (vendor_found) {
752 return true;
753 }
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900754 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
755 return false;
756}
757
758static bool setCategoriesEnableFromFile(const char* categories_file)
759{
760 if (!categories_file) {
761 return true;
762 }
Yi Kong19d5c002018-07-20 13:39:55 -0700763 Tokenizer* tokenizer = nullptr;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900764 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
765 return false;
766 }
767 bool ok = true;
768 while (!tokenizer->isEol()) {
769 String8 token = tokenizer->nextToken(" ");
770 if (token.isEmpty()) {
771 tokenizer->skipDelimiters(" ");
772 continue;
773 }
Wei Wang16a63a42018-09-21 15:47:45 -0700774 ok &= setCategoryEnable(token.string());
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900775 }
776 delete tokenizer;
777 return ok;
778}
779
Hector Dearman11845782018-03-08 14:35:44 +0000780static bool setUpUserspaceTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800781{
782 bool ok = true;
783
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800784 // Set up the tags property.
785 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700786 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800787 if (g_categoryEnables[i]) {
788 const TracingCategory &c = k_categories[i];
789 tags |= c.tags;
790 }
791 }
sergeyvdb404152016-05-02 19:26:07 -0700792
793 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700794 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700795 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
796 coreServicesTagEnabled = g_categoryEnables[i];
797 }
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700798
799 // Set whether to poke PDX services in this session.
800 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
801 g_tracePdx = g_categoryEnables[i];
802 }
sergeyvdb404152016-05-02 19:26:07 -0700803 }
804
805 std::string packageList(g_debugAppCmdLine);
806 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700807 if (!packageList.empty()) {
808 packageList += ",";
809 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700810 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700811 }
Dan Austin09a79872016-05-31 13:27:03 -0700812 ok &= setAppCmdlineProperty(&packageList[0]);
Florian Mayer6263b582019-12-10 13:28:45 +0000813 ok &= setTagsProperty(tags);
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700814 if (g_tracePdx) {
815 ok &= ServiceUtility::PokeServices();
816 }
817
Hector Dearman11845782018-03-08 14:35:44 +0000818 return ok;
819}
820
821static void cleanUpUserspaceTracing()
822{
823 setTagsProperty(0);
824 clearAppProperties();
Hector Dearman11845782018-03-08 14:35:44 +0000825
826 if (g_tracePdx) {
827 ServiceUtility::PokeServices();
828 }
829}
830
831
832// Set all the kernel tracing settings to the desired state for this trace
833// capture.
834static bool setUpKernelTracing()
835{
836 bool ok = true;
837
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700838 ok &= setUserInitiatedTraceProperty(true);
839
Hector Dearman11845782018-03-08 14:35:44 +0000840 // Set up the tracing options.
841 ok &= setCategoriesEnableFromFile(g_categoriesFile);
842 ok &= setTraceOverwriteEnable(g_traceOverwrite);
843 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
844 // TODO: Re-enable after stabilization
845 //ok &= setCmdlineSize();
846 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
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800873 return ok;
874}
875
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700876// Reset all the kernel tracing settings to their default state.
Hector Dearman11845782018-03-08 14:35:44 +0000877static void cleanUpKernelTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800878{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800879 // Disable all tracing that we're able to.
880 disableKernelTraceEvents();
881
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800882 // Set the options back to their defaults.
883 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700884 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700885 setPrintTgidEnableIfPresent(false);
Yi Kong19d5c002018-07-20 13:39:55 -0700886 setKernelTraceFuncs(nullptr);
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700887 setUserInitiatedTraceProperty(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700888}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800889
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700890// Enable tracing in the kernel.
891static bool startTrace()
892{
893 return setTracingEnabled(true);
894}
895
896// Disable tracing in the kernel.
897static void stopTrace()
898{
899 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800900}
901
Martijn Coenend9535872015-11-26 10:00:55 +0100902// Read data from the tracing pipe and forward to stdout
903static void streamTrace()
904{
905 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800906 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100907 if (traceFD == -1) {
908 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
909 strerror(errno), errno);
910 return;
911 }
912 while (!g_traceAborted) {
913 ssize_t bytes_read = read(traceFD, trace_data, 4096);
914 if (bytes_read > 0) {
915 write(STDOUT_FILENO, trace_data, bytes_read);
916 fflush(stdout);
917 } else {
918 if (!g_traceAborted) {
919 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
920 bytes_read, errno, strerror(errno));
921 }
922 break;
923 }
924 }
925}
926
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800927// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700928static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800929{
John Reck6c8ac922016-03-28 11:25:30 -0700930 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800931 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800932 if (traceFD == -1) {
933 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
934 strerror(errno), errno);
935 return;
936 }
937
938 if (g_compress) {
939 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800940 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700941
942 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800943 if (result != Z_OK) {
944 fprintf(stderr, "error initializing zlib: %d\n", result);
945 close(traceFD);
946 return;
947 }
948
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700949 constexpr size_t bufSize = 64*1024;
950 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
951 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
952 if (!in || !out) {
953 fprintf(stderr, "couldn't allocate buffers\n");
954 close(traceFD);
955 return;
956 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800957
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700958 int flush = Z_NO_FLUSH;
959
960 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800961 zs.avail_out = bufSize;
962
963 do {
964
965 if (zs.avail_in == 0) {
966 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700967 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800968 if (result < 0) {
969 fprintf(stderr, "error reading trace: %s (%d)\n",
970 strerror(errno), errno);
971 result = Z_STREAM_END;
972 break;
973 } else if (result == 0) {
974 flush = Z_FINISH;
975 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700976 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800977 zs.avail_in = result;
978 }
979 }
980
981 if (zs.avail_out == 0) {
982 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700983 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800984 if ((size_t)result < bufSize) {
985 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
986 strerror(errno), errno);
987 result = Z_STREAM_END; // skip deflate error message
988 zs.avail_out = bufSize; // skip the final write
989 break;
990 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700991 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800992 zs.avail_out = bufSize;
993 }
994
995 } while ((result = deflate(&zs, flush)) == Z_OK);
996
997 if (result != Z_STREAM_END) {
998 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
999 }
1000
1001 if (zs.avail_out < bufSize) {
1002 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -07001003 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001004 if ((size_t)result < bytes) {
1005 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1006 strerror(errno), errno);
1007 }
1008 }
1009
1010 result = deflateEnd(&zs);
1011 if (result != Z_OK) {
1012 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1013 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001014 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001015 char buf[4096];
1016 ssize_t rc;
1017 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1018 if (!android::base::WriteFully(outFd, buf, rc)) {
1019 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1020 break;
1021 }
1022 }
1023 if (rc == -1) {
1024 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001025 }
1026 }
1027
1028 close(traceFD);
1029}
1030
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001031static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001032{
1033 if (!g_nohup) {
1034 g_traceAborted = true;
1035 }
1036}
1037
1038static void registerSigHandler()
1039{
1040 struct sigaction sa;
1041 sigemptyset(&sa.sa_mask);
1042 sa.sa_flags = 0;
1043 sa.sa_handler = handleSignal;
Yi Kong19d5c002018-07-20 13:39:55 -07001044 sigaction(SIGHUP, &sa, nullptr);
1045 sigaction(SIGINT, &sa, nullptr);
1046 sigaction(SIGQUIT, &sa, nullptr);
1047 sigaction(SIGTERM, &sa, nullptr);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001048}
1049
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001050static void listSupportedCategories()
1051{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001052 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001053 const TracingCategory& c = k_categories[i];
1054 if (isCategorySupported(c)) {
1055 printf(" %10s - %s\n", c.name, c.longname);
1056 }
1057 }
Wei Wang16a63a42018-09-21 15:47:45 -07001058 for (const auto &c : g_vendorCategories) {
1059 printf(" %10s - %s (HAL)\n", c.name.c_str(), c.description.c_str());
1060 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001061}
1062
1063// Print the command usage help to stderr.
1064static void showHelp(const char *cmd)
1065{
1066 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1067 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001068 " -a appname enable app-level tracing for a comma "
Daniel Colascione519a0792018-02-09 20:05:39 -08001069 "separated list of cmdlines; * is a wildcard matching any process\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001070 " -b N use a trace buffer size of N KB\n"
1071 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001072 " -f filename use the categories written in a file as space-separated\n"
1073 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001074 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001075 " -n ignore signals\n"
1076 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001077 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001078 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001079 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001080 " --async_dump dump the current contents of circular trace buffer\n"
1081 " --async_stop stop tracing and dump the current contents of circular\n"
1082 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001083 " --stream stream trace to stdout as it enters the trace buffer\n"
1084 " Note: this can take significant CPU time, and is best\n"
1085 " used for measuring things that are not affected by\n"
1086 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001087 " --list_categories\n"
1088 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001089 " -o filename write the trace to the specified file instead\n"
1090 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001091 );
1092}
1093
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001094bool findTraceFiles()
1095{
1096 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1097 static const std::string tracefs_path = "/sys/kernel/tracing/";
1098 static const std::string trace_file = "trace_marker";
1099
1100 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1101 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1102
1103 if (!tracefs && !debugfs) {
1104 fprintf(stderr, "Error: Did not find trace folder\n");
1105 return false;
1106 }
1107
1108 if (tracefs) {
1109 g_traceFolder = tracefs_path;
1110 } else {
1111 g_traceFolder = debugfs_path;
1112 }
1113
1114 return true;
1115}
1116
Wei Wang16a63a42018-09-21 15:47:45 -07001117void initVendorCategories()
1118{
1119 g_atraceHal = IAtraceDevice::getService();
1120
1121 if (g_atraceHal == nullptr) {
1122 // No atrace HAL
1123 return;
1124 }
1125
1126 Return<void> ret = g_atraceHal->listCategories(
1127 [](const auto& list) {
1128 g_vendorCategories.reserve(list.size());
1129 for (const auto& category : list) {
1130 g_vendorCategories.emplace_back(category.name, category.description, false);
1131 }
1132 });
1133 if (!ret.isOk()) {
1134 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1135 }
1136}
1137
1138static bool setUpVendorTracing()
1139{
1140 if (g_atraceHal == nullptr) {
1141 // No atrace HAL
1142 return true;
1143 }
1144
1145 std::vector<hidl_string> categories;
1146 for (const auto &c : g_vendorCategories) {
1147 if (c.enabled) {
1148 categories.emplace_back(c.name);
1149 }
1150 }
1151
1152 if (!categories.size()) {
1153 return true;
1154 }
1155
1156 auto ret = g_atraceHal->enableCategories(categories);
1157 if (!ret.isOk()) {
1158 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1159 return false;
1160 } else if (ret != Status::SUCCESS) {
1161 fprintf(stderr, "calling atrace HAL failed: %s\n", toString(ret).c_str());
1162 return false;
1163 }
1164 return true;
1165}
1166
1167static bool cleanUpVendorTracing()
1168{
1169 if (g_atraceHal == nullptr) {
1170 // No atrace HAL
1171 return true;
1172 }
1173
1174 if (!g_vendorCategories.size()) {
1175 // No vendor categories
1176 return true;
1177 }
1178
1179 auto ret = g_atraceHal->disableAllCategories();
1180 if (!ret.isOk()) {
1181 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1182 return false;
1183 } else if (ret != Status::SUCCESS) {
1184 fprintf(stderr, "calling atrace HAL failed: %s\n", toString(ret).c_str());
1185 return false;
1186 }
1187 return true;
1188}
1189
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001190int main(int argc, char **argv)
1191{
1192 bool async = false;
1193 bool traceStart = true;
1194 bool traceStop = true;
1195 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001196 bool traceStream = false;
Hector Dearman11845782018-03-08 14:35:44 +00001197 bool onlyUserspace = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001198
1199 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1200 showHelp(argv[0]);
1201 exit(0);
1202 }
1203
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001204 if (!findTraceFiles()) {
1205 fprintf(stderr, "No trace folder found\n");
1206 exit(-1);
1207 }
1208
Wei Wang16a63a42018-09-21 15:47:45 -07001209 initVendorCategories();
1210
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001211 for (;;) {
1212 int ret;
1213 int option_index = 0;
1214 static struct option long_options[] = {
Yi Kong19d5c002018-07-20 13:39:55 -07001215 {"async_start", no_argument, nullptr, 0 },
1216 {"async_stop", no_argument, nullptr, 0 },
1217 {"async_dump", no_argument, nullptr, 0 },
1218 {"only_userspace", no_argument, nullptr, 0 },
1219 {"list_categories", no_argument, nullptr, 0 },
1220 {"stream", no_argument, nullptr, 0 },
1221 {nullptr, 0, nullptr, 0 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001222 };
1223
John Reck40b26b42016-03-30 09:44:36 -07001224 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001225 long_options, &option_index);
1226
1227 if (ret < 0) {
1228 for (int i = optind; i < argc; i++) {
Wei Wang16a63a42018-09-21 15:47:45 -07001229 if (!setCategoryEnable(argv[i])) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001230 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1231 exit(1);
1232 }
1233 }
1234 break;
1235 }
1236
1237 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001238 case 'a':
1239 g_debugAppCmdLine = optarg;
1240 break;
1241
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001242 case 'b':
1243 g_traceBufferSizeKB = atoi(optarg);
1244 break;
1245
1246 case 'c':
1247 g_traceOverwrite = true;
1248 break;
1249
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001250 case 'f':
1251 g_categoriesFile = optarg;
1252 break;
1253
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001254 case 'k':
1255 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001256 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001257
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001258 case 'n':
1259 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001260 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001261
1262 case 's':
1263 g_initialSleepSecs = atoi(optarg);
1264 break;
1265
1266 case 't':
1267 g_traceDurationSeconds = atoi(optarg);
1268 break;
1269
1270 case 'z':
1271 g_compress = true;
1272 break;
1273
John Reck40b26b42016-03-30 09:44:36 -07001274 case 'o':
1275 g_outputFile = optarg;
1276 break;
1277
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001278 case 0:
1279 if (!strcmp(long_options[option_index].name, "async_start")) {
1280 async = true;
1281 traceStop = false;
1282 traceDump = false;
1283 g_traceOverwrite = true;
1284 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1285 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001286 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001287 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1288 async = true;
1289 traceStart = false;
1290 traceStop = false;
Hector Dearman11845782018-03-08 14:35:44 +00001291 } else if (!strcmp(long_options[option_index].name, "only_userspace")) {
1292 onlyUserspace = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001293 } else if (!strcmp(long_options[option_index].name, "stream")) {
1294 traceStream = true;
1295 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001296 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1297 listSupportedCategories();
1298 exit(0);
1299 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001300 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001301
1302 default:
1303 fprintf(stderr, "\n");
1304 showHelp(argv[0]);
1305 exit(-1);
1306 break;
1307 }
1308 }
1309
Hector Dearman11845782018-03-08 14:35:44 +00001310 if (onlyUserspace) {
1311 if (!async || !(traceStart || traceStop)) {
1312 fprintf(stderr, "--only_userspace can only be used with "
1313 "--async_start or --async_stop\n");
1314 exit(1);
1315 }
1316 }
1317
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001318 registerSigHandler();
1319
1320 if (g_initialSleepSecs > 0) {
1321 sleep(g_initialSleepSecs);
1322 }
1323
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001324 bool ok = true;
Hector Dearman11845782018-03-08 14:35:44 +00001325
Wei Wang5b73b742018-03-08 13:33:12 -08001326 if (traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001327 ok &= setUpUserspaceTracing();
1328 }
1329
1330 if (ok && traceStart && !onlyUserspace) {
1331 ok &= setUpKernelTracing();
Wei Wang16a63a42018-09-21 15:47:45 -07001332 ok &= setUpVendorTracing();
Wei Wang5b73b742018-03-08 13:33:12 -08001333 ok &= startTrace();
1334 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001335
1336 if (ok && traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001337
1338 if (!traceStream && !onlyUserspace) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001339 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001340 fflush(stdout);
1341 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001342
1343 // We clear the trace after starting it because tracing gets enabled for
1344 // each CPU individually in the kernel. Having the beginning of the trace
1345 // contain entries from only one CPU can cause "begin" entries without a
1346 // matching "end" entry to show up if a task gets migrated from one CPU to
1347 // another.
Hector Dearman11845782018-03-08 14:35:44 +00001348 if (!onlyUserspace)
1349 ok = clearTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001350
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001351 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001352 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001353 // Sleep to allow the trace to be captured.
1354 struct timespec timeLeft;
1355 timeLeft.tv_sec = g_traceDurationSeconds;
1356 timeLeft.tv_nsec = 0;
1357 do {
1358 if (g_traceAborted) {
1359 break;
1360 }
1361 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1362 }
Martijn Coenend9535872015-11-26 10:00:55 +01001363
1364 if (traceStream) {
1365 streamTrace();
1366 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001367 }
1368
1369 // Stop the trace and restore the default settings.
Hector Dearman11845782018-03-08 14:35:44 +00001370 if (traceStop && !onlyUserspace)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001371 stopTrace();
1372
Hector Dearman11845782018-03-08 14:35:44 +00001373 if (ok && traceDump && !onlyUserspace) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001374 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001375 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001376 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001377 int outFd = STDOUT_FILENO;
1378 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001379 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001380 }
1381 if (outFd == -1) {
1382 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1383 } else {
1384 dprintf(outFd, "TRACE:\n");
1385 dumpTrace(outFd);
1386 if (g_outputFile) {
1387 close(outFd);
1388 }
1389 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001390 } else {
1391 printf("\ntrace aborted.\n");
1392 fflush(stdout);
1393 }
1394 clearTrace();
1395 } else if (!ok) {
1396 fprintf(stderr, "unable to start tracing\n");
1397 }
1398
1399 // Reset the trace buffer size to 1.
Hector Dearman11845782018-03-08 14:35:44 +00001400 if (traceStop) {
1401 cleanUpUserspaceTracing();
Hector Dearmanada0a4a2019-04-09 14:13:14 +01001402 if (!onlyUserspace) {
1403 cleanUpVendorTracing();
Hector Dearman11845782018-03-08 14:35:44 +00001404 cleanUpKernelTracing();
Hector Dearmanada0a4a2019-04-09 14:13:14 +01001405 }
Hector Dearman11845782018-03-08 14:35:44 +00001406 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001407
1408 return g_traceAborted ? 1 : 0;
1409}