blob: 90a5a2af2ba693c5279568e02922e01ca74e92fe [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, { } },
Chienyuan Huang53a8b412020-08-20 08:42:31 +0000127 { "sysprop", "System Property", ATRACE_TAG_SYSPROP, { } },
sergeyvdb404152016-05-02 19:26:07 -0700128 { k_coreServiceCategory, "Core services", 0, { } },
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700129 { k_pdxServiceCategory, "PDX services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700130 { "sched", "CPU Scheduling", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800131 { REQ, "events/sched/sched_switch/enable" },
132 { REQ, "events/sched/sched_wakeup/enable" },
Joel Fernandesee593e22017-06-04 13:05:59 -0700133 { OPT, "events/sched/sched_waking/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800134 { OPT, "events/sched/sched_blocked_reason/enable" },
135 { OPT, "events/sched/sched_cpu_hotplug/enable" },
Wei Wangca49dfc2018-05-03 15:45:20 -0700136 { OPT, "events/sched/sched_pi_setprio/enable" },
Carmen Jackson63ea2912019-04-26 10:41:00 -0700137 { OPT, "events/sched/sched_process_exit/enable" },
Joel Fernandes4dfca7c2017-06-15 16:53:52 -0700138 { OPT, "events/cgroup/enable" },
Carmen Jackson63ea2912019-04-26 10:41:00 -0700139 { OPT, "events/oom/oom_score_adj_update/enable" },
140 { OPT, "events/task/task_rename/enable" },
141 { OPT, "events/task/task_newtask/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800142 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700143 { "irq", "IRQ Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800144 { REQ, "events/irq/enable" },
145 { OPT, "events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700146 } },
Joel Fernandes6ccad102017-08-31 08:35:05 -0700147 { "irqoff", "IRQ-disabled code section tracing", 0, {
148 { REQ, "events/preemptirq/irq_enable/enable" },
149 { REQ, "events/preemptirq/irq_disable/enable" },
150 } },
151 { "preemptoff", "Preempt-disabled code section tracing", 0, {
152 { REQ, "events/preemptirq/preempt_enable/enable" },
153 { REQ, "events/preemptirq/preempt_disable/enable" },
154 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100155 { "i2c", "I2C Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800156 { REQ, "events/i2c/enable" },
157 { REQ, "events/i2c/i2c_read/enable" },
158 { REQ, "events/i2c/i2c_write/enable" },
159 { REQ, "events/i2c/i2c_result/enable" },
160 { REQ, "events/i2c/i2c_reply/enable" },
161 { OPT, "events/i2c/smbus_read/enable" },
162 { OPT, "events/i2c/smbus_write/enable" },
163 { OPT, "events/i2c/smbus_result/enable" },
164 { OPT, "events/i2c/smbus_reply/enable" },
Michael Wright43fb6782016-08-18 19:56:43 +0100165 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700166 { "freq", "CPU Frequency", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800167 { REQ, "events/power/cpu_frequency/enable" },
168 { OPT, "events/power/clock_set_rate/enable" },
Kevin DuBois062e0b92017-11-03 15:44:08 -0700169 { OPT, "events/power/clock_disable/enable" },
170 { OPT, "events/power/clock_enable/enable" },
Wei Wang53305dd2018-02-22 11:40:07 -0800171 { OPT, "events/clk/clk_set_rate/enable" },
172 { OPT, "events/clk/clk_disable/enable" },
173 { OPT, "events/clk/clk_enable/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800174 { OPT, "events/power/cpu_frequency_limits/enable" },
Carmen Jackson5ab84322019-08-08 14:35:47 -0700175 { OPT, "events/power/suspend_resume/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800176 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700177 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800178 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800179 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700180 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800181 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800182 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700183 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800184 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
185 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
186 { OPT, "events/f2fs/f2fs_write_begin/enable" },
187 { OPT, "events/f2fs/f2fs_write_end/enable" },
188 { OPT, "events/ext4/ext4_da_write_begin/enable" },
189 { OPT, "events/ext4/ext4_da_write_end/enable" },
190 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
191 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
192 { REQ, "events/block/block_rq_issue/enable" },
193 { REQ, "events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800194 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700195 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800196 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700197 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700198 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800199 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800200 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700201 { "sync", "Synchronization", 0, {
Jesse Halla978cef2019-02-25 16:24:10 -0800202 // linux kernel < 4.9
Jesse Hallae001a32018-05-15 12:02:15 -0700203 { OPT, "events/sync/enable" },
Jesse Halla978cef2019-02-25 16:24:10 -0800204 // linux kernel == 4.9.x
Jesse Hallae001a32018-05-15 12:02:15 -0700205 { OPT, "events/fence/enable" },
Jesse Halla978cef2019-02-25 16:24:10 -0800206 // linux kernel > 4.9
207 { OPT, "events/dma_fence/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800208 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700209 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800210 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800211 } },
Colin Cross580407f2014-08-18 15:22:13 -0700212 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800213 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
214 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
215 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
216 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Carmen Jackson7a23eb72018-07-02 13:14:56 -0700217 { OPT, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700218 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800219 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800220 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800221 } },
Scott Bauerae473362015-06-08 16:32:36 -0700222 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800223 { REQ, "events/binder/binder_transaction/enable" },
224 { REQ, "events/binder/binder_transaction_received/enable" },
Mika Raento80c3e5d2018-06-25 16:47:24 +0100225 { REQ, "events/binder/binder_transaction_alloc_buf/enable" },
Martijn Coenen7f3d7a22017-05-26 09:50:55 -0700226 { OPT, "events/binder/binder_set_priority/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700227 } },
228 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800229 { OPT, "events/binder/binder_lock/enable" },
230 { OPT, "events/binder/binder_locked/enable" },
231 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700232 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200233 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800234 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200235 } },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700236 { "memory", "Memory", 0, {
Collin Fijalkovich08e3f4a2020-03-30 16:20:24 -0700237 { OPT, "events/mm_event/mm_event_record/enable" },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700238 { OPT, "events/kmem/rss_stat/enable" },
239 { OPT, "events/kmem/ion_heap_grow/enable" },
240 { OPT, "events/kmem/ion_heap_shrink/enable" },
Ioannis Ilkos88a85f32020-04-23 22:43:40 +0100241 { OPT, "events/ion/ion_stat/enable" },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700242 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800243};
244
Wei Wang16a63a42018-09-21 15:47:45 -0700245struct TracingVendorCategory {
246 // The name identifying the category.
247 std::string name;
248
249 // A longer description of the category.
250 std::string description;
251
252 // If the category is enabled through command.
253 bool enabled;
254
255 TracingVendorCategory(string &&name, string &&description, bool enabled)
256 : name(std::move(name))
257 , description(std::move(description))
258 , enabled(enabled)
259 {}
260};
261
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800262/* Command line options */
263static int g_traceDurationSeconds = 5;
264static bool g_traceOverwrite = false;
265static int g_traceBufferSizeKB = 2048;
266static bool g_compress = false;
267static bool g_nohup = false;
268static int g_initialSleepSecs = 0;
Yi Kong19d5c002018-07-20 13:39:55 -0700269static const char* g_categoriesFile = nullptr;
270static const char* g_kernelTraceFuncs = nullptr;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700271static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700272static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800273
274/* Global state */
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700275static bool g_tracePdx = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800276static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700277static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800278static std::string g_traceFolder;
Wei Wang16a63a42018-09-21 15:47:45 -0700279static sp<IAtraceDevice> g_atraceHal;
280static std::vector<TracingVendorCategory> g_vendorCategories;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800281
282/* Sys file paths */
283static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800284 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800285
286static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800287 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800288
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700289#if 0
290// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700291static const char* k_traceCmdlineSizePath =
292 "saved_cmdlines_size";
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700293#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700294
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800295static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800296 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800297
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700298static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800299 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700300
301static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800302 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700303
John Recke757b1c2018-06-28 12:24:33 -0700304static const char* k_recordTgidPath =
305 "options/record-tgid";
306
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700307static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800308 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700309
310static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800311 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700312
313static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800314 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700315
316static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800317 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700318
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700319static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800320 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700321
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800322static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800323 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800324
325static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800326 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800327
Martijn Coenend9535872015-11-26 10:00:55 +0100328static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800329 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100330
John Reck469a1942015-03-26 15:31:35 -0700331static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800332 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700333
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800334// Check whether a file exists.
335static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800336 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800337}
338
339// Check whether a file is writable.
340static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800341 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800342}
343
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700344// Truncate a file.
345static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800346{
Jamie Gennis43122e72013-03-21 14:06:31 -0700347 // This uses creat rather than truncate because some of the debug kernel
348 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
349 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800350 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700351 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800352 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700353 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700354 return false;
355 }
356
Jamie Gennis43122e72013-03-21 14:06:31 -0700357 close(traceFD);
358
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700359 return true;
360}
361
362static bool _writeStr(const char* filename, const char* str, int flags)
363{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800364 std::string fullFilename = g_traceFolder + filename;
365 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800366 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800367 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800368 strerror(errno), errno);
369 return false;
370 }
371
372 bool ok = true;
373 ssize_t len = strlen(str);
374 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800375 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800376 strerror(errno), errno);
377 ok = false;
378 }
379
380 close(fd);
381
382 return ok;
383}
384
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700385// Write a string to a file, returning true if the write was successful.
386static bool writeStr(const char* filename, const char* str)
387{
388 return _writeStr(filename, str, O_WRONLY);
389}
390
391// Append a string to a file, returning true if the write was successful.
392static bool appendStr(const char* filename, const char* str)
393{
394 return _writeStr(filename, str, O_APPEND|O_WRONLY);
395}
396
John Reck469a1942015-03-26 15:31:35 -0700397static void writeClockSyncMarker()
398{
399 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200400 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800401 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200402 if (fd == -1) {
403 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
404 strerror(errno), errno);
405 return;
406 }
John Reck469a1942015-03-26 15:31:35 -0700407 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200408
409 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
410 if (write(fd, buffer, len) != len) {
411 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
412 }
413
414 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
415 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
416 if (write(fd, buffer, len) != len) {
417 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
418 }
419
420 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700421}
422
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800423// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
424// file.
425static bool setKernelOptionEnable(const char* filename, bool enable)
426{
427 return writeStr(filename, enable ? "1" : "0");
428}
429
430// Check whether the category is supported on the device with the current
431// rootness. A category is supported only if all its required /sys/ files are
432// writable and if enabling the category will enable one or more tracing tags
433// or /sys/ files.
434static bool isCategorySupported(const TracingCategory& category)
435{
sergeyvdb404152016-05-02 19:26:07 -0700436 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700437 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700438 }
439
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700440 if (strcmp(category.name, k_pdxServiceCategory) == 0) {
441 return true;
442 }
443
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800444 bool ok = category.tags != 0;
445 for (int i = 0; i < MAX_SYS_FILES; i++) {
446 const char* path = category.sysfiles[i].path;
447 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700448 if (path != nullptr) {
Carmen Jackson5bbc9a22018-12-06 13:47:18 -0800449 if (fileIsWritable(path)) {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800450 ok = true;
Carmen Jackson5bbc9a22018-12-06 13:47:18 -0800451 } else if (req) {
452 return false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800453 }
454 }
455 }
456 return ok;
457}
458
459// Check whether the category would be supported on the device if the user
460// were root. This function assumes that root is able to write to any file
461// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700462// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800463static bool isCategorySupportedForRoot(const TracingCategory& category)
464{
465 bool ok = category.tags != 0;
466 for (int i = 0; i < MAX_SYS_FILES; i++) {
467 const char* path = category.sysfiles[i].path;
468 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700469 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800470 if (req) {
471 if (!fileExists(path)) {
472 return false;
473 } else {
474 ok = true;
475 }
476 } else {
477 ok |= fileExists(path);
478 }
479 }
480 }
481 return ok;
482}
483
484// Enable or disable overwriting of the kernel trace buffers. Disabling this
485// will cause tracing to stop once the trace buffers have filled up.
486static bool setTraceOverwriteEnable(bool enable)
487{
488 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
489}
490
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700491// Set the user initiated trace property
492static bool setUserInitiatedTraceProperty(bool enable)
493{
494 if (!android::base::SetProperty(k_userInitiatedTraceProperty, enable ? "1" : "")) {
495 fprintf(stderr, "error setting user initiated strace system property\n");
496 return false;
497 }
498 return true;
499}
500
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800501// Enable or disable kernel tracing.
502static bool setTracingEnabled(bool enable)
503{
504 return setKernelOptionEnable(k_tracingOnPath, enable);
505}
506
507// Clear the contents of the kernel trace.
508static bool clearTrace()
509{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700510 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800511}
512
513// Set the size of the kernel's trace buffer in kilobytes.
514static bool setTraceBufferSizeKB(int size)
515{
516 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800517 if (size < 1) {
518 size = 1;
519 }
520 snprintf(str, 32, "%d", size);
521 return writeStr(k_traceBufferSizePath, str);
522}
523
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700524#if 0
525// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700526// Set the default size of cmdline hashtable
527static bool setCmdlineSize()
528{
Joel Fernandesce964f22017-06-06 12:20:29 -0700529 if (fileExists(k_traceCmdlineSizePath)) {
530 return writeStr(k_traceCmdlineSizePath, "8192");
531 }
532 return true;
Joel Fernandesed80bd02017-06-02 10:19:28 -0700533}
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700534#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700535
Carmen Jacksonea826792017-05-05 11:42:32 -0700536// Set the clock to the best available option while tracing. Use 'boot' if it's
537// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700538// Any write to the trace_clock sysfs file will reset the buffer, so only
539// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700540static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800541{
Carmen Jacksonea826792017-05-05 11:42:32 -0700542 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
543 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
544 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700545
Carmen Jacksonea826792017-05-05 11:42:32 -0700546 std::string newClock;
547 if (clockStr.find("boot") != std::string::npos) {
548 newClock = "boot";
549 } else if (clockStr.find("mono") != std::string::npos) {
550 newClock = "mono";
551 } else {
552 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700553 }
554
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700555 size_t begin = clockStr.find('[') + 1;
556 size_t end = clockStr.find(']');
Carmen Jacksonea826792017-05-05 11:42:32 -0700557 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
558 return true;
559 }
560 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800561}
562
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700563static bool setPrintTgidEnableIfPresent(bool enable)
564{
John Reckedbf9ec2018-06-29 11:15:17 -0700565 // Pre-4.13 this was options/print-tgid as an android-specific option.
566 // In 4.13+ this is an upstream option called options/record-tgid
567 // Both options produce the same ftrace format change
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700568 if (fileExists(k_printTgidPath)) {
569 return setKernelOptionEnable(k_printTgidPath, enable);
570 }
John Recke757b1c2018-06-28 12:24:33 -0700571 if (fileExists(k_recordTgidPath)) {
572 return setKernelOptionEnable(k_recordTgidPath, enable);
573 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700574 return true;
575}
576
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800577// Set the trace tags that userland tracing uses, and poke the running
578// processes to pick up the new value.
579static bool setTagsProperty(uint64_t tags)
580{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700581 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
582 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800583 fprintf(stderr, "error setting trace tags system property\n");
584 return false;
585 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700586 return true;
587}
588
sergeyv4144eff2016-04-28 11:40:04 -0700589static void clearAppProperties()
590{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700591 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700592 fprintf(stderr, "failed to clear system property: %s",
593 k_traceAppsNumberProperty);
594 }
595}
596
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700597// Set the system property that indicates which apps should perform
598// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700599static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700600{
sergeyv4144eff2016-04-28 11:40:04 -0700601 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700602 char* start = cmdline;
Yi Kong19d5c002018-07-20 13:39:55 -0700603 while (start != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700604 char* end = strchr(start, ',');
Yi Kong19d5c002018-07-20 13:39:55 -0700605 if (end != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700606 *end = '\0';
607 end++;
608 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700609 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
610 if (!android::base::SetProperty(key, start)) {
611 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700612 clearAppProperties();
613 return false;
614 }
615 start = end;
616 i++;
617 }
618
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700619 std::string value = android::base::StringPrintf("%d", i);
620 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
621 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700622 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700623 return false;
624 }
625 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800626}
627
628// Disable all /sys/ enable files.
629static bool disableKernelTraceEvents() {
630 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700631 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800632 const TracingCategory &c = k_categories[i];
633 for (int j = 0; j < MAX_SYS_FILES; j++) {
634 const char* path = c.sysfiles[j].path;
Yi Kong19d5c002018-07-20 13:39:55 -0700635 if (path != nullptr && fileIsWritable(path)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800636 ok &= setKernelOptionEnable(path, false);
637 }
638 }
639 }
640 return ok;
641}
642
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700643// Verify that the comma separated list of functions are being traced by the
644// kernel.
645static bool verifyKernelTraceFuncs(const char* funcs)
646{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100647 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800648 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100649 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700650 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100651 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700652 }
653
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100654 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700655
656 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100657 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700658 bool ok = true;
659 char* myFuncs = strdup(funcs);
660 char* func = strtok(myFuncs, ",");
661 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100662 if (!strchr(func, '*')) {
663 String8 fancyFunc = String8::format("\n%s\n", func);
664 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
665 if (!found || func[0] == '\0') {
666 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
667 "to trace.\n", func);
668 ok = false;
669 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700670 }
Yi Kong19d5c002018-07-20 13:39:55 -0700671 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700672 }
673 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700674 return ok;
675}
676
677// Set the comma separated list of functions that the kernel is to trace.
678static bool setKernelTraceFuncs(const char* funcs)
679{
680 bool ok = true;
681
Yi Kong19d5c002018-07-20 13:39:55 -0700682 if (funcs == nullptr || funcs[0] == '\0') {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700683 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700684 if (fileIsWritable(k_currentTracerPath)) {
685 ok &= writeStr(k_currentTracerPath, "nop");
686 }
687 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700688 ok &= truncateFile(k_ftraceFilterPath);
689 }
690 } else {
691 // Enable kernel function tracing.
692 ok &= writeStr(k_currentTracerPath, "function_graph");
693 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
694 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
695 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
696 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
697
698 // Set the requested filter functions.
699 ok &= truncateFile(k_ftraceFilterPath);
700 char* myFuncs = strdup(funcs);
701 char* func = strtok(myFuncs, ",");
702 while (func) {
703 ok &= appendStr(k_ftraceFilterPath, func);
Yi Kong19d5c002018-07-20 13:39:55 -0700704 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700705 }
706 free(myFuncs);
707
708 // Verify that the set functions are being traced.
709 if (ok) {
710 ok &= verifyKernelTraceFuncs(funcs);
711 }
712 }
713
714 return ok;
715}
716
Wei Wang16a63a42018-09-21 15:47:45 -0700717static bool setCategoryEnable(const char* name)
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900718{
Wei Wang16a63a42018-09-21 15:47:45 -0700719 bool vendor_found = false;
720 for (auto &c : g_vendorCategories) {
721 if (strcmp(name, c.name.c_str()) == 0) {
722 c.enabled = true;
723 vendor_found = true;
724 }
725 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700726 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900727 const TracingCategory& c = k_categories[i];
728 if (strcmp(name, c.name) == 0) {
729 if (isCategorySupported(c)) {
Wei Wang16a63a42018-09-21 15:47:45 -0700730 g_categoryEnables[i] = true;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900731 return true;
732 } else {
733 if (isCategorySupportedForRoot(c)) {
734 fprintf(stderr, "error: category \"%s\" requires root "
735 "privileges.\n", name);
736 } else {
737 fprintf(stderr, "error: category \"%s\" is not supported "
738 "on this device.\n", name);
739 }
740 return false;
741 }
742 }
743 }
Wei Wang16a63a42018-09-21 15:47:45 -0700744 if (vendor_found) {
745 return true;
746 }
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900747 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
748 return false;
749}
750
751static bool setCategoriesEnableFromFile(const char* categories_file)
752{
753 if (!categories_file) {
754 return true;
755 }
Yi Kong19d5c002018-07-20 13:39:55 -0700756 Tokenizer* tokenizer = nullptr;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900757 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
758 return false;
759 }
760 bool ok = true;
761 while (!tokenizer->isEol()) {
762 String8 token = tokenizer->nextToken(" ");
763 if (token.isEmpty()) {
764 tokenizer->skipDelimiters(" ");
765 continue;
766 }
Wei Wang16a63a42018-09-21 15:47:45 -0700767 ok &= setCategoryEnable(token.string());
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900768 }
769 delete tokenizer;
770 return ok;
771}
772
Hector Dearman11845782018-03-08 14:35:44 +0000773static bool setUpUserspaceTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800774{
775 bool ok = true;
776
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800777 // Set up the tags property.
778 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700779 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800780 if (g_categoryEnables[i]) {
781 const TracingCategory &c = k_categories[i];
782 tags |= c.tags;
783 }
784 }
sergeyvdb404152016-05-02 19:26:07 -0700785
786 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700787 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700788 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
789 coreServicesTagEnabled = g_categoryEnables[i];
790 }
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700791
792 // Set whether to poke PDX services in this session.
793 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
794 g_tracePdx = g_categoryEnables[i];
795 }
sergeyvdb404152016-05-02 19:26:07 -0700796 }
797
798 std::string packageList(g_debugAppCmdLine);
799 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700800 if (!packageList.empty()) {
801 packageList += ",";
802 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700803 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700804 }
Dan Austin09a79872016-05-31 13:27:03 -0700805 ok &= setAppCmdlineProperty(&packageList[0]);
Florian Mayer6263b582019-12-10 13:28:45 +0000806 ok &= setTagsProperty(tags);
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700807 if (g_tracePdx) {
808 ok &= ServiceUtility::PokeServices();
809 }
810
Hector Dearman11845782018-03-08 14:35:44 +0000811 return ok;
812}
813
814static void cleanUpUserspaceTracing()
815{
816 setTagsProperty(0);
817 clearAppProperties();
Hector Dearman11845782018-03-08 14:35:44 +0000818
819 if (g_tracePdx) {
820 ServiceUtility::PokeServices();
821 }
822}
823
824
825// Set all the kernel tracing settings to the desired state for this trace
826// capture.
827static bool setUpKernelTracing()
828{
829 bool ok = true;
830
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700831 ok &= setUserInitiatedTraceProperty(true);
832
Hector Dearman11845782018-03-08 14:35:44 +0000833 // Set up the tracing options.
834 ok &= setCategoriesEnableFromFile(g_categoriesFile);
835 ok &= setTraceOverwriteEnable(g_traceOverwrite);
836 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
837 // TODO: Re-enable after stabilization
838 //ok &= setCmdlineSize();
839 ok &= setClock();
840 ok &= setPrintTgidEnableIfPresent(true);
841 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
842
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800843 // Disable all the sysfs enables. This is done as a separate loop from
844 // the enables to allow the same enable to exist in multiple categories.
845 ok &= disableKernelTraceEvents();
846
847 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700848 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800849 if (g_categoryEnables[i]) {
850 const TracingCategory &c = k_categories[i];
851 for (int j = 0; j < MAX_SYS_FILES; j++) {
852 const char* path = c.sysfiles[j].path;
853 bool required = c.sysfiles[j].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700854 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800855 if (fileIsWritable(path)) {
856 ok &= setKernelOptionEnable(path, true);
857 } else if (required) {
858 fprintf(stderr, "error writing file %s\n", path);
859 ok = false;
860 }
861 }
862 }
863 }
864 }
865
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800866 return ok;
867}
868
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700869// Reset all the kernel tracing settings to their default state.
Hector Dearman11845782018-03-08 14:35:44 +0000870static void cleanUpKernelTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800871{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800872 // Disable all tracing that we're able to.
873 disableKernelTraceEvents();
874
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800875 // Set the options back to their defaults.
876 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700877 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700878 setPrintTgidEnableIfPresent(false);
Yi Kong19d5c002018-07-20 13:39:55 -0700879 setKernelTraceFuncs(nullptr);
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700880 setUserInitiatedTraceProperty(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700881}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800882
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700883// Enable tracing in the kernel.
884static bool startTrace()
885{
886 return setTracingEnabled(true);
887}
888
889// Disable tracing in the kernel.
890static void stopTrace()
891{
892 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800893}
894
Martijn Coenend9535872015-11-26 10:00:55 +0100895// Read data from the tracing pipe and forward to stdout
896static void streamTrace()
897{
898 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800899 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100900 if (traceFD == -1) {
901 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
902 strerror(errno), errno);
903 return;
904 }
905 while (!g_traceAborted) {
906 ssize_t bytes_read = read(traceFD, trace_data, 4096);
907 if (bytes_read > 0) {
908 write(STDOUT_FILENO, trace_data, bytes_read);
909 fflush(stdout);
910 } else {
911 if (!g_traceAborted) {
912 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
913 bytes_read, errno, strerror(errno));
914 }
915 break;
916 }
917 }
918}
919
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800920// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700921static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800922{
John Reck6c8ac922016-03-28 11:25:30 -0700923 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800924 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800925 if (traceFD == -1) {
926 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
927 strerror(errno), errno);
928 return;
929 }
930
931 if (g_compress) {
932 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800933 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700934
935 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800936 if (result != Z_OK) {
937 fprintf(stderr, "error initializing zlib: %d\n", result);
938 close(traceFD);
939 return;
940 }
941
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700942 constexpr size_t bufSize = 64*1024;
943 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
944 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
945 if (!in || !out) {
946 fprintf(stderr, "couldn't allocate buffers\n");
947 close(traceFD);
948 return;
949 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800950
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700951 int flush = Z_NO_FLUSH;
952
953 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800954 zs.avail_out = bufSize;
955
956 do {
957
958 if (zs.avail_in == 0) {
959 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700960 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800961 if (result < 0) {
962 fprintf(stderr, "error reading trace: %s (%d)\n",
963 strerror(errno), errno);
964 result = Z_STREAM_END;
965 break;
966 } else if (result == 0) {
967 flush = Z_FINISH;
968 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700969 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800970 zs.avail_in = result;
971 }
972 }
973
974 if (zs.avail_out == 0) {
975 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700976 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800977 if ((size_t)result < bufSize) {
978 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
979 strerror(errno), errno);
980 result = Z_STREAM_END; // skip deflate error message
981 zs.avail_out = bufSize; // skip the final write
982 break;
983 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700984 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800985 zs.avail_out = bufSize;
986 }
987
988 } while ((result = deflate(&zs, flush)) == Z_OK);
989
990 if (result != Z_STREAM_END) {
991 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
992 }
993
994 if (zs.avail_out < bufSize) {
995 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -0700996 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800997 if ((size_t)result < bytes) {
998 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
999 strerror(errno), errno);
1000 }
1001 }
1002
1003 result = deflateEnd(&zs);
1004 if (result != Z_OK) {
1005 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1006 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001007 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001008 char buf[4096];
1009 ssize_t rc;
1010 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1011 if (!android::base::WriteFully(outFd, buf, rc)) {
1012 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1013 break;
1014 }
1015 }
1016 if (rc == -1) {
1017 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001018 }
1019 }
1020
1021 close(traceFD);
1022}
1023
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001024static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001025{
1026 if (!g_nohup) {
1027 g_traceAborted = true;
1028 }
1029}
1030
1031static void registerSigHandler()
1032{
1033 struct sigaction sa;
1034 sigemptyset(&sa.sa_mask);
1035 sa.sa_flags = 0;
1036 sa.sa_handler = handleSignal;
Yi Kong19d5c002018-07-20 13:39:55 -07001037 sigaction(SIGHUP, &sa, nullptr);
1038 sigaction(SIGINT, &sa, nullptr);
1039 sigaction(SIGQUIT, &sa, nullptr);
1040 sigaction(SIGTERM, &sa, nullptr);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001041}
1042
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001043static void listSupportedCategories()
1044{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001045 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001046 const TracingCategory& c = k_categories[i];
1047 if (isCategorySupported(c)) {
1048 printf(" %10s - %s\n", c.name, c.longname);
1049 }
1050 }
Wei Wang16a63a42018-09-21 15:47:45 -07001051 for (const auto &c : g_vendorCategories) {
1052 printf(" %10s - %s (HAL)\n", c.name.c_str(), c.description.c_str());
1053 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001054}
1055
1056// Print the command usage help to stderr.
1057static void showHelp(const char *cmd)
1058{
1059 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1060 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001061 " -a appname enable app-level tracing for a comma "
Daniel Colascione519a0792018-02-09 20:05:39 -08001062 "separated list of cmdlines; * is a wildcard matching any process\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001063 " -b N use a trace buffer size of N KB\n"
1064 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001065 " -f filename use the categories written in a file as space-separated\n"
1066 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001067 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001068 " -n ignore signals\n"
1069 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001070 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001071 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001072 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001073 " --async_dump dump the current contents of circular trace buffer\n"
1074 " --async_stop stop tracing and dump the current contents of circular\n"
1075 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001076 " --stream stream trace to stdout as it enters the trace buffer\n"
1077 " Note: this can take significant CPU time, and is best\n"
1078 " used for measuring things that are not affected by\n"
1079 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001080 " --list_categories\n"
1081 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001082 " -o filename write the trace to the specified file instead\n"
1083 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001084 );
1085}
1086
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001087bool findTraceFiles()
1088{
1089 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1090 static const std::string tracefs_path = "/sys/kernel/tracing/";
1091 static const std::string trace_file = "trace_marker";
1092
1093 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1094 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1095
1096 if (!tracefs && !debugfs) {
1097 fprintf(stderr, "Error: Did not find trace folder\n");
1098 return false;
1099 }
1100
1101 if (tracefs) {
1102 g_traceFolder = tracefs_path;
1103 } else {
1104 g_traceFolder = debugfs_path;
1105 }
1106
1107 return true;
1108}
1109
Wei Wang16a63a42018-09-21 15:47:45 -07001110void initVendorCategories()
1111{
1112 g_atraceHal = IAtraceDevice::getService();
1113
1114 if (g_atraceHal == nullptr) {
1115 // No atrace HAL
1116 return;
1117 }
1118
1119 Return<void> ret = g_atraceHal->listCategories(
1120 [](const auto& list) {
1121 g_vendorCategories.reserve(list.size());
1122 for (const auto& category : list) {
1123 g_vendorCategories.emplace_back(category.name, category.description, false);
1124 }
1125 });
1126 if (!ret.isOk()) {
1127 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1128 }
1129}
1130
1131static bool setUpVendorTracing()
1132{
1133 if (g_atraceHal == nullptr) {
1134 // No atrace HAL
1135 return true;
1136 }
1137
1138 std::vector<hidl_string> categories;
1139 for (const auto &c : g_vendorCategories) {
1140 if (c.enabled) {
1141 categories.emplace_back(c.name);
1142 }
1143 }
1144
1145 if (!categories.size()) {
1146 return true;
1147 }
1148
1149 auto ret = g_atraceHal->enableCategories(categories);
1150 if (!ret.isOk()) {
1151 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1152 return false;
1153 } else if (ret != Status::SUCCESS) {
1154 fprintf(stderr, "calling atrace HAL failed: %s\n", toString(ret).c_str());
1155 return false;
1156 }
1157 return true;
1158}
1159
1160static bool cleanUpVendorTracing()
1161{
1162 if (g_atraceHal == nullptr) {
1163 // No atrace HAL
1164 return true;
1165 }
1166
1167 if (!g_vendorCategories.size()) {
1168 // No vendor categories
1169 return true;
1170 }
1171
1172 auto ret = g_atraceHal->disableAllCategories();
1173 if (!ret.isOk()) {
1174 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1175 return false;
1176 } else if (ret != Status::SUCCESS) {
1177 fprintf(stderr, "calling atrace HAL failed: %s\n", toString(ret).c_str());
1178 return false;
1179 }
1180 return true;
1181}
1182
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001183int main(int argc, char **argv)
1184{
1185 bool async = false;
1186 bool traceStart = true;
1187 bool traceStop = true;
1188 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001189 bool traceStream = false;
Hector Dearman11845782018-03-08 14:35:44 +00001190 bool onlyUserspace = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001191
1192 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1193 showHelp(argv[0]);
1194 exit(0);
1195 }
1196
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001197 if (!findTraceFiles()) {
1198 fprintf(stderr, "No trace folder found\n");
1199 exit(-1);
1200 }
1201
Wei Wang16a63a42018-09-21 15:47:45 -07001202 initVendorCategories();
1203
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001204 for (;;) {
1205 int ret;
1206 int option_index = 0;
1207 static struct option long_options[] = {
Yi Kong19d5c002018-07-20 13:39:55 -07001208 {"async_start", no_argument, nullptr, 0 },
1209 {"async_stop", no_argument, nullptr, 0 },
1210 {"async_dump", no_argument, nullptr, 0 },
1211 {"only_userspace", no_argument, nullptr, 0 },
1212 {"list_categories", no_argument, nullptr, 0 },
1213 {"stream", no_argument, nullptr, 0 },
1214 {nullptr, 0, nullptr, 0 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001215 };
1216
John Reck40b26b42016-03-30 09:44:36 -07001217 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001218 long_options, &option_index);
1219
1220 if (ret < 0) {
1221 for (int i = optind; i < argc; i++) {
Wei Wang16a63a42018-09-21 15:47:45 -07001222 if (!setCategoryEnable(argv[i])) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001223 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1224 exit(1);
1225 }
1226 }
1227 break;
1228 }
1229
1230 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001231 case 'a':
1232 g_debugAppCmdLine = optarg;
1233 break;
1234
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001235 case 'b':
1236 g_traceBufferSizeKB = atoi(optarg);
1237 break;
1238
1239 case 'c':
1240 g_traceOverwrite = true;
1241 break;
1242
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001243 case 'f':
1244 g_categoriesFile = optarg;
1245 break;
1246
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001247 case 'k':
1248 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001249 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001250
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001251 case 'n':
1252 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001253 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001254
1255 case 's':
1256 g_initialSleepSecs = atoi(optarg);
1257 break;
1258
1259 case 't':
1260 g_traceDurationSeconds = atoi(optarg);
1261 break;
1262
1263 case 'z':
1264 g_compress = true;
1265 break;
1266
John Reck40b26b42016-03-30 09:44:36 -07001267 case 'o':
1268 g_outputFile = optarg;
1269 break;
1270
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001271 case 0:
1272 if (!strcmp(long_options[option_index].name, "async_start")) {
1273 async = true;
1274 traceStop = false;
1275 traceDump = false;
1276 g_traceOverwrite = true;
1277 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1278 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001279 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001280 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1281 async = true;
1282 traceStart = false;
1283 traceStop = false;
Hector Dearman11845782018-03-08 14:35:44 +00001284 } else if (!strcmp(long_options[option_index].name, "only_userspace")) {
1285 onlyUserspace = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001286 } else if (!strcmp(long_options[option_index].name, "stream")) {
1287 traceStream = true;
1288 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001289 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1290 listSupportedCategories();
1291 exit(0);
1292 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001293 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001294
1295 default:
1296 fprintf(stderr, "\n");
1297 showHelp(argv[0]);
1298 exit(-1);
1299 break;
1300 }
1301 }
1302
Hector Dearman11845782018-03-08 14:35:44 +00001303 if (onlyUserspace) {
1304 if (!async || !(traceStart || traceStop)) {
1305 fprintf(stderr, "--only_userspace can only be used with "
1306 "--async_start or --async_stop\n");
1307 exit(1);
1308 }
1309 }
1310
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001311 registerSigHandler();
1312
1313 if (g_initialSleepSecs > 0) {
1314 sleep(g_initialSleepSecs);
1315 }
1316
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001317 bool ok = true;
Hector Dearman11845782018-03-08 14:35:44 +00001318
Wei Wang5b73b742018-03-08 13:33:12 -08001319 if (traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001320 ok &= setUpUserspaceTracing();
1321 }
1322
1323 if (ok && traceStart && !onlyUserspace) {
1324 ok &= setUpKernelTracing();
Wei Wang16a63a42018-09-21 15:47:45 -07001325 ok &= setUpVendorTracing();
Wei Wang5b73b742018-03-08 13:33:12 -08001326 ok &= startTrace();
1327 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001328
1329 if (ok && traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001330
1331 if (!traceStream && !onlyUserspace) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001332 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001333 fflush(stdout);
1334 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001335
1336 // We clear the trace after starting it because tracing gets enabled for
1337 // each CPU individually in the kernel. Having the beginning of the trace
1338 // contain entries from only one CPU can cause "begin" entries without a
1339 // matching "end" entry to show up if a task gets migrated from one CPU to
1340 // another.
Hector Dearman11845782018-03-08 14:35:44 +00001341 if (!onlyUserspace)
1342 ok = clearTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001343
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001344 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001345 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001346 // Sleep to allow the trace to be captured.
1347 struct timespec timeLeft;
1348 timeLeft.tv_sec = g_traceDurationSeconds;
1349 timeLeft.tv_nsec = 0;
1350 do {
1351 if (g_traceAborted) {
1352 break;
1353 }
1354 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1355 }
Martijn Coenend9535872015-11-26 10:00:55 +01001356
1357 if (traceStream) {
1358 streamTrace();
1359 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001360 }
1361
1362 // Stop the trace and restore the default settings.
Hector Dearman11845782018-03-08 14:35:44 +00001363 if (traceStop && !onlyUserspace)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001364 stopTrace();
1365
Hector Dearman11845782018-03-08 14:35:44 +00001366 if (ok && traceDump && !onlyUserspace) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001367 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001368 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001369 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001370 int outFd = STDOUT_FILENO;
1371 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001372 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001373 }
1374 if (outFd == -1) {
1375 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1376 } else {
1377 dprintf(outFd, "TRACE:\n");
1378 dumpTrace(outFd);
1379 if (g_outputFile) {
1380 close(outFd);
1381 }
1382 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001383 } else {
1384 printf("\ntrace aborted.\n");
1385 fflush(stdout);
1386 }
1387 clearTrace();
1388 } else if (!ok) {
1389 fprintf(stderr, "unable to start tracing\n");
1390 }
1391
1392 // Reset the trace buffer size to 1.
Hector Dearman11845782018-03-08 14:35:44 +00001393 if (traceStop) {
1394 cleanUpUserspaceTracing();
Hector Dearmanada0a4a2019-04-09 14:13:14 +01001395 if (!onlyUserspace) {
1396 cleanUpVendorTracing();
Hector Dearman11845782018-03-08 14:35:44 +00001397 cleanUpKernelTracing();
Hector Dearmanada0a4a2019-04-09 14:13:14 +01001398 }
Hector Dearman11845782018-03-08 14:35:44 +00001399 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001400
1401 return g_traceAborted ? 1 : 0;
1402}