blob: 31848431e4a9d629690682b54f06f517c048a03c [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
Carmen Jackson63ea2912019-04-26 10:41:00 -070065#define MAX_SYS_FILES 11
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" },
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" },
192 { OPT, "events/ext4/ext4_da_write_begin/enable" },
193 { OPT, "events/ext4/ext4_da_write_end/enable" },
194 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
195 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
196 { REQ, "events/block/block_rq_issue/enable" },
197 { REQ, "events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800198 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700199 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800200 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700201 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700202 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800203 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800204 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700205 { "sync", "Synchronization", 0, {
Jesse Halla978cef2019-02-25 16:24:10 -0800206 // linux kernel < 4.9
Jesse Hallae001a32018-05-15 12:02:15 -0700207 { OPT, "events/sync/enable" },
Jesse Halla978cef2019-02-25 16:24:10 -0800208 // linux kernel == 4.9.x
Jesse Hallae001a32018-05-15 12:02:15 -0700209 { OPT, "events/fence/enable" },
Jesse Halla978cef2019-02-25 16:24:10 -0800210 // linux kernel > 4.9
211 { OPT, "events/dma_fence/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800212 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700213 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800214 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800215 } },
Colin Cross580407f2014-08-18 15:22:13 -0700216 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800217 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
218 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
219 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
220 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Carmen Jackson7a23eb72018-07-02 13:14:56 -0700221 { OPT, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700222 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800223 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800224 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800225 } },
Scott Bauerae473362015-06-08 16:32:36 -0700226 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800227 { REQ, "events/binder/binder_transaction/enable" },
228 { REQ, "events/binder/binder_transaction_received/enable" },
Mika Raento80c3e5d2018-06-25 16:47:24 +0100229 { REQ, "events/binder/binder_transaction_alloc_buf/enable" },
Martijn Coenen7f3d7a22017-05-26 09:50:55 -0700230 { OPT, "events/binder/binder_set_priority/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700231 } },
232 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800233 { OPT, "events/binder/binder_lock/enable" },
234 { OPT, "events/binder/binder_locked/enable" },
235 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700236 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200237 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800238 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200239 } },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700240 { "memory", "Memory", 0, {
Collin Fijalkovich08e3f4a2020-03-30 16:20:24 -0700241 { OPT, "events/mm_event/mm_event_record/enable" },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700242 { OPT, "events/kmem/rss_stat/enable" },
243 { OPT, "events/kmem/ion_heap_grow/enable" },
244 { OPT, "events/kmem/ion_heap_shrink/enable" },
Ioannis Ilkos88a85f32020-04-23 22:43:40 +0100245 { OPT, "events/ion/ion_stat/enable" },
Yiwei Zhang63775062020-09-18 11:42:33 -0700246 { OPT, "events/gpu_mem/gpu_mem_total/enable" },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700247 } },
Wei Wange3079a92020-07-08 15:33:20 -0700248 { "thermal", "Thermal event", 0, {
249 { REQ, "events/thermal/thermal_temperature/enable" },
250 { OPT, "events/thermal/cdev_update/enable" },
251 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800252};
253
Wei Wang16a63a42018-09-21 15:47:45 -0700254struct TracingVendorCategory {
255 // The name identifying the category.
256 std::string name;
257
258 // A longer description of the category.
259 std::string description;
260
261 // If the category is enabled through command.
262 bool enabled;
263
264 TracingVendorCategory(string &&name, string &&description, bool enabled)
265 : name(std::move(name))
266 , description(std::move(description))
267 , enabled(enabled)
268 {}
269};
270
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800271/* Command line options */
272static int g_traceDurationSeconds = 5;
273static bool g_traceOverwrite = false;
274static int g_traceBufferSizeKB = 2048;
275static bool g_compress = false;
276static bool g_nohup = false;
277static int g_initialSleepSecs = 0;
Yi Kong19d5c002018-07-20 13:39:55 -0700278static const char* g_categoriesFile = nullptr;
279static const char* g_kernelTraceFuncs = nullptr;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700280static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700281static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800282
283/* Global state */
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700284static bool g_tracePdx = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800285static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700286static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800287static std::string g_traceFolder;
Wei Wang16a63a42018-09-21 15:47:45 -0700288static sp<IAtraceDevice> g_atraceHal;
289static std::vector<TracingVendorCategory> g_vendorCategories;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800290
291/* Sys file paths */
292static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800293 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800294
295static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800296 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800297
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700298#if 0
299// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700300static const char* k_traceCmdlineSizePath =
301 "saved_cmdlines_size";
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700302#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700303
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800304static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800305 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800306
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700307static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800308 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700309
310static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800311 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700312
John Recke757b1c2018-06-28 12:24:33 -0700313static const char* k_recordTgidPath =
314 "options/record-tgid";
315
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700316static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800317 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700318
319static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800320 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700321
322static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800323 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700324
325static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800326 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700327
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700328static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800329 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700330
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800331static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800332 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800333
334static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800335 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800336
Martijn Coenend9535872015-11-26 10:00:55 +0100337static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800338 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100339
John Reck469a1942015-03-26 15:31:35 -0700340static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800341 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700342
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800343// Check whether a file exists.
344static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800345 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800346}
347
348// Check whether a file is writable.
349static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800350 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800351}
352
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700353// Truncate a file.
354static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800355{
Jamie Gennis43122e72013-03-21 14:06:31 -0700356 // This uses creat rather than truncate because some of the debug kernel
357 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
358 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800359 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700360 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800361 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700362 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700363 return false;
364 }
365
Jamie Gennis43122e72013-03-21 14:06:31 -0700366 close(traceFD);
367
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700368 return true;
369}
370
371static bool _writeStr(const char* filename, const char* str, int flags)
372{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800373 std::string fullFilename = g_traceFolder + filename;
374 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800375 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800376 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800377 strerror(errno), errno);
378 return false;
379 }
380
381 bool ok = true;
382 ssize_t len = strlen(str);
383 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800384 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800385 strerror(errno), errno);
386 ok = false;
387 }
388
389 close(fd);
390
391 return ok;
392}
393
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700394// Write a string to a file, returning true if the write was successful.
395static bool writeStr(const char* filename, const char* str)
396{
397 return _writeStr(filename, str, O_WRONLY);
398}
399
400// Append a string to a file, returning true if the write was successful.
401static bool appendStr(const char* filename, const char* str)
402{
403 return _writeStr(filename, str, O_APPEND|O_WRONLY);
404}
405
John Reck469a1942015-03-26 15:31:35 -0700406static void writeClockSyncMarker()
407{
408 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200409 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800410 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200411 if (fd == -1) {
412 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
413 strerror(errno), errno);
414 return;
415 }
John Reck469a1942015-03-26 15:31:35 -0700416 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200417
418 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
419 if (write(fd, buffer, len) != len) {
420 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
421 }
422
423 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
424 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
425 if (write(fd, buffer, len) != len) {
426 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
427 }
428
429 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700430}
431
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800432// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
433// file.
434static bool setKernelOptionEnable(const char* filename, bool enable)
435{
436 return writeStr(filename, enable ? "1" : "0");
437}
438
439// Check whether the category is supported on the device with the current
440// rootness. A category is supported only if all its required /sys/ files are
441// writable and if enabling the category will enable one or more tracing tags
442// or /sys/ files.
443static bool isCategorySupported(const TracingCategory& category)
444{
sergeyvdb404152016-05-02 19:26:07 -0700445 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700446 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700447 }
448
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700449 if (strcmp(category.name, k_pdxServiceCategory) == 0) {
450 return true;
451 }
452
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800453 bool ok = category.tags != 0;
454 for (int i = 0; i < MAX_SYS_FILES; i++) {
455 const char* path = category.sysfiles[i].path;
456 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700457 if (path != nullptr) {
Carmen Jackson5bbc9a22018-12-06 13:47:18 -0800458 if (fileIsWritable(path)) {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800459 ok = true;
Carmen Jackson5bbc9a22018-12-06 13:47:18 -0800460 } else if (req) {
461 return false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800462 }
463 }
464 }
465 return ok;
466}
467
468// Check whether the category would be supported on the device if the user
469// were root. This function assumes that root is able to write to any file
470// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700471// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800472static bool isCategorySupportedForRoot(const TracingCategory& category)
473{
474 bool ok = category.tags != 0;
475 for (int i = 0; i < MAX_SYS_FILES; i++) {
476 const char* path = category.sysfiles[i].path;
477 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700478 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800479 if (req) {
480 if (!fileExists(path)) {
481 return false;
482 } else {
483 ok = true;
484 }
485 } else {
486 ok |= fileExists(path);
487 }
488 }
489 }
490 return ok;
491}
492
493// Enable or disable overwriting of the kernel trace buffers. Disabling this
494// will cause tracing to stop once the trace buffers have filled up.
495static bool setTraceOverwriteEnable(bool enable)
496{
497 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
498}
499
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700500// Set the user initiated trace property
501static bool setUserInitiatedTraceProperty(bool enable)
502{
503 if (!android::base::SetProperty(k_userInitiatedTraceProperty, enable ? "1" : "")) {
504 fprintf(stderr, "error setting user initiated strace system property\n");
505 return false;
506 }
507 return true;
508}
509
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800510// Enable or disable kernel tracing.
511static bool setTracingEnabled(bool enable)
512{
513 return setKernelOptionEnable(k_tracingOnPath, enable);
514}
515
516// Clear the contents of the kernel trace.
517static bool clearTrace()
518{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700519 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800520}
521
522// Set the size of the kernel's trace buffer in kilobytes.
523static bool setTraceBufferSizeKB(int size)
524{
525 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800526 if (size < 1) {
527 size = 1;
528 }
529 snprintf(str, 32, "%d", size);
530 return writeStr(k_traceBufferSizePath, str);
531}
532
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700533#if 0
534// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700535// Set the default size of cmdline hashtable
536static bool setCmdlineSize()
537{
Joel Fernandesce964f22017-06-06 12:20:29 -0700538 if (fileExists(k_traceCmdlineSizePath)) {
539 return writeStr(k_traceCmdlineSizePath, "8192");
540 }
541 return true;
Joel Fernandesed80bd02017-06-02 10:19:28 -0700542}
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700543#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700544
Carmen Jacksonea826792017-05-05 11:42:32 -0700545// Set the clock to the best available option while tracing. Use 'boot' if it's
546// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700547// Any write to the trace_clock sysfs file will reset the buffer, so only
548// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700549static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800550{
Carmen Jacksonea826792017-05-05 11:42:32 -0700551 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
552 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
553 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700554
Carmen Jacksonea826792017-05-05 11:42:32 -0700555 std::string newClock;
556 if (clockStr.find("boot") != std::string::npos) {
557 newClock = "boot";
558 } else if (clockStr.find("mono") != std::string::npos) {
559 newClock = "mono";
560 } else {
561 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700562 }
563
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700564 size_t begin = clockStr.find('[') + 1;
565 size_t end = clockStr.find(']');
Carmen Jacksonea826792017-05-05 11:42:32 -0700566 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
567 return true;
568 }
569 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800570}
571
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700572static bool setPrintTgidEnableIfPresent(bool enable)
573{
John Reckedbf9ec2018-06-29 11:15:17 -0700574 // Pre-4.13 this was options/print-tgid as an android-specific option.
575 // In 4.13+ this is an upstream option called options/record-tgid
576 // Both options produce the same ftrace format change
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700577 if (fileExists(k_printTgidPath)) {
578 return setKernelOptionEnable(k_printTgidPath, enable);
579 }
John Recke757b1c2018-06-28 12:24:33 -0700580 if (fileExists(k_recordTgidPath)) {
581 return setKernelOptionEnable(k_recordTgidPath, enable);
582 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700583 return true;
584}
585
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800586// Set the trace tags that userland tracing uses, and poke the running
587// processes to pick up the new value.
588static bool setTagsProperty(uint64_t tags)
589{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700590 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
591 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800592 fprintf(stderr, "error setting trace tags system property\n");
593 return false;
594 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700595 return true;
596}
597
sergeyv4144eff2016-04-28 11:40:04 -0700598static void clearAppProperties()
599{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700600 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700601 fprintf(stderr, "failed to clear system property: %s",
602 k_traceAppsNumberProperty);
603 }
604}
605
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700606// Set the system property that indicates which apps should perform
607// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700608static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700609{
sergeyv4144eff2016-04-28 11:40:04 -0700610 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700611 char* start = cmdline;
Yi Kong19d5c002018-07-20 13:39:55 -0700612 while (start != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700613 char* end = strchr(start, ',');
Yi Kong19d5c002018-07-20 13:39:55 -0700614 if (end != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700615 *end = '\0';
616 end++;
617 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700618 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
619 if (!android::base::SetProperty(key, start)) {
620 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700621 clearAppProperties();
622 return false;
623 }
624 start = end;
625 i++;
626 }
627
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700628 std::string value = android::base::StringPrintf("%d", i);
629 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
630 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700631 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700632 return false;
633 }
634 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800635}
636
637// Disable all /sys/ enable files.
638static bool disableKernelTraceEvents() {
639 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700640 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800641 const TracingCategory &c = k_categories[i];
642 for (int j = 0; j < MAX_SYS_FILES; j++) {
643 const char* path = c.sysfiles[j].path;
Yi Kong19d5c002018-07-20 13:39:55 -0700644 if (path != nullptr && fileIsWritable(path)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800645 ok &= setKernelOptionEnable(path, false);
646 }
647 }
648 }
649 return ok;
650}
651
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700652// Verify that the comma separated list of functions are being traced by the
653// kernel.
654static bool verifyKernelTraceFuncs(const char* funcs)
655{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100656 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800657 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100658 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700659 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100660 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700661 }
662
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100663 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700664
665 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100666 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700667 bool ok = true;
668 char* myFuncs = strdup(funcs);
669 char* func = strtok(myFuncs, ",");
670 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100671 if (!strchr(func, '*')) {
672 String8 fancyFunc = String8::format("\n%s\n", func);
673 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
674 if (!found || func[0] == '\0') {
675 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
676 "to trace.\n", func);
677 ok = false;
678 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700679 }
Yi Kong19d5c002018-07-20 13:39:55 -0700680 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700681 }
682 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700683 return ok;
684}
685
686// Set the comma separated list of functions that the kernel is to trace.
687static bool setKernelTraceFuncs(const char* funcs)
688{
689 bool ok = true;
690
Yi Kong19d5c002018-07-20 13:39:55 -0700691 if (funcs == nullptr || funcs[0] == '\0') {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700692 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700693 if (fileIsWritable(k_currentTracerPath)) {
694 ok &= writeStr(k_currentTracerPath, "nop");
695 }
696 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700697 ok &= truncateFile(k_ftraceFilterPath);
698 }
699 } else {
700 // Enable kernel function tracing.
701 ok &= writeStr(k_currentTracerPath, "function_graph");
702 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
703 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
704 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
705 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
706
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++) {
Wei Wang16a63a42018-09-21 15:47:45 -07001231 if (!setCategoryEnable(argv[i])) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001232 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1233 exit(1);
1234 }
1235 }
1236 break;
1237 }
1238
1239 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001240 case 'a':
1241 g_debugAppCmdLine = optarg;
1242 break;
1243
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001244 case 'b':
1245 g_traceBufferSizeKB = atoi(optarg);
1246 break;
1247
1248 case 'c':
1249 g_traceOverwrite = true;
1250 break;
1251
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001252 case 'f':
1253 g_categoriesFile = optarg;
1254 break;
1255
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001256 case 'k':
1257 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001258 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001259
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001260 case 'n':
1261 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001262 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001263
1264 case 's':
1265 g_initialSleepSecs = atoi(optarg);
1266 break;
1267
1268 case 't':
1269 g_traceDurationSeconds = atoi(optarg);
1270 break;
1271
1272 case 'z':
1273 g_compress = true;
1274 break;
1275
John Reck40b26b42016-03-30 09:44:36 -07001276 case 'o':
1277 g_outputFile = optarg;
1278 break;
1279
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001280 case 0:
1281 if (!strcmp(long_options[option_index].name, "async_start")) {
1282 async = true;
1283 traceStop = false;
1284 traceDump = false;
1285 g_traceOverwrite = true;
1286 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1287 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001288 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001289 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1290 async = true;
1291 traceStart = false;
1292 traceStop = false;
Hector Dearman11845782018-03-08 14:35:44 +00001293 } else if (!strcmp(long_options[option_index].name, "only_userspace")) {
1294 onlyUserspace = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001295 } else if (!strcmp(long_options[option_index].name, "stream")) {
1296 traceStream = true;
1297 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001298 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1299 listSupportedCategories();
1300 exit(0);
1301 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001302 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001303
1304 default:
1305 fprintf(stderr, "\n");
1306 showHelp(argv[0]);
1307 exit(-1);
1308 break;
1309 }
1310 }
1311
Hector Dearman11845782018-03-08 14:35:44 +00001312 if (onlyUserspace) {
1313 if (!async || !(traceStart || traceStop)) {
1314 fprintf(stderr, "--only_userspace can only be used with "
1315 "--async_start or --async_stop\n");
1316 exit(1);
1317 }
1318 }
1319
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001320 registerSigHandler();
1321
1322 if (g_initialSleepSecs > 0) {
1323 sleep(g_initialSleepSecs);
1324 }
1325
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001326 bool ok = true;
Hector Dearman11845782018-03-08 14:35:44 +00001327
Wei Wang5b73b742018-03-08 13:33:12 -08001328 if (traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001329 ok &= setUpUserspaceTracing();
1330 }
1331
1332 if (ok && traceStart && !onlyUserspace) {
1333 ok &= setUpKernelTracing();
Wei Wang16a63a42018-09-21 15:47:45 -07001334 ok &= setUpVendorTracing();
Wei Wang5b73b742018-03-08 13:33:12 -08001335 ok &= startTrace();
1336 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001337
1338 if (ok && traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001339
1340 if (!traceStream && !onlyUserspace) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001341 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001342 fflush(stdout);
1343 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001344
1345 // We clear the trace after starting it because tracing gets enabled for
1346 // each CPU individually in the kernel. Having the beginning of the trace
1347 // contain entries from only one CPU can cause "begin" entries without a
1348 // matching "end" entry to show up if a task gets migrated from one CPU to
1349 // another.
Hector Dearman11845782018-03-08 14:35:44 +00001350 if (!onlyUserspace)
1351 ok = clearTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001352
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001353 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001354 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001355 // Sleep to allow the trace to be captured.
1356 struct timespec timeLeft;
1357 timeLeft.tv_sec = g_traceDurationSeconds;
1358 timeLeft.tv_nsec = 0;
1359 do {
1360 if (g_traceAborted) {
1361 break;
1362 }
1363 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1364 }
Martijn Coenend9535872015-11-26 10:00:55 +01001365
1366 if (traceStream) {
1367 streamTrace();
1368 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001369 }
1370
1371 // Stop the trace and restore the default settings.
Hector Dearman11845782018-03-08 14:35:44 +00001372 if (traceStop && !onlyUserspace)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001373 stopTrace();
1374
Hector Dearman11845782018-03-08 14:35:44 +00001375 if (ok && traceDump && !onlyUserspace) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001376 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001377 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001378 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001379 int outFd = STDOUT_FILENO;
1380 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001381 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001382 }
1383 if (outFd == -1) {
1384 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1385 } else {
1386 dprintf(outFd, "TRACE:\n");
1387 dumpTrace(outFd);
1388 if (g_outputFile) {
1389 close(outFd);
1390 }
1391 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001392 } else {
1393 printf("\ntrace aborted.\n");
1394 fflush(stdout);
1395 }
1396 clearTrace();
1397 } else if (!ok) {
1398 fprintf(stderr, "unable to start tracing\n");
1399 }
1400
1401 // Reset the trace buffer size to 1.
Hector Dearman11845782018-03-08 14:35:44 +00001402 if (traceStop) {
1403 cleanUpUserspaceTracing();
Hector Dearmanada0a4a2019-04-09 14:13:14 +01001404 if (!onlyUserspace) {
1405 cleanUpVendorTracing();
Hector Dearman11845782018-03-08 14:35:44 +00001406 cleanUpKernelTracing();
Hector Dearmanada0a4a2019-04-09 14:13:14 +01001407 }
Hector Dearman11845782018-03-08 14:35:44 +00001408 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001409
1410 return g_traceAborted ? 1 : 0;
1411}