blob: 287dd4874dab4cddf0428a1dc49fd3e83dd54c8e [file] [log] [blame]
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Paul Lawrence2cd93cc2017-01-17 09:50:18 -080017#define LOG_TAG "atrace"
John Reck40b26b42016-03-30 09:44:36 -070018
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080019#include <errno.h>
20#include <fcntl.h>
21#include <getopt.h>
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070022#include <inttypes.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080023#include <signal.h>
24#include <stdarg.h>
25#include <stdbool.h>
26#include <stdio.h>
27#include <stdlib.h>
Elliott Hughes3da5d232015-01-25 08:35:20 -080028#include <string.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080029#include <time.h>
Martijn Coenend9535872015-11-26 10:00:55 +010030#include <unistd.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080031#include <zlib.h>
32
Carmen Jacksonea826792017-05-05 11:42:32 -070033#include <fstream>
Elliott Hughesa252f4d2016-07-21 17:12:15 -070034#include <memory>
35
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080036#include <binder/IBinder.h>
37#include <binder/IServiceManager.h>
38#include <binder/Parcel.h>
39
Wei Wang16a63a42018-09-21 15:47:45 -070040#include <android/hardware/atrace/1.0/IAtraceDevice.h>
Martijn Coenenee9b97e2016-11-16 16:00:26 +010041#include <android/hidl/manager/1.0/IServiceManager.h>
42#include <hidl/ServiceManagement.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080043
Corey Tabakaa6c0a722017-05-31 16:37:40 -070044#include <pdx/default_transport/service_utility.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080045#include <utils/String8.h>
John Reck469a1942015-03-26 15:31:35 -070046#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +090047#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080048#include <utils/Trace.h>
Stephane Gasparinid8419c22016-03-02 13:45:15 +010049#include <android-base/file.h>
Elliott Hughes5fd6ff62017-03-28 14:55:31 -070050#include <android-base/macros.h>
51#include <android-base/properties.h>
52#include <android-base/stringprintf.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080053
54using namespace android;
Corey Tabakaa6c0a722017-05-31 16:37:40 -070055using pdx::default_transport::ServiceUtility;
Wei Wang16a63a42018-09-21 15:47:45 -070056using hardware::hidl_vec;
57using hardware::hidl_string;
58using hardware::Return;
59using hardware::atrace::V1_0::IAtraceDevice;
60using hardware::atrace::V1_0::Status;
61using hardware::atrace::V1_0::toString;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080062
Martijn Coenenee9b97e2016-11-16 16:00:26 +010063using std::string;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080064
Wei Wang963999c2021-03-17 16:28:59 -070065#define MAX_SYS_FILES 12
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080066
67const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
Carmen Jackson65ecfbb2018-05-22 10:29:47 -070068const char* k_userInitiatedTraceProperty = "debug.atrace.user_initiated";
sergeyv4144eff2016-04-28 11:40:04 -070069
70const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
71const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070072const char* k_coreServiceCategory = "core_services";
Corey Tabakaa6c0a722017-05-31 16:37:40 -070073const char* k_pdxServiceCategory = "pdx";
sergeyvdb404152016-05-02 19:26:07 -070074const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080075
76typedef enum { OPT, REQ } requiredness ;
77
78struct TracingCategory {
79 // The name identifying the category.
80 const char* name;
81
82 // A longer description of the category.
83 const char* longname;
84
85 // The userland tracing tags that the category enables.
86 uint64_t tags;
87
88 // The fname==NULL terminated list of /sys/ files that the category
89 // enables.
90 struct {
91 // Whether the file must be writable in order to enable the tracing
92 // category.
93 requiredness required;
94
95 // The path to the enable file.
96 const char* path;
97 } sysfiles[MAX_SYS_FILES];
98};
99
100/* Tracing categories */
101static const TracingCategory k_categories[] = {
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" },
Wei Wang2ded52d2020-07-31 01:13:58 -0700175 { OPT, "events/cpuhp/cpuhp_enter/enable" },
176 { OPT, "events/cpuhp/cpuhp_exit/enable" },
Wei Wang963999c2021-03-17 16:28:59 -0700177 { OPT, "events/cpuhp/cpuhp_pause/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800178 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700179 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800180 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800181 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700182 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800183 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800184 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700185 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800186 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
187 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
188 { OPT, "events/f2fs/f2fs_write_begin/enable" },
189 { OPT, "events/f2fs/f2fs_write_end/enable" },
190 { OPT, "events/ext4/ext4_da_write_begin/enable" },
191 { OPT, "events/ext4/ext4_da_write_end/enable" },
192 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
193 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
194 { REQ, "events/block/block_rq_issue/enable" },
195 { REQ, "events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800196 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700197 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800198 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700199 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700200 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800201 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800202 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700203 { "sync", "Synchronization", 0, {
Jesse Halla978cef2019-02-25 16:24:10 -0800204 // linux kernel < 4.9
Jesse Hallae001a32018-05-15 12:02:15 -0700205 { OPT, "events/sync/enable" },
Jesse Halla978cef2019-02-25 16:24:10 -0800206 // linux kernel == 4.9.x
Jesse Hallae001a32018-05-15 12:02:15 -0700207 { OPT, "events/fence/enable" },
Jesse Halla978cef2019-02-25 16:24:10 -0800208 // linux kernel > 4.9
209 { OPT, "events/dma_fence/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800210 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700211 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800212 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800213 } },
Colin Cross580407f2014-08-18 15:22:13 -0700214 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800215 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
216 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
217 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
218 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Carmen Jackson7a23eb72018-07-02 13:14:56 -0700219 { OPT, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700220 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800221 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800222 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800223 } },
Scott Bauerae473362015-06-08 16:32:36 -0700224 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800225 { REQ, "events/binder/binder_transaction/enable" },
226 { REQ, "events/binder/binder_transaction_received/enable" },
Mika Raento80c3e5d2018-06-25 16:47:24 +0100227 { REQ, "events/binder/binder_transaction_alloc_buf/enable" },
Martijn Coenen7f3d7a22017-05-26 09:50:55 -0700228 { OPT, "events/binder/binder_set_priority/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700229 } },
230 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800231 { OPT, "events/binder/binder_lock/enable" },
232 { OPT, "events/binder/binder_locked/enable" },
233 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700234 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200235 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800236 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200237 } },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700238 { "memory", "Memory", 0, {
Collin Fijalkovich08e3f4a2020-03-30 16:20:24 -0700239 { OPT, "events/mm_event/mm_event_record/enable" },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700240 { OPT, "events/kmem/rss_stat/enable" },
241 { OPT, "events/kmem/ion_heap_grow/enable" },
242 { OPT, "events/kmem/ion_heap_shrink/enable" },
Ioannis Ilkos88a85f32020-04-23 22:43:40 +0100243 { OPT, "events/ion/ion_stat/enable" },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700244 } },
Wei Wange3079a92020-07-08 15:33:20 -0700245 { "thermal", "Thermal event", 0, {
246 { REQ, "events/thermal/thermal_temperature/enable" },
247 { OPT, "events/thermal/cdev_update/enable" },
248 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800249};
250
Wei Wang16a63a42018-09-21 15:47:45 -0700251struct TracingVendorCategory {
252 // The name identifying the category.
253 std::string name;
254
255 // A longer description of the category.
256 std::string description;
257
258 // If the category is enabled through command.
259 bool enabled;
260
261 TracingVendorCategory(string &&name, string &&description, bool enabled)
262 : name(std::move(name))
263 , description(std::move(description))
264 , enabled(enabled)
265 {}
266};
267
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800268/* Command line options */
269static int g_traceDurationSeconds = 5;
270static bool g_traceOverwrite = false;
271static int g_traceBufferSizeKB = 2048;
272static bool g_compress = false;
273static bool g_nohup = false;
274static int g_initialSleepSecs = 0;
Yi Kong19d5c002018-07-20 13:39:55 -0700275static const char* g_categoriesFile = nullptr;
276static const char* g_kernelTraceFuncs = nullptr;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700277static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700278static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800279
280/* Global state */
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700281static bool g_tracePdx = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800282static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700283static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800284static std::string g_traceFolder;
Wei Wang16a63a42018-09-21 15:47:45 -0700285static sp<IAtraceDevice> g_atraceHal;
286static std::vector<TracingVendorCategory> g_vendorCategories;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800287
288/* Sys file paths */
289static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800290 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800291
292static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800293 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800294
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700295#if 0
296// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700297static const char* k_traceCmdlineSizePath =
298 "saved_cmdlines_size";
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700299#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700300
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800301static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800302 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800303
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700304static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800305 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700306
307static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800308 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700309
John Recke757b1c2018-06-28 12:24:33 -0700310static const char* k_recordTgidPath =
311 "options/record-tgid";
312
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700313static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800314 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700315
316static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800317 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700318
319static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800320 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700321
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700322static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800323 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700324
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800325static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800326 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800327
328static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800329 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800330
Martijn Coenend9535872015-11-26 10:00:55 +0100331static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800332 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100333
John Reck469a1942015-03-26 15:31:35 -0700334static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800335 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700336
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800337// Check whether a file exists.
338static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800339 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800340}
341
342// Check whether a file is writable.
343static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800344 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800345}
346
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700347// Truncate a file.
348static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800349{
Jamie Gennis43122e72013-03-21 14:06:31 -0700350 // This uses creat rather than truncate because some of the debug kernel
351 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
352 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800353 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700354 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800355 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700356 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700357 return false;
358 }
359
Jamie Gennis43122e72013-03-21 14:06:31 -0700360 close(traceFD);
361
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700362 return true;
363}
364
365static bool _writeStr(const char* filename, const char* str, int flags)
366{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800367 std::string fullFilename = g_traceFolder + filename;
368 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800369 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800370 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800371 strerror(errno), errno);
372 return false;
373 }
374
375 bool ok = true;
376 ssize_t len = strlen(str);
377 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800378 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800379 strerror(errno), errno);
380 ok = false;
381 }
382
383 close(fd);
384
385 return ok;
386}
387
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700388// Write a string to a file, returning true if the write was successful.
389static bool writeStr(const char* filename, const char* str)
390{
391 return _writeStr(filename, str, O_WRONLY);
392}
393
394// Append a string to a file, returning true if the write was successful.
395static bool appendStr(const char* filename, const char* str)
396{
397 return _writeStr(filename, str, O_APPEND|O_WRONLY);
398}
399
John Reck469a1942015-03-26 15:31:35 -0700400static void writeClockSyncMarker()
401{
402 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200403 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800404 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200405 if (fd == -1) {
406 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
407 strerror(errno), errno);
408 return;
409 }
John Reck469a1942015-03-26 15:31:35 -0700410 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200411
412 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
413 if (write(fd, buffer, len) != len) {
414 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
415 }
416
417 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
418 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
419 if (write(fd, buffer, len) != len) {
420 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
421 }
422
423 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700424}
425
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800426// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
427// file.
428static bool setKernelOptionEnable(const char* filename, bool enable)
429{
430 return writeStr(filename, enable ? "1" : "0");
431}
432
433// Check whether the category is supported on the device with the current
434// rootness. A category is supported only if all its required /sys/ files are
435// writable and if enabling the category will enable one or more tracing tags
436// or /sys/ files.
437static bool isCategorySupported(const TracingCategory& category)
438{
sergeyvdb404152016-05-02 19:26:07 -0700439 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700440 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700441 }
442
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700443 if (strcmp(category.name, k_pdxServiceCategory) == 0) {
444 return true;
445 }
446
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800447 bool ok = category.tags != 0;
448 for (int i = 0; i < MAX_SYS_FILES; i++) {
449 const char* path = category.sysfiles[i].path;
450 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700451 if (path != nullptr) {
Carmen Jackson5bbc9a22018-12-06 13:47:18 -0800452 if (fileIsWritable(path)) {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800453 ok = true;
Carmen Jackson5bbc9a22018-12-06 13:47:18 -0800454 } else if (req) {
455 return false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800456 }
457 }
458 }
459 return ok;
460}
461
462// Check whether the category would be supported on the device if the user
463// were root. This function assumes that root is able to write to any file
464// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700465// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800466static bool isCategorySupportedForRoot(const TracingCategory& category)
467{
468 bool ok = category.tags != 0;
469 for (int i = 0; i < MAX_SYS_FILES; i++) {
470 const char* path = category.sysfiles[i].path;
471 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700472 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800473 if (req) {
474 if (!fileExists(path)) {
475 return false;
476 } else {
477 ok = true;
478 }
479 } else {
480 ok |= fileExists(path);
481 }
482 }
483 }
484 return ok;
485}
486
487// Enable or disable overwriting of the kernel trace buffers. Disabling this
488// will cause tracing to stop once the trace buffers have filled up.
489static bool setTraceOverwriteEnable(bool enable)
490{
491 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
492}
493
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700494// Set the user initiated trace property
495static bool setUserInitiatedTraceProperty(bool enable)
496{
497 if (!android::base::SetProperty(k_userInitiatedTraceProperty, enable ? "1" : "")) {
498 fprintf(stderr, "error setting user initiated strace system property\n");
499 return false;
500 }
501 return true;
502}
503
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800504// Enable or disable kernel tracing.
505static bool setTracingEnabled(bool enable)
506{
507 return setKernelOptionEnable(k_tracingOnPath, enable);
508}
509
510// Clear the contents of the kernel trace.
511static bool clearTrace()
512{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700513 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800514}
515
516// Set the size of the kernel's trace buffer in kilobytes.
517static bool setTraceBufferSizeKB(int size)
518{
519 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800520 if (size < 1) {
521 size = 1;
522 }
523 snprintf(str, 32, "%d", size);
524 return writeStr(k_traceBufferSizePath, str);
525}
526
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700527#if 0
528// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700529// Set the default size of cmdline hashtable
530static bool setCmdlineSize()
531{
Joel Fernandesce964f22017-06-06 12:20:29 -0700532 if (fileExists(k_traceCmdlineSizePath)) {
533 return writeStr(k_traceCmdlineSizePath, "8192");
534 }
535 return true;
Joel Fernandesed80bd02017-06-02 10:19:28 -0700536}
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700537#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700538
Carmen Jacksonea826792017-05-05 11:42:32 -0700539// Set the clock to the best available option while tracing. Use 'boot' if it's
540// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700541// Any write to the trace_clock sysfs file will reset the buffer, so only
542// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700543static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800544{
Carmen Jacksonea826792017-05-05 11:42:32 -0700545 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
546 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
547 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700548
Carmen Jacksonea826792017-05-05 11:42:32 -0700549 std::string newClock;
550 if (clockStr.find("boot") != std::string::npos) {
551 newClock = "boot";
552 } else if (clockStr.find("mono") != std::string::npos) {
553 newClock = "mono";
554 } else {
555 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700556 }
557
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700558 size_t begin = clockStr.find('[') + 1;
559 size_t end = clockStr.find(']');
Carmen Jacksonea826792017-05-05 11:42:32 -0700560 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
561 return true;
562 }
563 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800564}
565
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700566static bool setPrintTgidEnableIfPresent(bool enable)
567{
John Reckedbf9ec2018-06-29 11:15:17 -0700568 // Pre-4.13 this was options/print-tgid as an android-specific option.
569 // In 4.13+ this is an upstream option called options/record-tgid
570 // Both options produce the same ftrace format change
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700571 if (fileExists(k_printTgidPath)) {
572 return setKernelOptionEnable(k_printTgidPath, enable);
573 }
John Recke757b1c2018-06-28 12:24:33 -0700574 if (fileExists(k_recordTgidPath)) {
575 return setKernelOptionEnable(k_recordTgidPath, enable);
576 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700577 return true;
578}
579
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800580// Set the trace tags that userland tracing uses, and poke the running
581// processes to pick up the new value.
582static bool setTagsProperty(uint64_t tags)
583{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700584 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
585 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800586 fprintf(stderr, "error setting trace tags system property\n");
587 return false;
588 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700589 return true;
590}
591
sergeyv4144eff2016-04-28 11:40:04 -0700592static void clearAppProperties()
593{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700594 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700595 fprintf(stderr, "failed to clear system property: %s",
596 k_traceAppsNumberProperty);
597 }
598}
599
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700600// Set the system property that indicates which apps should perform
601// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700602static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700603{
sergeyv4144eff2016-04-28 11:40:04 -0700604 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700605 char* start = cmdline;
Yi Kong19d5c002018-07-20 13:39:55 -0700606 while (start != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700607 char* end = strchr(start, ',');
Yi Kong19d5c002018-07-20 13:39:55 -0700608 if (end != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700609 *end = '\0';
610 end++;
611 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700612 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
613 if (!android::base::SetProperty(key, start)) {
614 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700615 clearAppProperties();
616 return false;
617 }
618 start = end;
619 i++;
620 }
621
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700622 std::string value = android::base::StringPrintf("%d", i);
623 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
624 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700625 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700626 return false;
627 }
628 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800629}
630
631// Disable all /sys/ enable files.
632static bool disableKernelTraceEvents() {
633 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700634 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800635 const TracingCategory &c = k_categories[i];
636 for (int j = 0; j < MAX_SYS_FILES; j++) {
637 const char* path = c.sysfiles[j].path;
Yi Kong19d5c002018-07-20 13:39:55 -0700638 if (path != nullptr && fileIsWritable(path)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800639 ok &= setKernelOptionEnable(path, false);
640 }
641 }
642 }
643 return ok;
644}
645
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700646// Verify that the comma separated list of functions are being traced by the
647// kernel.
648static bool verifyKernelTraceFuncs(const char* funcs)
649{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100650 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800651 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100652 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700653 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100654 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700655 }
656
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100657 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700658
659 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100660 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700661 bool ok = true;
662 char* myFuncs = strdup(funcs);
663 char* func = strtok(myFuncs, ",");
664 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100665 if (!strchr(func, '*')) {
666 String8 fancyFunc = String8::format("\n%s\n", func);
667 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
668 if (!found || func[0] == '\0') {
669 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
670 "to trace.\n", func);
671 ok = false;
672 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700673 }
Yi Kong19d5c002018-07-20 13:39:55 -0700674 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700675 }
676 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700677 return ok;
678}
679
680// Set the comma separated list of functions that the kernel is to trace.
681static bool setKernelTraceFuncs(const char* funcs)
682{
683 bool ok = true;
684
Yi Kong19d5c002018-07-20 13:39:55 -0700685 if (funcs == nullptr || funcs[0] == '\0') {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700686 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700687 if (fileIsWritable(k_currentTracerPath)) {
688 ok &= writeStr(k_currentTracerPath, "nop");
689 }
690 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700691 ok &= truncateFile(k_ftraceFilterPath);
692 }
693 } else {
694 // Enable kernel function tracing.
695 ok &= writeStr(k_currentTracerPath, "function_graph");
696 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
697 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
698 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700699
700 // Set the requested filter functions.
701 ok &= truncateFile(k_ftraceFilterPath);
702 char* myFuncs = strdup(funcs);
703 char* func = strtok(myFuncs, ",");
704 while (func) {
705 ok &= appendStr(k_ftraceFilterPath, func);
Yi Kong19d5c002018-07-20 13:39:55 -0700706 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700707 }
708 free(myFuncs);
709
710 // Verify that the set functions are being traced.
711 if (ok) {
712 ok &= verifyKernelTraceFuncs(funcs);
713 }
714 }
715
716 return ok;
717}
718
Wei Wang16a63a42018-09-21 15:47:45 -0700719static bool setCategoryEnable(const char* name)
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900720{
Wei Wang16a63a42018-09-21 15:47:45 -0700721 bool vendor_found = false;
722 for (auto &c : g_vendorCategories) {
723 if (strcmp(name, c.name.c_str()) == 0) {
724 c.enabled = true;
725 vendor_found = true;
726 }
727 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700728 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900729 const TracingCategory& c = k_categories[i];
730 if (strcmp(name, c.name) == 0) {
731 if (isCategorySupported(c)) {
Wei Wang16a63a42018-09-21 15:47:45 -0700732 g_categoryEnables[i] = true;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900733 return true;
734 } else {
735 if (isCategorySupportedForRoot(c)) {
736 fprintf(stderr, "error: category \"%s\" requires root "
737 "privileges.\n", name);
738 } else {
739 fprintf(stderr, "error: category \"%s\" is not supported "
740 "on this device.\n", name);
741 }
742 return false;
743 }
744 }
745 }
Wei Wang16a63a42018-09-21 15:47:45 -0700746 if (vendor_found) {
747 return true;
748 }
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900749 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
750 return false;
751}
752
753static bool setCategoriesEnableFromFile(const char* categories_file)
754{
755 if (!categories_file) {
756 return true;
757 }
Yi Kong19d5c002018-07-20 13:39:55 -0700758 Tokenizer* tokenizer = nullptr;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900759 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
760 return false;
761 }
762 bool ok = true;
763 while (!tokenizer->isEol()) {
764 String8 token = tokenizer->nextToken(" ");
765 if (token.isEmpty()) {
766 tokenizer->skipDelimiters(" ");
767 continue;
768 }
Wei Wang16a63a42018-09-21 15:47:45 -0700769 ok &= setCategoryEnable(token.string());
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900770 }
771 delete tokenizer;
772 return ok;
773}
774
Hector Dearman11845782018-03-08 14:35:44 +0000775static bool setUpUserspaceTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800776{
777 bool ok = true;
778
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800779 // Set up the tags property.
780 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700781 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800782 if (g_categoryEnables[i]) {
783 const TracingCategory &c = k_categories[i];
784 tags |= c.tags;
785 }
786 }
sergeyvdb404152016-05-02 19:26:07 -0700787
788 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700789 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700790 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
791 coreServicesTagEnabled = g_categoryEnables[i];
792 }
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700793
794 // Set whether to poke PDX services in this session.
795 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
796 g_tracePdx = g_categoryEnables[i];
797 }
sergeyvdb404152016-05-02 19:26:07 -0700798 }
799
800 std::string packageList(g_debugAppCmdLine);
801 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700802 if (!packageList.empty()) {
803 packageList += ",";
804 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700805 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700806 }
Dan Austin09a79872016-05-31 13:27:03 -0700807 ok &= setAppCmdlineProperty(&packageList[0]);
Florian Mayer6263b582019-12-10 13:28:45 +0000808 ok &= setTagsProperty(tags);
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700809 if (g_tracePdx) {
810 ok &= ServiceUtility::PokeServices();
811 }
812
Hector Dearman11845782018-03-08 14:35:44 +0000813 return ok;
814}
815
816static void cleanUpUserspaceTracing()
817{
818 setTagsProperty(0);
819 clearAppProperties();
Hector Dearman11845782018-03-08 14:35:44 +0000820
821 if (g_tracePdx) {
822 ServiceUtility::PokeServices();
823 }
824}
825
826
827// Set all the kernel tracing settings to the desired state for this trace
828// capture.
829static bool setUpKernelTracing()
830{
831 bool ok = true;
832
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700833 ok &= setUserInitiatedTraceProperty(true);
834
Hector Dearman11845782018-03-08 14:35:44 +0000835 // Set up the tracing options.
836 ok &= setCategoriesEnableFromFile(g_categoriesFile);
837 ok &= setTraceOverwriteEnable(g_traceOverwrite);
838 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
839 // TODO: Re-enable after stabilization
840 //ok &= setCmdlineSize();
841 ok &= setClock();
842 ok &= setPrintTgidEnableIfPresent(true);
843 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
844
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800845 // Disable all the sysfs enables. This is done as a separate loop from
846 // the enables to allow the same enable to exist in multiple categories.
847 ok &= disableKernelTraceEvents();
848
849 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700850 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800851 if (g_categoryEnables[i]) {
852 const TracingCategory &c = k_categories[i];
853 for (int j = 0; j < MAX_SYS_FILES; j++) {
854 const char* path = c.sysfiles[j].path;
855 bool required = c.sysfiles[j].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700856 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800857 if (fileIsWritable(path)) {
858 ok &= setKernelOptionEnable(path, true);
859 } else if (required) {
860 fprintf(stderr, "error writing file %s\n", path);
861 ok = false;
862 }
863 }
864 }
865 }
866 }
867
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800868 return ok;
869}
870
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700871// Reset all the kernel tracing settings to their default state.
Hector Dearman11845782018-03-08 14:35:44 +0000872static void cleanUpKernelTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800873{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800874 // Disable all tracing that we're able to.
875 disableKernelTraceEvents();
876
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800877 // Set the options back to their defaults.
878 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700879 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700880 setPrintTgidEnableIfPresent(false);
Yi Kong19d5c002018-07-20 13:39:55 -0700881 setKernelTraceFuncs(nullptr);
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700882 setUserInitiatedTraceProperty(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700883}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800884
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700885// Enable tracing in the kernel.
886static bool startTrace()
887{
888 return setTracingEnabled(true);
889}
890
891// Disable tracing in the kernel.
892static void stopTrace()
893{
894 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800895}
896
Martijn Coenend9535872015-11-26 10:00:55 +0100897// Read data from the tracing pipe and forward to stdout
898static void streamTrace()
899{
900 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800901 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100902 if (traceFD == -1) {
903 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
904 strerror(errno), errno);
905 return;
906 }
907 while (!g_traceAborted) {
908 ssize_t bytes_read = read(traceFD, trace_data, 4096);
909 if (bytes_read > 0) {
910 write(STDOUT_FILENO, trace_data, bytes_read);
911 fflush(stdout);
912 } else {
913 if (!g_traceAborted) {
914 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
915 bytes_read, errno, strerror(errno));
916 }
917 break;
918 }
919 }
920}
921
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800922// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700923static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800924{
John Reck6c8ac922016-03-28 11:25:30 -0700925 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800926 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800927 if (traceFD == -1) {
928 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
929 strerror(errno), errno);
930 return;
931 }
932
933 if (g_compress) {
934 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800935 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700936
937 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800938 if (result != Z_OK) {
939 fprintf(stderr, "error initializing zlib: %d\n", result);
940 close(traceFD);
941 return;
942 }
943
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700944 constexpr size_t bufSize = 64*1024;
945 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
946 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
947 if (!in || !out) {
948 fprintf(stderr, "couldn't allocate buffers\n");
949 close(traceFD);
950 return;
951 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800952
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700953 int flush = Z_NO_FLUSH;
954
955 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800956 zs.avail_out = bufSize;
957
958 do {
959
960 if (zs.avail_in == 0) {
961 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700962 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800963 if (result < 0) {
964 fprintf(stderr, "error reading trace: %s (%d)\n",
965 strerror(errno), errno);
966 result = Z_STREAM_END;
967 break;
968 } else if (result == 0) {
969 flush = Z_FINISH;
970 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700971 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800972 zs.avail_in = result;
973 }
974 }
975
976 if (zs.avail_out == 0) {
977 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700978 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800979 if ((size_t)result < bufSize) {
980 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
981 strerror(errno), errno);
982 result = Z_STREAM_END; // skip deflate error message
983 zs.avail_out = bufSize; // skip the final write
984 break;
985 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700986 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800987 zs.avail_out = bufSize;
988 }
989
990 } while ((result = deflate(&zs, flush)) == Z_OK);
991
992 if (result != Z_STREAM_END) {
993 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
994 }
995
996 if (zs.avail_out < bufSize) {
997 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -0700998 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800999 if ((size_t)result < bytes) {
1000 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1001 strerror(errno), errno);
1002 }
1003 }
1004
1005 result = deflateEnd(&zs);
1006 if (result != Z_OK) {
1007 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1008 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001009 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001010 char buf[4096];
1011 ssize_t rc;
1012 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1013 if (!android::base::WriteFully(outFd, buf, rc)) {
1014 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1015 break;
1016 }
1017 }
1018 if (rc == -1) {
1019 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001020 }
1021 }
1022
1023 close(traceFD);
1024}
1025
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001026static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001027{
1028 if (!g_nohup) {
1029 g_traceAborted = true;
1030 }
1031}
1032
1033static void registerSigHandler()
1034{
1035 struct sigaction sa;
1036 sigemptyset(&sa.sa_mask);
1037 sa.sa_flags = 0;
1038 sa.sa_handler = handleSignal;
Yi Kong19d5c002018-07-20 13:39:55 -07001039 sigaction(SIGHUP, &sa, nullptr);
1040 sigaction(SIGINT, &sa, nullptr);
1041 sigaction(SIGQUIT, &sa, nullptr);
1042 sigaction(SIGTERM, &sa, nullptr);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001043}
1044
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001045static void listSupportedCategories()
1046{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001047 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001048 const TracingCategory& c = k_categories[i];
1049 if (isCategorySupported(c)) {
1050 printf(" %10s - %s\n", c.name, c.longname);
1051 }
1052 }
Wei Wang16a63a42018-09-21 15:47:45 -07001053 for (const auto &c : g_vendorCategories) {
1054 printf(" %10s - %s (HAL)\n", c.name.c_str(), c.description.c_str());
1055 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001056}
1057
1058// Print the command usage help to stderr.
1059static void showHelp(const char *cmd)
1060{
1061 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1062 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001063 " -a appname enable app-level tracing for a comma "
Daniel Colascione519a0792018-02-09 20:05:39 -08001064 "separated list of cmdlines; * is a wildcard matching any process\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001065 " -b N use a trace buffer size of N KB\n"
1066 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001067 " -f filename use the categories written in a file as space-separated\n"
1068 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001069 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001070 " -n ignore signals\n"
1071 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001072 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001073 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001074 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001075 " --async_dump dump the current contents of circular trace buffer\n"
1076 " --async_stop stop tracing and dump the current contents of circular\n"
1077 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001078 " --stream stream trace to stdout as it enters the trace buffer\n"
1079 " Note: this can take significant CPU time, and is best\n"
1080 " used for measuring things that are not affected by\n"
1081 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001082 " --list_categories\n"
1083 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001084 " -o filename write the trace to the specified file instead\n"
1085 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001086 );
1087}
1088
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001089bool findTraceFiles()
1090{
1091 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1092 static const std::string tracefs_path = "/sys/kernel/tracing/";
1093 static const std::string trace_file = "trace_marker";
1094
1095 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1096 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1097
1098 if (!tracefs && !debugfs) {
1099 fprintf(stderr, "Error: Did not find trace folder\n");
1100 return false;
1101 }
1102
1103 if (tracefs) {
1104 g_traceFolder = tracefs_path;
1105 } else {
1106 g_traceFolder = debugfs_path;
1107 }
1108
1109 return true;
1110}
1111
Wei Wang16a63a42018-09-21 15:47:45 -07001112void initVendorCategories()
1113{
1114 g_atraceHal = IAtraceDevice::getService();
1115
1116 if (g_atraceHal == nullptr) {
1117 // No atrace HAL
1118 return;
1119 }
1120
1121 Return<void> ret = g_atraceHal->listCategories(
1122 [](const auto& list) {
1123 g_vendorCategories.reserve(list.size());
1124 for (const auto& category : list) {
1125 g_vendorCategories.emplace_back(category.name, category.description, false);
1126 }
1127 });
1128 if (!ret.isOk()) {
1129 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1130 }
1131}
1132
1133static bool setUpVendorTracing()
1134{
1135 if (g_atraceHal == nullptr) {
1136 // No atrace HAL
1137 return true;
1138 }
1139
1140 std::vector<hidl_string> categories;
1141 for (const auto &c : g_vendorCategories) {
1142 if (c.enabled) {
1143 categories.emplace_back(c.name);
1144 }
1145 }
1146
1147 if (!categories.size()) {
1148 return true;
1149 }
1150
1151 auto ret = g_atraceHal->enableCategories(categories);
1152 if (!ret.isOk()) {
1153 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1154 return false;
1155 } else if (ret != Status::SUCCESS) {
1156 fprintf(stderr, "calling atrace HAL failed: %s\n", toString(ret).c_str());
1157 return false;
1158 }
1159 return true;
1160}
1161
1162static bool cleanUpVendorTracing()
1163{
1164 if (g_atraceHal == nullptr) {
1165 // No atrace HAL
1166 return true;
1167 }
1168
1169 if (!g_vendorCategories.size()) {
1170 // No vendor categories
1171 return true;
1172 }
1173
1174 auto ret = g_atraceHal->disableAllCategories();
1175 if (!ret.isOk()) {
1176 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1177 return false;
1178 } else if (ret != Status::SUCCESS) {
1179 fprintf(stderr, "calling atrace HAL failed: %s\n", toString(ret).c_str());
1180 return false;
1181 }
1182 return true;
1183}
1184
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001185int main(int argc, char **argv)
1186{
1187 bool async = false;
1188 bool traceStart = true;
1189 bool traceStop = true;
1190 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001191 bool traceStream = false;
Hector Dearman11845782018-03-08 14:35:44 +00001192 bool onlyUserspace = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001193
1194 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1195 showHelp(argv[0]);
1196 exit(0);
1197 }
1198
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001199 if (!findTraceFiles()) {
1200 fprintf(stderr, "No trace folder found\n");
1201 exit(-1);
1202 }
1203
Wei Wang16a63a42018-09-21 15:47:45 -07001204 initVendorCategories();
1205
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001206 for (;;) {
1207 int ret;
1208 int option_index = 0;
1209 static struct option long_options[] = {
Yi Kong19d5c002018-07-20 13:39:55 -07001210 {"async_start", no_argument, nullptr, 0 },
1211 {"async_stop", no_argument, nullptr, 0 },
1212 {"async_dump", no_argument, nullptr, 0 },
1213 {"only_userspace", no_argument, nullptr, 0 },
1214 {"list_categories", no_argument, nullptr, 0 },
1215 {"stream", no_argument, nullptr, 0 },
1216 {nullptr, 0, nullptr, 0 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001217 };
1218
John Reck40b26b42016-03-30 09:44:36 -07001219 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001220 long_options, &option_index);
1221
1222 if (ret < 0) {
1223 for (int i = optind; i < argc; i++) {
Wei Wang16a63a42018-09-21 15:47:45 -07001224 if (!setCategoryEnable(argv[i])) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001225 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1226 exit(1);
1227 }
1228 }
1229 break;
1230 }
1231
1232 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001233 case 'a':
1234 g_debugAppCmdLine = optarg;
1235 break;
1236
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001237 case 'b':
1238 g_traceBufferSizeKB = atoi(optarg);
1239 break;
1240
1241 case 'c':
1242 g_traceOverwrite = true;
1243 break;
1244
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001245 case 'f':
1246 g_categoriesFile = optarg;
1247 break;
1248
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001249 case 'k':
1250 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001251 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001252
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001253 case 'n':
1254 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001255 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001256
1257 case 's':
1258 g_initialSleepSecs = atoi(optarg);
1259 break;
1260
1261 case 't':
1262 g_traceDurationSeconds = atoi(optarg);
1263 break;
1264
1265 case 'z':
1266 g_compress = true;
1267 break;
1268
John Reck40b26b42016-03-30 09:44:36 -07001269 case 'o':
1270 g_outputFile = optarg;
1271 break;
1272
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001273 case 0:
1274 if (!strcmp(long_options[option_index].name, "async_start")) {
1275 async = true;
1276 traceStop = false;
1277 traceDump = false;
1278 g_traceOverwrite = true;
1279 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1280 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001281 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001282 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1283 async = true;
1284 traceStart = false;
1285 traceStop = false;
Hector Dearman11845782018-03-08 14:35:44 +00001286 } else if (!strcmp(long_options[option_index].name, "only_userspace")) {
1287 onlyUserspace = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001288 } else if (!strcmp(long_options[option_index].name, "stream")) {
1289 traceStream = true;
1290 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001291 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1292 listSupportedCategories();
1293 exit(0);
1294 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001295 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001296
1297 default:
1298 fprintf(stderr, "\n");
1299 showHelp(argv[0]);
1300 exit(-1);
1301 break;
1302 }
1303 }
1304
Hector Dearman11845782018-03-08 14:35:44 +00001305 if (onlyUserspace) {
1306 if (!async || !(traceStart || traceStop)) {
1307 fprintf(stderr, "--only_userspace can only be used with "
1308 "--async_start or --async_stop\n");
1309 exit(1);
1310 }
1311 }
1312
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001313 registerSigHandler();
1314
1315 if (g_initialSleepSecs > 0) {
1316 sleep(g_initialSleepSecs);
1317 }
1318
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001319 bool ok = true;
Hector Dearman11845782018-03-08 14:35:44 +00001320
Wei Wang5b73b742018-03-08 13:33:12 -08001321 if (traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001322 ok &= setUpUserspaceTracing();
1323 }
1324
1325 if (ok && traceStart && !onlyUserspace) {
1326 ok &= setUpKernelTracing();
Wei Wang16a63a42018-09-21 15:47:45 -07001327 ok &= setUpVendorTracing();
Wei Wang5b73b742018-03-08 13:33:12 -08001328 ok &= startTrace();
1329 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001330
1331 if (ok && traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001332
1333 if (!traceStream && !onlyUserspace) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001334 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001335 fflush(stdout);
1336 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001337
1338 // We clear the trace after starting it because tracing gets enabled for
1339 // each CPU individually in the kernel. Having the beginning of the trace
1340 // contain entries from only one CPU can cause "begin" entries without a
1341 // matching "end" entry to show up if a task gets migrated from one CPU to
1342 // another.
Hector Dearman11845782018-03-08 14:35:44 +00001343 if (!onlyUserspace)
1344 ok = clearTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001345
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001346 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001347 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001348 // Sleep to allow the trace to be captured.
1349 struct timespec timeLeft;
1350 timeLeft.tv_sec = g_traceDurationSeconds;
1351 timeLeft.tv_nsec = 0;
1352 do {
1353 if (g_traceAborted) {
1354 break;
1355 }
1356 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1357 }
Martijn Coenend9535872015-11-26 10:00:55 +01001358
1359 if (traceStream) {
1360 streamTrace();
1361 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001362 }
1363
1364 // Stop the trace and restore the default settings.
Hector Dearman11845782018-03-08 14:35:44 +00001365 if (traceStop && !onlyUserspace)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001366 stopTrace();
1367
Hector Dearman11845782018-03-08 14:35:44 +00001368 if (ok && traceDump && !onlyUserspace) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001369 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001370 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001371 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001372 int outFd = STDOUT_FILENO;
1373 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001374 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001375 }
1376 if (outFd == -1) {
1377 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1378 } else {
1379 dprintf(outFd, "TRACE:\n");
1380 dumpTrace(outFd);
1381 if (g_outputFile) {
1382 close(outFd);
1383 }
1384 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001385 } else {
1386 printf("\ntrace aborted.\n");
1387 fflush(stdout);
1388 }
1389 clearTrace();
1390 } else if (!ok) {
1391 fprintf(stderr, "unable to start tracing\n");
1392 }
1393
1394 // Reset the trace buffer size to 1.
Hector Dearman11845782018-03-08 14:35:44 +00001395 if (traceStop) {
1396 cleanUpUserspaceTracing();
Hector Dearmanada0a4a2019-04-09 14:13:14 +01001397 if (!onlyUserspace) {
1398 cleanUpVendorTracing();
Hector Dearman11845782018-03-08 14:35:44 +00001399 cleanUpKernelTracing();
Hector Dearmanada0a4a2019-04-09 14:13:14 +01001400 }
Hector Dearman11845782018-03-08 14:35:44 +00001401 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001402
1403 return g_traceAborted ? 1 : 0;
1404}