blob: 544e26c66694eba435f543ac7c512ef8d8361861 [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[] = {
MÃ¥rten Kongstad2d4f89b2018-12-03 12:58:56 +0100102 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, { } },
103 { "input", "Input", ATRACE_TAG_INPUT, { } },
104 { "view", "View System", ATRACE_TAG_VIEW, { } },
105 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
106 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
107 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
108 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
109 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
110 { "video", "Video", ATRACE_TAG_VIDEO, { } },
111 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
112 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
113 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
114 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
115 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
116 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
117 { "power", "Power Management", ATRACE_TAG_POWER, { } },
118 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
119 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
120 { "database", "Database", ATRACE_TAG_DATABASE, { } },
121 { "network", "Network", ATRACE_TAG_NETWORK, { } },
122 { "adb", "ADB", ATRACE_TAG_ADB, { } },
123 { "vibrator", "Vibrator", ATRACE_TAG_VIBRATOR, { } },
124 { "aidl", "AIDL calls", ATRACE_TAG_AIDL, { } },
125 { "nnapi", "NNAPI", ATRACE_TAG_NNAPI, { } },
126 { "rro", "Runtime Resource Overlay", ATRACE_TAG_RRO, { } },
sergeyvdb404152016-05-02 19:26:07 -0700127 { k_coreServiceCategory, "Core services", 0, { } },
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700128 { k_pdxServiceCategory, "PDX services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700129 { "sched", "CPU Scheduling", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800130 { REQ, "events/sched/sched_switch/enable" },
131 { REQ, "events/sched/sched_wakeup/enable" },
Joel Fernandesee593e22017-06-04 13:05:59 -0700132 { OPT, "events/sched/sched_waking/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800133 { OPT, "events/sched/sched_blocked_reason/enable" },
134 { OPT, "events/sched/sched_cpu_hotplug/enable" },
Wei Wangca49dfc2018-05-03 15:45:20 -0700135 { OPT, "events/sched/sched_pi_setprio/enable" },
Carmen Jackson63ea2912019-04-26 10:41:00 -0700136 { OPT, "events/sched/sched_process_exit/enable" },
Joel Fernandes4dfca7c2017-06-15 16:53:52 -0700137 { OPT, "events/cgroup/enable" },
Carmen Jackson63ea2912019-04-26 10:41:00 -0700138 { OPT, "events/oom/oom_score_adj_update/enable" },
139 { OPT, "events/task/task_rename/enable" },
140 { OPT, "events/task/task_newtask/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800141 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700142 { "irq", "IRQ Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800143 { REQ, "events/irq/enable" },
144 { OPT, "events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700145 } },
Joel Fernandes6ccad102017-08-31 08:35:05 -0700146 { "irqoff", "IRQ-disabled code section tracing", 0, {
147 { REQ, "events/preemptirq/irq_enable/enable" },
148 { REQ, "events/preemptirq/irq_disable/enable" },
149 } },
150 { "preemptoff", "Preempt-disabled code section tracing", 0, {
151 { REQ, "events/preemptirq/preempt_enable/enable" },
152 { REQ, "events/preemptirq/preempt_disable/enable" },
153 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100154 { "i2c", "I2C Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800155 { REQ, "events/i2c/enable" },
156 { REQ, "events/i2c/i2c_read/enable" },
157 { REQ, "events/i2c/i2c_write/enable" },
158 { REQ, "events/i2c/i2c_result/enable" },
159 { REQ, "events/i2c/i2c_reply/enable" },
160 { OPT, "events/i2c/smbus_read/enable" },
161 { OPT, "events/i2c/smbus_write/enable" },
162 { OPT, "events/i2c/smbus_result/enable" },
163 { OPT, "events/i2c/smbus_reply/enable" },
Michael Wright43fb6782016-08-18 19:56:43 +0100164 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700165 { "freq", "CPU Frequency", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800166 { REQ, "events/power/cpu_frequency/enable" },
167 { OPT, "events/power/clock_set_rate/enable" },
Kevin DuBois062e0b92017-11-03 15:44:08 -0700168 { OPT, "events/power/clock_disable/enable" },
169 { OPT, "events/power/clock_enable/enable" },
Wei Wang53305dd2018-02-22 11:40:07 -0800170 { OPT, "events/clk/clk_set_rate/enable" },
171 { OPT, "events/clk/clk_disable/enable" },
172 { OPT, "events/clk/clk_enable/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800173 { OPT, "events/power/cpu_frequency_limits/enable" },
Carmen Jackson5ab84322019-08-08 14:35:47 -0700174 { OPT, "events/power/suspend_resume/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800175 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700176 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800177 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800178 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700179 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800180 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800181 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700182 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800183 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
184 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
185 { OPT, "events/f2fs/f2fs_write_begin/enable" },
186 { OPT, "events/f2fs/f2fs_write_end/enable" },
187 { OPT, "events/ext4/ext4_da_write_begin/enable" },
188 { OPT, "events/ext4/ext4_da_write_end/enable" },
189 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
190 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
191 { REQ, "events/block/block_rq_issue/enable" },
192 { REQ, "events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800193 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700194 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800195 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700196 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700197 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800198 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800199 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700200 { "sync", "Synchronization", 0, {
Jesse Halla978cef2019-02-25 16:24:10 -0800201 // linux kernel < 4.9
Jesse Hallae001a32018-05-15 12:02:15 -0700202 { OPT, "events/sync/enable" },
Jesse Halla978cef2019-02-25 16:24:10 -0800203 // linux kernel == 4.9.x
Jesse Hallae001a32018-05-15 12:02:15 -0700204 { OPT, "events/fence/enable" },
Jesse Halla978cef2019-02-25 16:24:10 -0800205 // linux kernel > 4.9
206 { OPT, "events/dma_fence/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800207 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700208 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800209 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800210 } },
Colin Cross580407f2014-08-18 15:22:13 -0700211 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800212 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
213 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
214 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
215 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Carmen Jackson7a23eb72018-07-02 13:14:56 -0700216 { OPT, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700217 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800218 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800219 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800220 } },
Scott Bauerae473362015-06-08 16:32:36 -0700221 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800222 { REQ, "events/binder/binder_transaction/enable" },
223 { REQ, "events/binder/binder_transaction_received/enable" },
Mika Raento80c3e5d2018-06-25 16:47:24 +0100224 { REQ, "events/binder/binder_transaction_alloc_buf/enable" },
Martijn Coenen7f3d7a22017-05-26 09:50:55 -0700225 { OPT, "events/binder/binder_set_priority/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700226 } },
227 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800228 { OPT, "events/binder/binder_lock/enable" },
229 { OPT, "events/binder/binder_locked/enable" },
230 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700231 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200232 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800233 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200234 } },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700235 { "memory", "Memory", 0, {
236 { OPT, "events/kmem/rss_stat/enable" },
237 { OPT, "events/kmem/ion_heap_grow/enable" },
238 { OPT, "events/kmem/ion_heap_shrink/enable" },
239 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800240};
241
Wei Wang16a63a42018-09-21 15:47:45 -0700242struct TracingVendorCategory {
243 // The name identifying the category.
244 std::string name;
245
246 // A longer description of the category.
247 std::string description;
248
249 // If the category is enabled through command.
250 bool enabled;
251
252 TracingVendorCategory(string &&name, string &&description, bool enabled)
253 : name(std::move(name))
254 , description(std::move(description))
255 , enabled(enabled)
256 {}
257};
258
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800259/* Command line options */
260static int g_traceDurationSeconds = 5;
261static bool g_traceOverwrite = false;
262static int g_traceBufferSizeKB = 2048;
263static bool g_compress = false;
264static bool g_nohup = false;
265static int g_initialSleepSecs = 0;
Yi Kong19d5c002018-07-20 13:39:55 -0700266static const char* g_categoriesFile = nullptr;
267static const char* g_kernelTraceFuncs = nullptr;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700268static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700269static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800270
271/* Global state */
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700272static bool g_tracePdx = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800273static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700274static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800275static std::string g_traceFolder;
Wei Wang16a63a42018-09-21 15:47:45 -0700276static sp<IAtraceDevice> g_atraceHal;
277static std::vector<TracingVendorCategory> g_vendorCategories;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800278
279/* Sys file paths */
280static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800281 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800282
283static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800284 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800285
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700286#if 0
287// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700288static const char* k_traceCmdlineSizePath =
289 "saved_cmdlines_size";
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700290#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700291
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800292static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800293 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800294
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700295static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800296 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700297
298static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800299 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700300
John Recke757b1c2018-06-28 12:24:33 -0700301static const char* k_recordTgidPath =
302 "options/record-tgid";
303
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700304static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800305 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700306
307static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800308 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700309
310static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800311 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700312
313static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800314 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700315
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700316static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800317 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700318
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800319static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800320 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800321
322static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800323 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800324
Martijn Coenend9535872015-11-26 10:00:55 +0100325static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800326 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100327
John Reck469a1942015-03-26 15:31:35 -0700328static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800329 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700330
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800331// Check whether a file exists.
332static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800333 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800334}
335
336// Check whether a file is writable.
337static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800338 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800339}
340
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700341// Truncate a file.
342static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800343{
Jamie Gennis43122e72013-03-21 14:06:31 -0700344 // This uses creat rather than truncate because some of the debug kernel
345 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
346 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800347 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700348 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800349 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700350 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700351 return false;
352 }
353
Jamie Gennis43122e72013-03-21 14:06:31 -0700354 close(traceFD);
355
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700356 return true;
357}
358
359static bool _writeStr(const char* filename, const char* str, int flags)
360{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800361 std::string fullFilename = g_traceFolder + filename;
362 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800363 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800364 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800365 strerror(errno), errno);
366 return false;
367 }
368
369 bool ok = true;
370 ssize_t len = strlen(str);
371 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800372 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800373 strerror(errno), errno);
374 ok = false;
375 }
376
377 close(fd);
378
379 return ok;
380}
381
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700382// Write a string to a file, returning true if the write was successful.
383static bool writeStr(const char* filename, const char* str)
384{
385 return _writeStr(filename, str, O_WRONLY);
386}
387
388// Append a string to a file, returning true if the write was successful.
389static bool appendStr(const char* filename, const char* str)
390{
391 return _writeStr(filename, str, O_APPEND|O_WRONLY);
392}
393
John Reck469a1942015-03-26 15:31:35 -0700394static void writeClockSyncMarker()
395{
396 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200397 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800398 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200399 if (fd == -1) {
400 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
401 strerror(errno), errno);
402 return;
403 }
John Reck469a1942015-03-26 15:31:35 -0700404 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200405
406 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
407 if (write(fd, buffer, len) != len) {
408 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
409 }
410
411 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
412 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
413 if (write(fd, buffer, len) != len) {
414 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
415 }
416
417 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700418}
419
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800420// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
421// file.
422static bool setKernelOptionEnable(const char* filename, bool enable)
423{
424 return writeStr(filename, enable ? "1" : "0");
425}
426
427// Check whether the category is supported on the device with the current
428// rootness. A category is supported only if all its required /sys/ files are
429// writable and if enabling the category will enable one or more tracing tags
430// or /sys/ files.
431static bool isCategorySupported(const TracingCategory& category)
432{
sergeyvdb404152016-05-02 19:26:07 -0700433 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700434 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700435 }
436
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700437 if (strcmp(category.name, k_pdxServiceCategory) == 0) {
438 return true;
439 }
440
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800441 bool ok = category.tags != 0;
442 for (int i = 0; i < MAX_SYS_FILES; i++) {
443 const char* path = category.sysfiles[i].path;
444 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700445 if (path != nullptr) {
Carmen Jackson5bbc9a22018-12-06 13:47:18 -0800446 if (fileIsWritable(path)) {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800447 ok = true;
Carmen Jackson5bbc9a22018-12-06 13:47:18 -0800448 } else if (req) {
449 return false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800450 }
451 }
452 }
453 return ok;
454}
455
456// Check whether the category would be supported on the device if the user
457// were root. This function assumes that root is able to write to any file
458// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700459// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800460static bool isCategorySupportedForRoot(const TracingCategory& category)
461{
462 bool ok = category.tags != 0;
463 for (int i = 0; i < MAX_SYS_FILES; i++) {
464 const char* path = category.sysfiles[i].path;
465 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700466 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800467 if (req) {
468 if (!fileExists(path)) {
469 return false;
470 } else {
471 ok = true;
472 }
473 } else {
474 ok |= fileExists(path);
475 }
476 }
477 }
478 return ok;
479}
480
481// Enable or disable overwriting of the kernel trace buffers. Disabling this
482// will cause tracing to stop once the trace buffers have filled up.
483static bool setTraceOverwriteEnable(bool enable)
484{
485 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
486}
487
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700488// Set the user initiated trace property
489static bool setUserInitiatedTraceProperty(bool enable)
490{
491 if (!android::base::SetProperty(k_userInitiatedTraceProperty, enable ? "1" : "")) {
492 fprintf(stderr, "error setting user initiated strace system property\n");
493 return false;
494 }
495 return true;
496}
497
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800498// Enable or disable kernel tracing.
499static bool setTracingEnabled(bool enable)
500{
501 return setKernelOptionEnable(k_tracingOnPath, enable);
502}
503
504// Clear the contents of the kernel trace.
505static bool clearTrace()
506{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700507 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800508}
509
510// Set the size of the kernel's trace buffer in kilobytes.
511static bool setTraceBufferSizeKB(int size)
512{
513 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800514 if (size < 1) {
515 size = 1;
516 }
517 snprintf(str, 32, "%d", size);
518 return writeStr(k_traceBufferSizePath, str);
519}
520
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700521#if 0
522// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700523// Set the default size of cmdline hashtable
524static bool setCmdlineSize()
525{
Joel Fernandesce964f22017-06-06 12:20:29 -0700526 if (fileExists(k_traceCmdlineSizePath)) {
527 return writeStr(k_traceCmdlineSizePath, "8192");
528 }
529 return true;
Joel Fernandesed80bd02017-06-02 10:19:28 -0700530}
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700531#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700532
Carmen Jacksonea826792017-05-05 11:42:32 -0700533// Set the clock to the best available option while tracing. Use 'boot' if it's
534// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700535// Any write to the trace_clock sysfs file will reset the buffer, so only
536// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700537static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800538{
Carmen Jacksonea826792017-05-05 11:42:32 -0700539 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
540 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
541 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700542
Carmen Jacksonea826792017-05-05 11:42:32 -0700543 std::string newClock;
544 if (clockStr.find("boot") != std::string::npos) {
545 newClock = "boot";
546 } else if (clockStr.find("mono") != std::string::npos) {
547 newClock = "mono";
548 } else {
549 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700550 }
551
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700552 size_t begin = clockStr.find('[') + 1;
553 size_t end = clockStr.find(']');
Carmen Jacksonea826792017-05-05 11:42:32 -0700554 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
555 return true;
556 }
557 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800558}
559
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700560static bool setPrintTgidEnableIfPresent(bool enable)
561{
John Reckedbf9ec2018-06-29 11:15:17 -0700562 // Pre-4.13 this was options/print-tgid as an android-specific option.
563 // In 4.13+ this is an upstream option called options/record-tgid
564 // Both options produce the same ftrace format change
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700565 if (fileExists(k_printTgidPath)) {
566 return setKernelOptionEnable(k_printTgidPath, enable);
567 }
John Recke757b1c2018-06-28 12:24:33 -0700568 if (fileExists(k_recordTgidPath)) {
569 return setKernelOptionEnable(k_recordTgidPath, enable);
570 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700571 return true;
572}
573
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800574// Set the trace tags that userland tracing uses, and poke the running
575// processes to pick up the new value.
576static bool setTagsProperty(uint64_t tags)
577{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700578 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
579 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800580 fprintf(stderr, "error setting trace tags system property\n");
581 return false;
582 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700583 return true;
584}
585
sergeyv4144eff2016-04-28 11:40:04 -0700586static void clearAppProperties()
587{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700588 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700589 fprintf(stderr, "failed to clear system property: %s",
590 k_traceAppsNumberProperty);
591 }
592}
593
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700594// Set the system property that indicates which apps should perform
595// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700596static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700597{
sergeyv4144eff2016-04-28 11:40:04 -0700598 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700599 char* start = cmdline;
Yi Kong19d5c002018-07-20 13:39:55 -0700600 while (start != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700601 char* end = strchr(start, ',');
Yi Kong19d5c002018-07-20 13:39:55 -0700602 if (end != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700603 *end = '\0';
604 end++;
605 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700606 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
607 if (!android::base::SetProperty(key, start)) {
608 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700609 clearAppProperties();
610 return false;
611 }
612 start = end;
613 i++;
614 }
615
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700616 std::string value = android::base::StringPrintf("%d", i);
617 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
618 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700619 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700620 return false;
621 }
622 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800623}
624
625// Disable all /sys/ enable files.
626static bool disableKernelTraceEvents() {
627 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700628 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800629 const TracingCategory &c = k_categories[i];
630 for (int j = 0; j < MAX_SYS_FILES; j++) {
631 const char* path = c.sysfiles[j].path;
Yi Kong19d5c002018-07-20 13:39:55 -0700632 if (path != nullptr && fileIsWritable(path)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800633 ok &= setKernelOptionEnable(path, false);
634 }
635 }
636 }
637 return ok;
638}
639
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700640// Verify that the comma separated list of functions are being traced by the
641// kernel.
642static bool verifyKernelTraceFuncs(const char* funcs)
643{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100644 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800645 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100646 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700647 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100648 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700649 }
650
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100651 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700652
653 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100654 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700655 bool ok = true;
656 char* myFuncs = strdup(funcs);
657 char* func = strtok(myFuncs, ",");
658 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100659 if (!strchr(func, '*')) {
660 String8 fancyFunc = String8::format("\n%s\n", func);
661 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
662 if (!found || func[0] == '\0') {
663 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
664 "to trace.\n", func);
665 ok = false;
666 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700667 }
Yi Kong19d5c002018-07-20 13:39:55 -0700668 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700669 }
670 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700671 return ok;
672}
673
674// Set the comma separated list of functions that the kernel is to trace.
675static bool setKernelTraceFuncs(const char* funcs)
676{
677 bool ok = true;
678
Yi Kong19d5c002018-07-20 13:39:55 -0700679 if (funcs == nullptr || funcs[0] == '\0') {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700680 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700681 if (fileIsWritable(k_currentTracerPath)) {
682 ok &= writeStr(k_currentTracerPath, "nop");
683 }
684 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700685 ok &= truncateFile(k_ftraceFilterPath);
686 }
687 } else {
688 // Enable kernel function tracing.
689 ok &= writeStr(k_currentTracerPath, "function_graph");
690 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
691 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
692 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
693 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
694
695 // Set the requested filter functions.
696 ok &= truncateFile(k_ftraceFilterPath);
697 char* myFuncs = strdup(funcs);
698 char* func = strtok(myFuncs, ",");
699 while (func) {
700 ok &= appendStr(k_ftraceFilterPath, func);
Yi Kong19d5c002018-07-20 13:39:55 -0700701 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700702 }
703 free(myFuncs);
704
705 // Verify that the set functions are being traced.
706 if (ok) {
707 ok &= verifyKernelTraceFuncs(funcs);
708 }
709 }
710
711 return ok;
712}
713
Wei Wang16a63a42018-09-21 15:47:45 -0700714static bool setCategoryEnable(const char* name)
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900715{
Wei Wang16a63a42018-09-21 15:47:45 -0700716 bool vendor_found = false;
717 for (auto &c : g_vendorCategories) {
718 if (strcmp(name, c.name.c_str()) == 0) {
719 c.enabled = true;
720 vendor_found = true;
721 }
722 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700723 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900724 const TracingCategory& c = k_categories[i];
725 if (strcmp(name, c.name) == 0) {
726 if (isCategorySupported(c)) {
Wei Wang16a63a42018-09-21 15:47:45 -0700727 g_categoryEnables[i] = true;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900728 return true;
729 } else {
730 if (isCategorySupportedForRoot(c)) {
731 fprintf(stderr, "error: category \"%s\" requires root "
732 "privileges.\n", name);
733 } else {
734 fprintf(stderr, "error: category \"%s\" is not supported "
735 "on this device.\n", name);
736 }
737 return false;
738 }
739 }
740 }
Wei Wang16a63a42018-09-21 15:47:45 -0700741 if (vendor_found) {
742 return true;
743 }
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900744 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
745 return false;
746}
747
748static bool setCategoriesEnableFromFile(const char* categories_file)
749{
750 if (!categories_file) {
751 return true;
752 }
Yi Kong19d5c002018-07-20 13:39:55 -0700753 Tokenizer* tokenizer = nullptr;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900754 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
755 return false;
756 }
757 bool ok = true;
758 while (!tokenizer->isEol()) {
759 String8 token = tokenizer->nextToken(" ");
760 if (token.isEmpty()) {
761 tokenizer->skipDelimiters(" ");
762 continue;
763 }
Wei Wang16a63a42018-09-21 15:47:45 -0700764 ok &= setCategoryEnable(token.string());
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900765 }
766 delete tokenizer;
767 return ok;
768}
769
Hector Dearman11845782018-03-08 14:35:44 +0000770static bool setUpUserspaceTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800771{
772 bool ok = true;
773
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800774 // Set up the tags property.
775 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700776 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800777 if (g_categoryEnables[i]) {
778 const TracingCategory &c = k_categories[i];
779 tags |= c.tags;
780 }
781 }
sergeyvdb404152016-05-02 19:26:07 -0700782
783 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700784 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700785 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
786 coreServicesTagEnabled = g_categoryEnables[i];
787 }
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700788
789 // Set whether to poke PDX services in this session.
790 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
791 g_tracePdx = g_categoryEnables[i];
792 }
sergeyvdb404152016-05-02 19:26:07 -0700793 }
794
795 std::string packageList(g_debugAppCmdLine);
796 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700797 if (!packageList.empty()) {
798 packageList += ",";
799 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700800 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700801 }
Dan Austin09a79872016-05-31 13:27:03 -0700802 ok &= setAppCmdlineProperty(&packageList[0]);
Florian Mayer6263b582019-12-10 13:28:45 +0000803 ok &= setTagsProperty(tags);
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700804 if (g_tracePdx) {
805 ok &= ServiceUtility::PokeServices();
806 }
807
Hector Dearman11845782018-03-08 14:35:44 +0000808 return ok;
809}
810
811static void cleanUpUserspaceTracing()
812{
813 setTagsProperty(0);
814 clearAppProperties();
Hector Dearman11845782018-03-08 14:35:44 +0000815
816 if (g_tracePdx) {
817 ServiceUtility::PokeServices();
818 }
819}
820
821
822// Set all the kernel tracing settings to the desired state for this trace
823// capture.
824static bool setUpKernelTracing()
825{
826 bool ok = true;
827
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700828 ok &= setUserInitiatedTraceProperty(true);
829
Hector Dearman11845782018-03-08 14:35:44 +0000830 // Set up the tracing options.
831 ok &= setCategoriesEnableFromFile(g_categoriesFile);
832 ok &= setTraceOverwriteEnable(g_traceOverwrite);
833 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
834 // TODO: Re-enable after stabilization
835 //ok &= setCmdlineSize();
836 ok &= setClock();
837 ok &= setPrintTgidEnableIfPresent(true);
838 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
839
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800840 // Disable all the sysfs enables. This is done as a separate loop from
841 // the enables to allow the same enable to exist in multiple categories.
842 ok &= disableKernelTraceEvents();
843
844 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700845 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800846 if (g_categoryEnables[i]) {
847 const TracingCategory &c = k_categories[i];
848 for (int j = 0; j < MAX_SYS_FILES; j++) {
849 const char* path = c.sysfiles[j].path;
850 bool required = c.sysfiles[j].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700851 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800852 if (fileIsWritable(path)) {
853 ok &= setKernelOptionEnable(path, true);
854 } else if (required) {
855 fprintf(stderr, "error writing file %s\n", path);
856 ok = false;
857 }
858 }
859 }
860 }
861 }
862
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800863 return ok;
864}
865
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700866// Reset all the kernel tracing settings to their default state.
Hector Dearman11845782018-03-08 14:35:44 +0000867static void cleanUpKernelTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800868{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800869 // Disable all tracing that we're able to.
870 disableKernelTraceEvents();
871
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800872 // Set the options back to their defaults.
873 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700874 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700875 setPrintTgidEnableIfPresent(false);
Yi Kong19d5c002018-07-20 13:39:55 -0700876 setKernelTraceFuncs(nullptr);
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700877 setUserInitiatedTraceProperty(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700878}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800879
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700880// Enable tracing in the kernel.
881static bool startTrace()
882{
883 return setTracingEnabled(true);
884}
885
886// Disable tracing in the kernel.
887static void stopTrace()
888{
889 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800890}
891
Martijn Coenend9535872015-11-26 10:00:55 +0100892// Read data from the tracing pipe and forward to stdout
893static void streamTrace()
894{
895 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800896 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100897 if (traceFD == -1) {
898 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
899 strerror(errno), errno);
900 return;
901 }
902 while (!g_traceAborted) {
903 ssize_t bytes_read = read(traceFD, trace_data, 4096);
904 if (bytes_read > 0) {
905 write(STDOUT_FILENO, trace_data, bytes_read);
906 fflush(stdout);
907 } else {
908 if (!g_traceAborted) {
909 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
910 bytes_read, errno, strerror(errno));
911 }
912 break;
913 }
914 }
915}
916
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800917// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700918static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800919{
John Reck6c8ac922016-03-28 11:25:30 -0700920 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800921 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800922 if (traceFD == -1) {
923 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
924 strerror(errno), errno);
925 return;
926 }
927
928 if (g_compress) {
929 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800930 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700931
932 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800933 if (result != Z_OK) {
934 fprintf(stderr, "error initializing zlib: %d\n", result);
935 close(traceFD);
936 return;
937 }
938
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700939 constexpr size_t bufSize = 64*1024;
940 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
941 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
942 if (!in || !out) {
943 fprintf(stderr, "couldn't allocate buffers\n");
944 close(traceFD);
945 return;
946 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800947
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700948 int flush = Z_NO_FLUSH;
949
950 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800951 zs.avail_out = bufSize;
952
953 do {
954
955 if (zs.avail_in == 0) {
956 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700957 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800958 if (result < 0) {
959 fprintf(stderr, "error reading trace: %s (%d)\n",
960 strerror(errno), errno);
961 result = Z_STREAM_END;
962 break;
963 } else if (result == 0) {
964 flush = Z_FINISH;
965 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700966 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800967 zs.avail_in = result;
968 }
969 }
970
971 if (zs.avail_out == 0) {
972 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700973 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800974 if ((size_t)result < bufSize) {
975 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
976 strerror(errno), errno);
977 result = Z_STREAM_END; // skip deflate error message
978 zs.avail_out = bufSize; // skip the final write
979 break;
980 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700981 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800982 zs.avail_out = bufSize;
983 }
984
985 } while ((result = deflate(&zs, flush)) == Z_OK);
986
987 if (result != Z_STREAM_END) {
988 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
989 }
990
991 if (zs.avail_out < bufSize) {
992 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -0700993 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800994 if ((size_t)result < bytes) {
995 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
996 strerror(errno), errno);
997 }
998 }
999
1000 result = deflateEnd(&zs);
1001 if (result != Z_OK) {
1002 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1003 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001004 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001005 char buf[4096];
1006 ssize_t rc;
1007 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1008 if (!android::base::WriteFully(outFd, buf, rc)) {
1009 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1010 break;
1011 }
1012 }
1013 if (rc == -1) {
1014 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001015 }
1016 }
1017
1018 close(traceFD);
1019}
1020
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001021static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001022{
1023 if (!g_nohup) {
1024 g_traceAborted = true;
1025 }
1026}
1027
1028static void registerSigHandler()
1029{
1030 struct sigaction sa;
1031 sigemptyset(&sa.sa_mask);
1032 sa.sa_flags = 0;
1033 sa.sa_handler = handleSignal;
Yi Kong19d5c002018-07-20 13:39:55 -07001034 sigaction(SIGHUP, &sa, nullptr);
1035 sigaction(SIGINT, &sa, nullptr);
1036 sigaction(SIGQUIT, &sa, nullptr);
1037 sigaction(SIGTERM, &sa, nullptr);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001038}
1039
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001040static void listSupportedCategories()
1041{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001042 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001043 const TracingCategory& c = k_categories[i];
1044 if (isCategorySupported(c)) {
1045 printf(" %10s - %s\n", c.name, c.longname);
1046 }
1047 }
Wei Wang16a63a42018-09-21 15:47:45 -07001048 for (const auto &c : g_vendorCategories) {
1049 printf(" %10s - %s (HAL)\n", c.name.c_str(), c.description.c_str());
1050 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001051}
1052
1053// Print the command usage help to stderr.
1054static void showHelp(const char *cmd)
1055{
1056 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1057 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001058 " -a appname enable app-level tracing for a comma "
Daniel Colascione519a0792018-02-09 20:05:39 -08001059 "separated list of cmdlines; * is a wildcard matching any process\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001060 " -b N use a trace buffer size of N KB\n"
1061 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001062 " -f filename use the categories written in a file as space-separated\n"
1063 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001064 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001065 " -n ignore signals\n"
1066 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001067 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001068 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001069 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001070 " --async_dump dump the current contents of circular trace buffer\n"
1071 " --async_stop stop tracing and dump the current contents of circular\n"
1072 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001073 " --stream stream trace to stdout as it enters the trace buffer\n"
1074 " Note: this can take significant CPU time, and is best\n"
1075 " used for measuring things that are not affected by\n"
1076 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001077 " --list_categories\n"
1078 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001079 " -o filename write the trace to the specified file instead\n"
1080 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001081 );
1082}
1083
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001084bool findTraceFiles()
1085{
1086 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1087 static const std::string tracefs_path = "/sys/kernel/tracing/";
1088 static const std::string trace_file = "trace_marker";
1089
1090 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1091 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1092
1093 if (!tracefs && !debugfs) {
1094 fprintf(stderr, "Error: Did not find trace folder\n");
1095 return false;
1096 }
1097
1098 if (tracefs) {
1099 g_traceFolder = tracefs_path;
1100 } else {
1101 g_traceFolder = debugfs_path;
1102 }
1103
1104 return true;
1105}
1106
Wei Wang16a63a42018-09-21 15:47:45 -07001107void initVendorCategories()
1108{
1109 g_atraceHal = IAtraceDevice::getService();
1110
1111 if (g_atraceHal == nullptr) {
1112 // No atrace HAL
1113 return;
1114 }
1115
1116 Return<void> ret = g_atraceHal->listCategories(
1117 [](const auto& list) {
1118 g_vendorCategories.reserve(list.size());
1119 for (const auto& category : list) {
1120 g_vendorCategories.emplace_back(category.name, category.description, false);
1121 }
1122 });
1123 if (!ret.isOk()) {
1124 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1125 }
1126}
1127
1128static bool setUpVendorTracing()
1129{
1130 if (g_atraceHal == nullptr) {
1131 // No atrace HAL
1132 return true;
1133 }
1134
1135 std::vector<hidl_string> categories;
1136 for (const auto &c : g_vendorCategories) {
1137 if (c.enabled) {
1138 categories.emplace_back(c.name);
1139 }
1140 }
1141
1142 if (!categories.size()) {
1143 return true;
1144 }
1145
1146 auto ret = g_atraceHal->enableCategories(categories);
1147 if (!ret.isOk()) {
1148 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1149 return false;
1150 } else if (ret != Status::SUCCESS) {
1151 fprintf(stderr, "calling atrace HAL failed: %s\n", toString(ret).c_str());
1152 return false;
1153 }
1154 return true;
1155}
1156
1157static bool cleanUpVendorTracing()
1158{
1159 if (g_atraceHal == nullptr) {
1160 // No atrace HAL
1161 return true;
1162 }
1163
1164 if (!g_vendorCategories.size()) {
1165 // No vendor categories
1166 return true;
1167 }
1168
1169 auto ret = g_atraceHal->disableAllCategories();
1170 if (!ret.isOk()) {
1171 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1172 return false;
1173 } else if (ret != Status::SUCCESS) {
1174 fprintf(stderr, "calling atrace HAL failed: %s\n", toString(ret).c_str());
1175 return false;
1176 }
1177 return true;
1178}
1179
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001180int main(int argc, char **argv)
1181{
1182 bool async = false;
1183 bool traceStart = true;
1184 bool traceStop = true;
1185 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001186 bool traceStream = false;
Hector Dearman11845782018-03-08 14:35:44 +00001187 bool onlyUserspace = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001188
1189 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1190 showHelp(argv[0]);
1191 exit(0);
1192 }
1193
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001194 if (!findTraceFiles()) {
1195 fprintf(stderr, "No trace folder found\n");
1196 exit(-1);
1197 }
1198
Wei Wang16a63a42018-09-21 15:47:45 -07001199 initVendorCategories();
1200
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001201 for (;;) {
1202 int ret;
1203 int option_index = 0;
1204 static struct option long_options[] = {
Yi Kong19d5c002018-07-20 13:39:55 -07001205 {"async_start", no_argument, nullptr, 0 },
1206 {"async_stop", no_argument, nullptr, 0 },
1207 {"async_dump", no_argument, nullptr, 0 },
1208 {"only_userspace", no_argument, nullptr, 0 },
1209 {"list_categories", no_argument, nullptr, 0 },
1210 {"stream", no_argument, nullptr, 0 },
1211 {nullptr, 0, nullptr, 0 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001212 };
1213
John Reck40b26b42016-03-30 09:44:36 -07001214 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001215 long_options, &option_index);
1216
1217 if (ret < 0) {
1218 for (int i = optind; i < argc; i++) {
Wei Wang16a63a42018-09-21 15:47:45 -07001219 if (!setCategoryEnable(argv[i])) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001220 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1221 exit(1);
1222 }
1223 }
1224 break;
1225 }
1226
1227 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001228 case 'a':
1229 g_debugAppCmdLine = optarg;
1230 break;
1231
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001232 case 'b':
1233 g_traceBufferSizeKB = atoi(optarg);
1234 break;
1235
1236 case 'c':
1237 g_traceOverwrite = true;
1238 break;
1239
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001240 case 'f':
1241 g_categoriesFile = optarg;
1242 break;
1243
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001244 case 'k':
1245 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001246 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001247
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001248 case 'n':
1249 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001250 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001251
1252 case 's':
1253 g_initialSleepSecs = atoi(optarg);
1254 break;
1255
1256 case 't':
1257 g_traceDurationSeconds = atoi(optarg);
1258 break;
1259
1260 case 'z':
1261 g_compress = true;
1262 break;
1263
John Reck40b26b42016-03-30 09:44:36 -07001264 case 'o':
1265 g_outputFile = optarg;
1266 break;
1267
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001268 case 0:
1269 if (!strcmp(long_options[option_index].name, "async_start")) {
1270 async = true;
1271 traceStop = false;
1272 traceDump = false;
1273 g_traceOverwrite = true;
1274 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1275 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001276 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001277 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1278 async = true;
1279 traceStart = false;
1280 traceStop = false;
Hector Dearman11845782018-03-08 14:35:44 +00001281 } else if (!strcmp(long_options[option_index].name, "only_userspace")) {
1282 onlyUserspace = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001283 } else if (!strcmp(long_options[option_index].name, "stream")) {
1284 traceStream = true;
1285 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001286 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1287 listSupportedCategories();
1288 exit(0);
1289 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001290 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001291
1292 default:
1293 fprintf(stderr, "\n");
1294 showHelp(argv[0]);
1295 exit(-1);
1296 break;
1297 }
1298 }
1299
Hector Dearman11845782018-03-08 14:35:44 +00001300 if (onlyUserspace) {
1301 if (!async || !(traceStart || traceStop)) {
1302 fprintf(stderr, "--only_userspace can only be used with "
1303 "--async_start or --async_stop\n");
1304 exit(1);
1305 }
1306 }
1307
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001308 registerSigHandler();
1309
1310 if (g_initialSleepSecs > 0) {
1311 sleep(g_initialSleepSecs);
1312 }
1313
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001314 bool ok = true;
Hector Dearman11845782018-03-08 14:35:44 +00001315
Wei Wang5b73b742018-03-08 13:33:12 -08001316 if (traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001317 ok &= setUpUserspaceTracing();
1318 }
1319
1320 if (ok && traceStart && !onlyUserspace) {
1321 ok &= setUpKernelTracing();
Wei Wang16a63a42018-09-21 15:47:45 -07001322 ok &= setUpVendorTracing();
Wei Wang5b73b742018-03-08 13:33:12 -08001323 ok &= startTrace();
1324 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001325
1326 if (ok && traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001327
1328 if (!traceStream && !onlyUserspace) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001329 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001330 fflush(stdout);
1331 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001332
1333 // We clear the trace after starting it because tracing gets enabled for
1334 // each CPU individually in the kernel. Having the beginning of the trace
1335 // contain entries from only one CPU can cause "begin" entries without a
1336 // matching "end" entry to show up if a task gets migrated from one CPU to
1337 // another.
Hector Dearman11845782018-03-08 14:35:44 +00001338 if (!onlyUserspace)
1339 ok = clearTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001340
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001341 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001342 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001343 // Sleep to allow the trace to be captured.
1344 struct timespec timeLeft;
1345 timeLeft.tv_sec = g_traceDurationSeconds;
1346 timeLeft.tv_nsec = 0;
1347 do {
1348 if (g_traceAborted) {
1349 break;
1350 }
1351 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1352 }
Martijn Coenend9535872015-11-26 10:00:55 +01001353
1354 if (traceStream) {
1355 streamTrace();
1356 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001357 }
1358
1359 // Stop the trace and restore the default settings.
Hector Dearman11845782018-03-08 14:35:44 +00001360 if (traceStop && !onlyUserspace)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001361 stopTrace();
1362
Hector Dearman11845782018-03-08 14:35:44 +00001363 if (ok && traceDump && !onlyUserspace) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001364 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001365 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001366 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001367 int outFd = STDOUT_FILENO;
1368 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001369 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001370 }
1371 if (outFd == -1) {
1372 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1373 } else {
1374 dprintf(outFd, "TRACE:\n");
1375 dumpTrace(outFd);
1376 if (g_outputFile) {
1377 close(outFd);
1378 }
1379 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001380 } else {
1381 printf("\ntrace aborted.\n");
1382 fflush(stdout);
1383 }
1384 clearTrace();
1385 } else if (!ok) {
1386 fprintf(stderr, "unable to start tracing\n");
1387 }
1388
1389 // Reset the trace buffer size to 1.
Hector Dearman11845782018-03-08 14:35:44 +00001390 if (traceStop) {
1391 cleanUpUserspaceTracing();
Hector Dearmanada0a4a2019-04-09 14:13:14 +01001392 if (!onlyUserspace) {
1393 cleanUpVendorTracing();
Hector Dearman11845782018-03-08 14:35:44 +00001394 cleanUpKernelTracing();
Hector Dearmanada0a4a2019-04-09 14:13:14 +01001395 }
Hector Dearman11845782018-03-08 14:35:44 +00001396 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001397
1398 return g_traceAborted ? 1 : 0;
1399}