blob: 7ac0eb7d69f28abf2d9bd640bd4f3009bfe649de [file] [log] [blame]
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Paul Lawrence2cd93cc2017-01-17 09:50:18 -080017#define LOG_TAG "atrace"
John Reck40b26b42016-03-30 09:44:36 -070018
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080019#include <errno.h>
20#include <fcntl.h>
21#include <getopt.h>
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070022#include <inttypes.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080023#include <signal.h>
24#include <stdarg.h>
25#include <stdbool.h>
26#include <stdio.h>
27#include <stdlib.h>
Elliott Hughes3da5d232015-01-25 08:35:20 -080028#include <string.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080029#include <time.h>
Martijn Coenend9535872015-11-26 10:00:55 +010030#include <unistd.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080031#include <zlib.h>
32
Carmen Jacksonea826792017-05-05 11:42:32 -070033#include <fstream>
Elliott Hughesa252f4d2016-07-21 17:12:15 -070034#include <memory>
35
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080036#include <binder/IBinder.h>
37#include <binder/IServiceManager.h>
38#include <binder/Parcel.h>
39
Wei Wang16a63a42018-09-21 15:47:45 -070040#include <android/hardware/atrace/1.0/IAtraceDevice.h>
Martijn Coenenee9b97e2016-11-16 16:00:26 +010041#include <android/hidl/manager/1.0/IServiceManager.h>
42#include <hidl/ServiceManagement.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080043
Corey Tabakaa6c0a722017-05-31 16:37:40 -070044#include <pdx/default_transport/service_utility.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080045#include <utils/String8.h>
John Reck469a1942015-03-26 15:31:35 -070046#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +090047#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080048#include <utils/Trace.h>
Stephane Gasparinid8419c22016-03-02 13:45:15 +010049#include <android-base/file.h>
Elliott Hughes5fd6ff62017-03-28 14:55:31 -070050#include <android-base/macros.h>
51#include <android-base/properties.h>
52#include <android-base/stringprintf.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080053
54using namespace android;
Corey Tabakaa6c0a722017-05-31 16:37:40 -070055using pdx::default_transport::ServiceUtility;
Wei Wang16a63a42018-09-21 15:47:45 -070056using hardware::hidl_vec;
57using hardware::hidl_string;
58using hardware::Return;
59using hardware::atrace::V1_0::IAtraceDevice;
60using hardware::atrace::V1_0::Status;
61using hardware::atrace::V1_0::toString;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080062
Martijn Coenenee9b97e2016-11-16 16:00:26 +010063using std::string;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080064
Carmen Jackson63ea2912019-04-26 10:41:00 -070065#define MAX_SYS_FILES 11
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080066
67const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
Carmen Jackson65ecfbb2018-05-22 10:29:47 -070068const char* k_userInitiatedTraceProperty = "debug.atrace.user_initiated";
sergeyv4144eff2016-04-28 11:40:04 -070069
70const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
71const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070072const char* k_coreServiceCategory = "core_services";
Corey Tabakaa6c0a722017-05-31 16:37:40 -070073const char* k_pdxServiceCategory = "pdx";
sergeyvdb404152016-05-02 19:26:07 -070074const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080075
76typedef enum { OPT, REQ } requiredness ;
77
78struct TracingCategory {
79 // The name identifying the category.
80 const char* name;
81
82 // A longer description of the category.
83 const char* longname;
84
85 // The userland tracing tags that the category enables.
86 uint64_t tags;
87
88 // The fname==NULL terminated list of /sys/ files that the category
89 // enables.
90 struct {
91 // Whether the file must be writable in order to enable the tracing
92 // category.
93 requiredness required;
94
95 // The path to the enable file.
96 const char* path;
97 } sysfiles[MAX_SYS_FILES];
98};
99
100/* Tracing categories */
101static const TracingCategory k_categories[] = {
MÃ¥rten Kongstad2d4f89b2018-12-03 12:58:56 +0100102 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, { } },
103 { "input", "Input", ATRACE_TAG_INPUT, { } },
104 { "view", "View System", ATRACE_TAG_VIEW, { } },
105 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
106 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
107 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
108 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
109 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
110 { "video", "Video", ATRACE_TAG_VIDEO, { } },
111 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
112 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
113 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
114 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
115 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
116 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
117 { "power", "Power Management", ATRACE_TAG_POWER, { } },
118 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
119 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
120 { "database", "Database", ATRACE_TAG_DATABASE, { } },
121 { "network", "Network", ATRACE_TAG_NETWORK, { } },
122 { "adb", "ADB", ATRACE_TAG_ADB, { } },
123 { "vibrator", "Vibrator", ATRACE_TAG_VIBRATOR, { } },
124 { "aidl", "AIDL calls", ATRACE_TAG_AIDL, { } },
125 { "nnapi", "NNAPI", ATRACE_TAG_NNAPI, { } },
126 { "rro", "Runtime Resource Overlay", ATRACE_TAG_RRO, { } },
sergeyvdb404152016-05-02 19:26:07 -0700127 { k_coreServiceCategory, "Core services", 0, { } },
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700128 { k_pdxServiceCategory, "PDX services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700129 { "sched", "CPU Scheduling", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800130 { REQ, "events/sched/sched_switch/enable" },
131 { REQ, "events/sched/sched_wakeup/enable" },
Joel Fernandesee593e22017-06-04 13:05:59 -0700132 { OPT, "events/sched/sched_waking/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800133 { OPT, "events/sched/sched_blocked_reason/enable" },
134 { OPT, "events/sched/sched_cpu_hotplug/enable" },
Wei Wangca49dfc2018-05-03 15:45:20 -0700135 { OPT, "events/sched/sched_pi_setprio/enable" },
Carmen Jackson63ea2912019-04-26 10:41:00 -0700136 { OPT, "events/sched/sched_process_exit/enable" },
Joel Fernandes4dfca7c2017-06-15 16:53:52 -0700137 { OPT, "events/cgroup/enable" },
Carmen Jackson63ea2912019-04-26 10:41:00 -0700138 { OPT, "events/oom/oom_score_adj_update/enable" },
139 { OPT, "events/task/task_rename/enable" },
140 { OPT, "events/task/task_newtask/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800141 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700142 { "irq", "IRQ Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800143 { REQ, "events/irq/enable" },
144 { OPT, "events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700145 } },
Joel Fernandes6ccad102017-08-31 08:35:05 -0700146 { "irqoff", "IRQ-disabled code section tracing", 0, {
147 { REQ, "events/preemptirq/irq_enable/enable" },
148 { REQ, "events/preemptirq/irq_disable/enable" },
149 } },
150 { "preemptoff", "Preempt-disabled code section tracing", 0, {
151 { REQ, "events/preemptirq/preempt_enable/enable" },
152 { REQ, "events/preemptirq/preempt_disable/enable" },
153 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100154 { "i2c", "I2C Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800155 { REQ, "events/i2c/enable" },
156 { REQ, "events/i2c/i2c_read/enable" },
157 { REQ, "events/i2c/i2c_write/enable" },
158 { REQ, "events/i2c/i2c_result/enable" },
159 { REQ, "events/i2c/i2c_reply/enable" },
160 { OPT, "events/i2c/smbus_read/enable" },
161 { OPT, "events/i2c/smbus_write/enable" },
162 { OPT, "events/i2c/smbus_result/enable" },
163 { OPT, "events/i2c/smbus_reply/enable" },
Michael Wright43fb6782016-08-18 19:56:43 +0100164 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700165 { "freq", "CPU Frequency", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800166 { REQ, "events/power/cpu_frequency/enable" },
167 { OPT, "events/power/clock_set_rate/enable" },
Kevin DuBois062e0b92017-11-03 15:44:08 -0700168 { OPT, "events/power/clock_disable/enable" },
169 { OPT, "events/power/clock_enable/enable" },
Wei Wang53305dd2018-02-22 11:40:07 -0800170 { OPT, "events/clk/clk_set_rate/enable" },
171 { OPT, "events/clk/clk_disable/enable" },
172 { OPT, "events/clk/clk_enable/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800173 { OPT, "events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800174 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700175 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800176 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800177 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700178 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800179 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800180 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700181 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800182 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
183 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
184 { OPT, "events/f2fs/f2fs_write_begin/enable" },
185 { OPT, "events/f2fs/f2fs_write_end/enable" },
186 { OPT, "events/ext4/ext4_da_write_begin/enable" },
187 { OPT, "events/ext4/ext4_da_write_end/enable" },
188 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
189 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
190 { REQ, "events/block/block_rq_issue/enable" },
191 { REQ, "events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800192 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700193 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800194 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700195 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700196 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800197 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800198 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700199 { "sync", "Synchronization", 0, {
Jesse Halla978cef2019-02-25 16:24:10 -0800200 // linux kernel < 4.9
Jesse Hallae001a32018-05-15 12:02:15 -0700201 { OPT, "events/sync/enable" },
Jesse Halla978cef2019-02-25 16:24:10 -0800202 // linux kernel == 4.9.x
Jesse Hallae001a32018-05-15 12:02:15 -0700203 { OPT, "events/fence/enable" },
Jesse Halla978cef2019-02-25 16:24:10 -0800204 // linux kernel > 4.9
205 { OPT, "events/dma_fence/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800206 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700207 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800208 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800209 } },
Colin Cross580407f2014-08-18 15:22:13 -0700210 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800211 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
212 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
213 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
214 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Carmen Jackson7a23eb72018-07-02 13:14:56 -0700215 { OPT, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700216 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800217 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800218 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800219 } },
Scott Bauerae473362015-06-08 16:32:36 -0700220 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800221 { REQ, "events/binder/binder_transaction/enable" },
222 { REQ, "events/binder/binder_transaction_received/enable" },
Mika Raento80c3e5d2018-06-25 16:47:24 +0100223 { REQ, "events/binder/binder_transaction_alloc_buf/enable" },
Martijn Coenen7f3d7a22017-05-26 09:50:55 -0700224 { OPT, "events/binder/binder_set_priority/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700225 } },
226 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800227 { OPT, "events/binder/binder_lock/enable" },
228 { OPT, "events/binder/binder_locked/enable" },
229 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700230 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200231 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800232 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200233 } },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700234 { "memory", "Memory", 0, {
235 { OPT, "events/kmem/rss_stat/enable" },
236 { OPT, "events/kmem/ion_heap_grow/enable" },
237 { OPT, "events/kmem/ion_heap_shrink/enable" },
238 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800239};
240
Wei Wang16a63a42018-09-21 15:47:45 -0700241struct TracingVendorCategory {
242 // The name identifying the category.
243 std::string name;
244
245 // A longer description of the category.
246 std::string description;
247
248 // If the category is enabled through command.
249 bool enabled;
250
251 TracingVendorCategory(string &&name, string &&description, bool enabled)
252 : name(std::move(name))
253 , description(std::move(description))
254 , enabled(enabled)
255 {}
256};
257
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800258/* Command line options */
259static int g_traceDurationSeconds = 5;
260static bool g_traceOverwrite = false;
261static int g_traceBufferSizeKB = 2048;
262static bool g_compress = false;
263static bool g_nohup = false;
264static int g_initialSleepSecs = 0;
Yi Kong19d5c002018-07-20 13:39:55 -0700265static const char* g_categoriesFile = nullptr;
266static const char* g_kernelTraceFuncs = nullptr;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700267static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700268static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800269
270/* Global state */
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700271static bool g_tracePdx = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800272static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700273static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800274static std::string g_traceFolder;
Wei Wang16a63a42018-09-21 15:47:45 -0700275static sp<IAtraceDevice> g_atraceHal;
276static std::vector<TracingVendorCategory> g_vendorCategories;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800277
278/* Sys file paths */
279static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800280 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800281
282static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800283 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800284
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700285#if 0
286// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700287static const char* k_traceCmdlineSizePath =
288 "saved_cmdlines_size";
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700289#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700290
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800291static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800292 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800293
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700294static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800295 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700296
297static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800298 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700299
John Recke757b1c2018-06-28 12:24:33 -0700300static const char* k_recordTgidPath =
301 "options/record-tgid";
302
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700303static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800304 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700305
306static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800307 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700308
309static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800310 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700311
312static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800313 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700314
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700315static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800316 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700317
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800318static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800319 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800320
321static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800322 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800323
Martijn Coenend9535872015-11-26 10:00:55 +0100324static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800325 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100326
John Reck469a1942015-03-26 15:31:35 -0700327static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800328 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700329
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800330// Check whether a file exists.
331static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800332 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800333}
334
335// Check whether a file is writable.
336static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800337 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800338}
339
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700340// Truncate a file.
341static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800342{
Jamie Gennis43122e72013-03-21 14:06:31 -0700343 // This uses creat rather than truncate because some of the debug kernel
344 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
345 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800346 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700347 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800348 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700349 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700350 return false;
351 }
352
Jamie Gennis43122e72013-03-21 14:06:31 -0700353 close(traceFD);
354
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700355 return true;
356}
357
358static bool _writeStr(const char* filename, const char* str, int flags)
359{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800360 std::string fullFilename = g_traceFolder + filename;
361 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800362 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800363 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800364 strerror(errno), errno);
365 return false;
366 }
367
368 bool ok = true;
369 ssize_t len = strlen(str);
370 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800371 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800372 strerror(errno), errno);
373 ok = false;
374 }
375
376 close(fd);
377
378 return ok;
379}
380
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700381// Write a string to a file, returning true if the write was successful.
382static bool writeStr(const char* filename, const char* str)
383{
384 return _writeStr(filename, str, O_WRONLY);
385}
386
387// Append a string to a file, returning true if the write was successful.
388static bool appendStr(const char* filename, const char* str)
389{
390 return _writeStr(filename, str, O_APPEND|O_WRONLY);
391}
392
John Reck469a1942015-03-26 15:31:35 -0700393static void writeClockSyncMarker()
394{
395 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200396 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800397 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200398 if (fd == -1) {
399 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
400 strerror(errno), errno);
401 return;
402 }
John Reck469a1942015-03-26 15:31:35 -0700403 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200404
405 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
406 if (write(fd, buffer, len) != len) {
407 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
408 }
409
410 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
411 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
412 if (write(fd, buffer, len) != len) {
413 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
414 }
415
416 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700417}
418
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800419// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
420// file.
421static bool setKernelOptionEnable(const char* filename, bool enable)
422{
423 return writeStr(filename, enable ? "1" : "0");
424}
425
426// Check whether the category is supported on the device with the current
427// rootness. A category is supported only if all its required /sys/ files are
428// writable and if enabling the category will enable one or more tracing tags
429// or /sys/ files.
430static bool isCategorySupported(const TracingCategory& category)
431{
sergeyvdb404152016-05-02 19:26:07 -0700432 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700433 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700434 }
435
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700436 if (strcmp(category.name, k_pdxServiceCategory) == 0) {
437 return true;
438 }
439
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800440 bool ok = category.tags != 0;
441 for (int i = 0; i < MAX_SYS_FILES; i++) {
442 const char* path = category.sysfiles[i].path;
443 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700444 if (path != nullptr) {
Carmen Jackson5bbc9a22018-12-06 13:47:18 -0800445 if (fileIsWritable(path)) {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800446 ok = true;
Carmen Jackson5bbc9a22018-12-06 13:47:18 -0800447 } else if (req) {
448 return false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800449 }
450 }
451 }
452 return ok;
453}
454
455// Check whether the category would be supported on the device if the user
456// were root. This function assumes that root is able to write to any file
457// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700458// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800459static bool isCategorySupportedForRoot(const TracingCategory& category)
460{
461 bool ok = category.tags != 0;
462 for (int i = 0; i < MAX_SYS_FILES; i++) {
463 const char* path = category.sysfiles[i].path;
464 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700465 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800466 if (req) {
467 if (!fileExists(path)) {
468 return false;
469 } else {
470 ok = true;
471 }
472 } else {
473 ok |= fileExists(path);
474 }
475 }
476 }
477 return ok;
478}
479
480// Enable or disable overwriting of the kernel trace buffers. Disabling this
481// will cause tracing to stop once the trace buffers have filled up.
482static bool setTraceOverwriteEnable(bool enable)
483{
484 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
485}
486
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700487// Set the user initiated trace property
488static bool setUserInitiatedTraceProperty(bool enable)
489{
490 if (!android::base::SetProperty(k_userInitiatedTraceProperty, enable ? "1" : "")) {
491 fprintf(stderr, "error setting user initiated strace system property\n");
492 return false;
493 }
494 return true;
495}
496
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800497// Enable or disable kernel tracing.
498static bool setTracingEnabled(bool enable)
499{
500 return setKernelOptionEnable(k_tracingOnPath, enable);
501}
502
503// Clear the contents of the kernel trace.
504static bool clearTrace()
505{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700506 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800507}
508
509// Set the size of the kernel's trace buffer in kilobytes.
510static bool setTraceBufferSizeKB(int size)
511{
512 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800513 if (size < 1) {
514 size = 1;
515 }
516 snprintf(str, 32, "%d", size);
517 return writeStr(k_traceBufferSizePath, str);
518}
519
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700520#if 0
521// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700522// Set the default size of cmdline hashtable
523static bool setCmdlineSize()
524{
Joel Fernandesce964f22017-06-06 12:20:29 -0700525 if (fileExists(k_traceCmdlineSizePath)) {
526 return writeStr(k_traceCmdlineSizePath, "8192");
527 }
528 return true;
Joel Fernandesed80bd02017-06-02 10:19:28 -0700529}
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700530#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700531
Carmen Jacksonea826792017-05-05 11:42:32 -0700532// Set the clock to the best available option while tracing. Use 'boot' if it's
533// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700534// Any write to the trace_clock sysfs file will reset the buffer, so only
535// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700536static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800537{
Carmen Jacksonea826792017-05-05 11:42:32 -0700538 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
539 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
540 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700541
Carmen Jacksonea826792017-05-05 11:42:32 -0700542 std::string newClock;
543 if (clockStr.find("boot") != std::string::npos) {
544 newClock = "boot";
545 } else if (clockStr.find("mono") != std::string::npos) {
546 newClock = "mono";
547 } else {
548 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700549 }
550
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700551 size_t begin = clockStr.find('[') + 1;
552 size_t end = clockStr.find(']');
Carmen Jacksonea826792017-05-05 11:42:32 -0700553 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
554 return true;
555 }
556 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800557}
558
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700559static bool setPrintTgidEnableIfPresent(bool enable)
560{
John Reckedbf9ec2018-06-29 11:15:17 -0700561 // Pre-4.13 this was options/print-tgid as an android-specific option.
562 // In 4.13+ this is an upstream option called options/record-tgid
563 // Both options produce the same ftrace format change
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700564 if (fileExists(k_printTgidPath)) {
565 return setKernelOptionEnable(k_printTgidPath, enable);
566 }
John Recke757b1c2018-06-28 12:24:33 -0700567 if (fileExists(k_recordTgidPath)) {
568 return setKernelOptionEnable(k_recordTgidPath, enable);
569 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700570 return true;
571}
572
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800573// Poke all the binder-enabled processes in the system to get them to re-read
574// their system properties.
575static bool pokeBinderServices()
576{
577 sp<IServiceManager> sm = defaultServiceManager();
578 Vector<String16> services = sm->listServices();
579 for (size_t i = 0; i < services.size(); i++) {
580 sp<IBinder> obj = sm->checkService(services[i]);
Yi Kong19d5c002018-07-20 13:39:55 -0700581 if (obj != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800582 Parcel data;
583 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
Yi Kong19d5c002018-07-20 13:39:55 -0700584 nullptr, 0) != OK) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800585 if (false) {
586 // XXX: For some reason this fails on tablets trying to
587 // poke the "phone" service. It's not clear whether some
588 // are expected to fail.
589 String8 svc(services[i]);
590 fprintf(stderr, "error poking binder service %s\n",
591 svc.string());
592 return false;
593 }
594 }
595 }
596 }
597 return true;
598}
599
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100600// Poke all the HAL processes in the system to get them to re-read
601// their system properties.
602static void pokeHalServices()
603{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100604 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100605 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100606 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100607 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100608
609 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800610
611 if (sm == nullptr) {
612 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
613 return;
614 }
615
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800616 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100617 for (size_t i = 0; i < interfaces.size(); i++) {
618 string fqInstanceName = interfaces[i];
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700619 string::size_type n = fqInstanceName.find('/');
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100620 if (n == std::string::npos || interfaces[i].size() == n+1)
621 continue;
622 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
623 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100624 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
625 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100626 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100627 continue;
628 }
Carmen Jackson73206122017-04-18 15:37:57 -0700629
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100630 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700631 if (interface == nullptr) {
632 // ignore
633 continue;
634 }
635
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100636 auto notifyRet = interface->notifySyspropsChanged();
637 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100638 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800639 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100640 }
641 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800642 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100643 // TODO(b/34242478) fix this when we determine the correct ACL
644 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800645 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100646}
647
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800648// Set the trace tags that userland tracing uses, and poke the running
649// processes to pick up the new value.
650static bool setTagsProperty(uint64_t tags)
651{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700652 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
653 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800654 fprintf(stderr, "error setting trace tags system property\n");
655 return false;
656 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700657 return true;
658}
659
sergeyv4144eff2016-04-28 11:40:04 -0700660static void clearAppProperties()
661{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700662 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700663 fprintf(stderr, "failed to clear system property: %s",
664 k_traceAppsNumberProperty);
665 }
666}
667
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700668// Set the system property that indicates which apps should perform
669// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700670static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700671{
sergeyv4144eff2016-04-28 11:40:04 -0700672 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700673 char* start = cmdline;
Yi Kong19d5c002018-07-20 13:39:55 -0700674 while (start != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700675 char* end = strchr(start, ',');
Yi Kong19d5c002018-07-20 13:39:55 -0700676 if (end != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700677 *end = '\0';
678 end++;
679 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700680 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
681 if (!android::base::SetProperty(key, start)) {
682 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700683 clearAppProperties();
684 return false;
685 }
686 start = end;
687 i++;
688 }
689
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700690 std::string value = android::base::StringPrintf("%d", i);
691 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
692 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700693 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700694 return false;
695 }
696 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800697}
698
699// Disable all /sys/ enable files.
700static bool disableKernelTraceEvents() {
701 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700702 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800703 const TracingCategory &c = k_categories[i];
704 for (int j = 0; j < MAX_SYS_FILES; j++) {
705 const char* path = c.sysfiles[j].path;
Yi Kong19d5c002018-07-20 13:39:55 -0700706 if (path != nullptr && fileIsWritable(path)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800707 ok &= setKernelOptionEnable(path, false);
708 }
709 }
710 }
711 return ok;
712}
713
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700714// Verify that the comma separated list of functions are being traced by the
715// kernel.
716static bool verifyKernelTraceFuncs(const char* funcs)
717{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100718 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800719 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100720 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700721 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100722 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700723 }
724
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100725 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700726
727 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100728 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700729 bool ok = true;
730 char* myFuncs = strdup(funcs);
731 char* func = strtok(myFuncs, ",");
732 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100733 if (!strchr(func, '*')) {
734 String8 fancyFunc = String8::format("\n%s\n", func);
735 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
736 if (!found || func[0] == '\0') {
737 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
738 "to trace.\n", func);
739 ok = false;
740 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700741 }
Yi Kong19d5c002018-07-20 13:39:55 -0700742 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700743 }
744 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700745 return ok;
746}
747
748// Set the comma separated list of functions that the kernel is to trace.
749static bool setKernelTraceFuncs(const char* funcs)
750{
751 bool ok = true;
752
Yi Kong19d5c002018-07-20 13:39:55 -0700753 if (funcs == nullptr || funcs[0] == '\0') {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700754 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700755 if (fileIsWritable(k_currentTracerPath)) {
756 ok &= writeStr(k_currentTracerPath, "nop");
757 }
758 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700759 ok &= truncateFile(k_ftraceFilterPath);
760 }
761 } else {
762 // Enable kernel function tracing.
763 ok &= writeStr(k_currentTracerPath, "function_graph");
764 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
765 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
766 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
767 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
768
769 // Set the requested filter functions.
770 ok &= truncateFile(k_ftraceFilterPath);
771 char* myFuncs = strdup(funcs);
772 char* func = strtok(myFuncs, ",");
773 while (func) {
774 ok &= appendStr(k_ftraceFilterPath, func);
Yi Kong19d5c002018-07-20 13:39:55 -0700775 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700776 }
777 free(myFuncs);
778
779 // Verify that the set functions are being traced.
780 if (ok) {
781 ok &= verifyKernelTraceFuncs(funcs);
782 }
783 }
784
785 return ok;
786}
787
Wei Wang16a63a42018-09-21 15:47:45 -0700788static bool setCategoryEnable(const char* name)
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900789{
Wei Wang16a63a42018-09-21 15:47:45 -0700790 bool vendor_found = false;
791 for (auto &c : g_vendorCategories) {
792 if (strcmp(name, c.name.c_str()) == 0) {
793 c.enabled = true;
794 vendor_found = true;
795 }
796 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700797 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900798 const TracingCategory& c = k_categories[i];
799 if (strcmp(name, c.name) == 0) {
800 if (isCategorySupported(c)) {
Wei Wang16a63a42018-09-21 15:47:45 -0700801 g_categoryEnables[i] = true;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900802 return true;
803 } else {
804 if (isCategorySupportedForRoot(c)) {
805 fprintf(stderr, "error: category \"%s\" requires root "
806 "privileges.\n", name);
807 } else {
808 fprintf(stderr, "error: category \"%s\" is not supported "
809 "on this device.\n", name);
810 }
811 return false;
812 }
813 }
814 }
Wei Wang16a63a42018-09-21 15:47:45 -0700815 if (vendor_found) {
816 return true;
817 }
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900818 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
819 return false;
820}
821
822static bool setCategoriesEnableFromFile(const char* categories_file)
823{
824 if (!categories_file) {
825 return true;
826 }
Yi Kong19d5c002018-07-20 13:39:55 -0700827 Tokenizer* tokenizer = nullptr;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900828 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
829 return false;
830 }
831 bool ok = true;
832 while (!tokenizer->isEol()) {
833 String8 token = tokenizer->nextToken(" ");
834 if (token.isEmpty()) {
835 tokenizer->skipDelimiters(" ");
836 continue;
837 }
Wei Wang16a63a42018-09-21 15:47:45 -0700838 ok &= setCategoryEnable(token.string());
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900839 }
840 delete tokenizer;
841 return ok;
842}
843
Hector Dearman11845782018-03-08 14:35:44 +0000844static bool setUpUserspaceTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800845{
846 bool ok = true;
847
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800848 // Set up the tags property.
849 uint64_t tags = 0;
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 tags |= c.tags;
854 }
855 }
856 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700857
858 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700859 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700860 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
861 coreServicesTagEnabled = g_categoryEnables[i];
862 }
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700863
864 // Set whether to poke PDX services in this session.
865 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
866 g_tracePdx = g_categoryEnables[i];
867 }
sergeyvdb404152016-05-02 19:26:07 -0700868 }
869
870 std::string packageList(g_debugAppCmdLine);
871 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700872 if (!packageList.empty()) {
873 packageList += ",";
874 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700875 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700876 }
Dan Austin09a79872016-05-31 13:27:03 -0700877 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700878 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100879 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800880
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700881 if (g_tracePdx) {
882 ok &= ServiceUtility::PokeServices();
883 }
884
Hector Dearman11845782018-03-08 14:35:44 +0000885 return ok;
886}
887
888static void cleanUpUserspaceTracing()
889{
890 setTagsProperty(0);
891 clearAppProperties();
892 pokeBinderServices();
893
894 if (g_tracePdx) {
895 ServiceUtility::PokeServices();
896 }
897}
898
899
900// Set all the kernel tracing settings to the desired state for this trace
901// capture.
902static bool setUpKernelTracing()
903{
904 bool ok = true;
905
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700906 ok &= setUserInitiatedTraceProperty(true);
907
Hector Dearman11845782018-03-08 14:35:44 +0000908 // Set up the tracing options.
909 ok &= setCategoriesEnableFromFile(g_categoriesFile);
910 ok &= setTraceOverwriteEnable(g_traceOverwrite);
911 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
912 // TODO: Re-enable after stabilization
913 //ok &= setCmdlineSize();
914 ok &= setClock();
915 ok &= setPrintTgidEnableIfPresent(true);
916 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
917
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800918 // Disable all the sysfs enables. This is done as a separate loop from
919 // the enables to allow the same enable to exist in multiple categories.
920 ok &= disableKernelTraceEvents();
921
922 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700923 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800924 if (g_categoryEnables[i]) {
925 const TracingCategory &c = k_categories[i];
926 for (int j = 0; j < MAX_SYS_FILES; j++) {
927 const char* path = c.sysfiles[j].path;
928 bool required = c.sysfiles[j].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700929 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800930 if (fileIsWritable(path)) {
931 ok &= setKernelOptionEnable(path, true);
932 } else if (required) {
933 fprintf(stderr, "error writing file %s\n", path);
934 ok = false;
935 }
936 }
937 }
938 }
939 }
940
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800941 return ok;
942}
943
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700944// Reset all the kernel tracing settings to their default state.
Hector Dearman11845782018-03-08 14:35:44 +0000945static void cleanUpKernelTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800946{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800947 // Disable all tracing that we're able to.
948 disableKernelTraceEvents();
949
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800950 // Set the options back to their defaults.
951 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700952 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700953 setPrintTgidEnableIfPresent(false);
Yi Kong19d5c002018-07-20 13:39:55 -0700954 setKernelTraceFuncs(nullptr);
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700955 setUserInitiatedTraceProperty(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700956}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800957
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700958// Enable tracing in the kernel.
959static bool startTrace()
960{
961 return setTracingEnabled(true);
962}
963
964// Disable tracing in the kernel.
965static void stopTrace()
966{
967 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800968}
969
Martijn Coenend9535872015-11-26 10:00:55 +0100970// Read data from the tracing pipe and forward to stdout
971static void streamTrace()
972{
973 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800974 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100975 if (traceFD == -1) {
976 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
977 strerror(errno), errno);
978 return;
979 }
980 while (!g_traceAborted) {
981 ssize_t bytes_read = read(traceFD, trace_data, 4096);
982 if (bytes_read > 0) {
983 write(STDOUT_FILENO, trace_data, bytes_read);
984 fflush(stdout);
985 } else {
986 if (!g_traceAborted) {
987 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
988 bytes_read, errno, strerror(errno));
989 }
990 break;
991 }
992 }
993}
994
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800995// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700996static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800997{
John Reck6c8ac922016-03-28 11:25:30 -0700998 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800999 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001000 if (traceFD == -1) {
1001 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
1002 strerror(errno), errno);
1003 return;
1004 }
1005
1006 if (g_compress) {
1007 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -08001008 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001009
1010 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001011 if (result != Z_OK) {
1012 fprintf(stderr, "error initializing zlib: %d\n", result);
1013 close(traceFD);
1014 return;
1015 }
1016
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001017 constexpr size_t bufSize = 64*1024;
1018 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
1019 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
1020 if (!in || !out) {
1021 fprintf(stderr, "couldn't allocate buffers\n");
1022 close(traceFD);
1023 return;
1024 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001025
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001026 int flush = Z_NO_FLUSH;
1027
1028 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001029 zs.avail_out = bufSize;
1030
1031 do {
1032
1033 if (zs.avail_in == 0) {
1034 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001035 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001036 if (result < 0) {
1037 fprintf(stderr, "error reading trace: %s (%d)\n",
1038 strerror(errno), errno);
1039 result = Z_STREAM_END;
1040 break;
1041 } else if (result == 0) {
1042 flush = Z_FINISH;
1043 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001044 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001045 zs.avail_in = result;
1046 }
1047 }
1048
1049 if (zs.avail_out == 0) {
1050 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -07001051 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001052 if ((size_t)result < bufSize) {
1053 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1054 strerror(errno), errno);
1055 result = Z_STREAM_END; // skip deflate error message
1056 zs.avail_out = bufSize; // skip the final write
1057 break;
1058 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001059 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001060 zs.avail_out = bufSize;
1061 }
1062
1063 } while ((result = deflate(&zs, flush)) == Z_OK);
1064
1065 if (result != Z_STREAM_END) {
1066 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
1067 }
1068
1069 if (zs.avail_out < bufSize) {
1070 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -07001071 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001072 if ((size_t)result < bytes) {
1073 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1074 strerror(errno), errno);
1075 }
1076 }
1077
1078 result = deflateEnd(&zs);
1079 if (result != Z_OK) {
1080 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1081 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001082 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001083 char buf[4096];
1084 ssize_t rc;
1085 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1086 if (!android::base::WriteFully(outFd, buf, rc)) {
1087 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1088 break;
1089 }
1090 }
1091 if (rc == -1) {
1092 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001093 }
1094 }
1095
1096 close(traceFD);
1097}
1098
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001099static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001100{
1101 if (!g_nohup) {
1102 g_traceAborted = true;
1103 }
1104}
1105
1106static void registerSigHandler()
1107{
1108 struct sigaction sa;
1109 sigemptyset(&sa.sa_mask);
1110 sa.sa_flags = 0;
1111 sa.sa_handler = handleSignal;
Yi Kong19d5c002018-07-20 13:39:55 -07001112 sigaction(SIGHUP, &sa, nullptr);
1113 sigaction(SIGINT, &sa, nullptr);
1114 sigaction(SIGQUIT, &sa, nullptr);
1115 sigaction(SIGTERM, &sa, nullptr);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001116}
1117
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001118static void listSupportedCategories()
1119{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001120 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001121 const TracingCategory& c = k_categories[i];
1122 if (isCategorySupported(c)) {
1123 printf(" %10s - %s\n", c.name, c.longname);
1124 }
1125 }
Wei Wang16a63a42018-09-21 15:47:45 -07001126 for (const auto &c : g_vendorCategories) {
1127 printf(" %10s - %s (HAL)\n", c.name.c_str(), c.description.c_str());
1128 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001129}
1130
1131// Print the command usage help to stderr.
1132static void showHelp(const char *cmd)
1133{
1134 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1135 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001136 " -a appname enable app-level tracing for a comma "
Daniel Colascione519a0792018-02-09 20:05:39 -08001137 "separated list of cmdlines; * is a wildcard matching any process\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001138 " -b N use a trace buffer size of N KB\n"
1139 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001140 " -f filename use the categories written in a file as space-separated\n"
1141 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001142 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001143 " -n ignore signals\n"
1144 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001145 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001146 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001147 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001148 " --async_dump dump the current contents of circular trace buffer\n"
1149 " --async_stop stop tracing and dump the current contents of circular\n"
1150 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001151 " --stream stream trace to stdout as it enters the trace buffer\n"
1152 " Note: this can take significant CPU time, and is best\n"
1153 " used for measuring things that are not affected by\n"
1154 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001155 " --list_categories\n"
1156 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001157 " -o filename write the trace to the specified file instead\n"
1158 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001159 );
1160}
1161
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001162bool findTraceFiles()
1163{
1164 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1165 static const std::string tracefs_path = "/sys/kernel/tracing/";
1166 static const std::string trace_file = "trace_marker";
1167
1168 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1169 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1170
1171 if (!tracefs && !debugfs) {
1172 fprintf(stderr, "Error: Did not find trace folder\n");
1173 return false;
1174 }
1175
1176 if (tracefs) {
1177 g_traceFolder = tracefs_path;
1178 } else {
1179 g_traceFolder = debugfs_path;
1180 }
1181
1182 return true;
1183}
1184
Wei Wang16a63a42018-09-21 15:47:45 -07001185void initVendorCategories()
1186{
1187 g_atraceHal = IAtraceDevice::getService();
1188
1189 if (g_atraceHal == nullptr) {
1190 // No atrace HAL
1191 return;
1192 }
1193
1194 Return<void> ret = g_atraceHal->listCategories(
1195 [](const auto& list) {
1196 g_vendorCategories.reserve(list.size());
1197 for (const auto& category : list) {
1198 g_vendorCategories.emplace_back(category.name, category.description, false);
1199 }
1200 });
1201 if (!ret.isOk()) {
1202 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1203 }
1204}
1205
1206static bool setUpVendorTracing()
1207{
1208 if (g_atraceHal == nullptr) {
1209 // No atrace HAL
1210 return true;
1211 }
1212
1213 std::vector<hidl_string> categories;
1214 for (const auto &c : g_vendorCategories) {
1215 if (c.enabled) {
1216 categories.emplace_back(c.name);
1217 }
1218 }
1219
1220 if (!categories.size()) {
1221 return true;
1222 }
1223
1224 auto ret = g_atraceHal->enableCategories(categories);
1225 if (!ret.isOk()) {
1226 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1227 return false;
1228 } else if (ret != Status::SUCCESS) {
1229 fprintf(stderr, "calling atrace HAL failed: %s\n", toString(ret).c_str());
1230 return false;
1231 }
1232 return true;
1233}
1234
1235static bool cleanUpVendorTracing()
1236{
1237 if (g_atraceHal == nullptr) {
1238 // No atrace HAL
1239 return true;
1240 }
1241
1242 if (!g_vendorCategories.size()) {
1243 // No vendor categories
1244 return true;
1245 }
1246
1247 auto ret = g_atraceHal->disableAllCategories();
1248 if (!ret.isOk()) {
1249 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1250 return false;
1251 } else if (ret != Status::SUCCESS) {
1252 fprintf(stderr, "calling atrace HAL failed: %s\n", toString(ret).c_str());
1253 return false;
1254 }
1255 return true;
1256}
1257
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001258int main(int argc, char **argv)
1259{
1260 bool async = false;
1261 bool traceStart = true;
1262 bool traceStop = true;
1263 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001264 bool traceStream = false;
Hector Dearman11845782018-03-08 14:35:44 +00001265 bool onlyUserspace = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001266
1267 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1268 showHelp(argv[0]);
1269 exit(0);
1270 }
1271
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001272 if (!findTraceFiles()) {
1273 fprintf(stderr, "No trace folder found\n");
1274 exit(-1);
1275 }
1276
Wei Wang16a63a42018-09-21 15:47:45 -07001277 initVendorCategories();
1278
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001279 for (;;) {
1280 int ret;
1281 int option_index = 0;
1282 static struct option long_options[] = {
Yi Kong19d5c002018-07-20 13:39:55 -07001283 {"async_start", no_argument, nullptr, 0 },
1284 {"async_stop", no_argument, nullptr, 0 },
1285 {"async_dump", no_argument, nullptr, 0 },
1286 {"only_userspace", no_argument, nullptr, 0 },
1287 {"list_categories", no_argument, nullptr, 0 },
1288 {"stream", no_argument, nullptr, 0 },
1289 {nullptr, 0, nullptr, 0 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001290 };
1291
John Reck40b26b42016-03-30 09:44:36 -07001292 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001293 long_options, &option_index);
1294
1295 if (ret < 0) {
1296 for (int i = optind; i < argc; i++) {
Wei Wang16a63a42018-09-21 15:47:45 -07001297 if (!setCategoryEnable(argv[i])) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001298 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1299 exit(1);
1300 }
1301 }
1302 break;
1303 }
1304
1305 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001306 case 'a':
1307 g_debugAppCmdLine = optarg;
1308 break;
1309
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001310 case 'b':
1311 g_traceBufferSizeKB = atoi(optarg);
1312 break;
1313
1314 case 'c':
1315 g_traceOverwrite = true;
1316 break;
1317
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001318 case 'f':
1319 g_categoriesFile = optarg;
1320 break;
1321
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001322 case 'k':
1323 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001324 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001325
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001326 case 'n':
1327 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001328 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001329
1330 case 's':
1331 g_initialSleepSecs = atoi(optarg);
1332 break;
1333
1334 case 't':
1335 g_traceDurationSeconds = atoi(optarg);
1336 break;
1337
1338 case 'z':
1339 g_compress = true;
1340 break;
1341
John Reck40b26b42016-03-30 09:44:36 -07001342 case 'o':
1343 g_outputFile = optarg;
1344 break;
1345
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001346 case 0:
1347 if (!strcmp(long_options[option_index].name, "async_start")) {
1348 async = true;
1349 traceStop = false;
1350 traceDump = false;
1351 g_traceOverwrite = true;
1352 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1353 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001354 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001355 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1356 async = true;
1357 traceStart = false;
1358 traceStop = false;
Hector Dearman11845782018-03-08 14:35:44 +00001359 } else if (!strcmp(long_options[option_index].name, "only_userspace")) {
1360 onlyUserspace = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001361 } else if (!strcmp(long_options[option_index].name, "stream")) {
1362 traceStream = true;
1363 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001364 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1365 listSupportedCategories();
1366 exit(0);
1367 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001368 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001369
1370 default:
1371 fprintf(stderr, "\n");
1372 showHelp(argv[0]);
1373 exit(-1);
1374 break;
1375 }
1376 }
1377
Hector Dearman11845782018-03-08 14:35:44 +00001378 if (onlyUserspace) {
1379 if (!async || !(traceStart || traceStop)) {
1380 fprintf(stderr, "--only_userspace can only be used with "
1381 "--async_start or --async_stop\n");
1382 exit(1);
1383 }
1384 }
1385
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001386 registerSigHandler();
1387
1388 if (g_initialSleepSecs > 0) {
1389 sleep(g_initialSleepSecs);
1390 }
1391
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001392 bool ok = true;
Hector Dearman11845782018-03-08 14:35:44 +00001393
Wei Wang5b73b742018-03-08 13:33:12 -08001394 if (traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001395 ok &= setUpUserspaceTracing();
1396 }
1397
1398 if (ok && traceStart && !onlyUserspace) {
1399 ok &= setUpKernelTracing();
Wei Wang16a63a42018-09-21 15:47:45 -07001400 ok &= setUpVendorTracing();
Wei Wang5b73b742018-03-08 13:33:12 -08001401 ok &= startTrace();
1402 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001403
1404 if (ok && traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001405
1406 if (!traceStream && !onlyUserspace) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001407 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001408 fflush(stdout);
1409 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001410
1411 // We clear the trace after starting it because tracing gets enabled for
1412 // each CPU individually in the kernel. Having the beginning of the trace
1413 // contain entries from only one CPU can cause "begin" entries without a
1414 // matching "end" entry to show up if a task gets migrated from one CPU to
1415 // another.
Hector Dearman11845782018-03-08 14:35:44 +00001416 if (!onlyUserspace)
1417 ok = clearTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001418
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001419 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001420 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001421 // Sleep to allow the trace to be captured.
1422 struct timespec timeLeft;
1423 timeLeft.tv_sec = g_traceDurationSeconds;
1424 timeLeft.tv_nsec = 0;
1425 do {
1426 if (g_traceAborted) {
1427 break;
1428 }
1429 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1430 }
Martijn Coenend9535872015-11-26 10:00:55 +01001431
1432 if (traceStream) {
1433 streamTrace();
1434 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001435 }
1436
1437 // Stop the trace and restore the default settings.
Hector Dearman11845782018-03-08 14:35:44 +00001438 if (traceStop && !onlyUserspace)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001439 stopTrace();
1440
Hector Dearman11845782018-03-08 14:35:44 +00001441 if (ok && traceDump && !onlyUserspace) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001442 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001443 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001444 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001445 int outFd = STDOUT_FILENO;
1446 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001447 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001448 }
1449 if (outFd == -1) {
1450 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1451 } else {
1452 dprintf(outFd, "TRACE:\n");
1453 dumpTrace(outFd);
1454 if (g_outputFile) {
1455 close(outFd);
1456 }
1457 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001458 } else {
1459 printf("\ntrace aborted.\n");
1460 fflush(stdout);
1461 }
1462 clearTrace();
1463 } else if (!ok) {
1464 fprintf(stderr, "unable to start tracing\n");
1465 }
1466
1467 // Reset the trace buffer size to 1.
Hector Dearman11845782018-03-08 14:35:44 +00001468 if (traceStop) {
Wei Wang16a63a42018-09-21 15:47:45 -07001469 cleanUpVendorTracing();
Hector Dearman11845782018-03-08 14:35:44 +00001470 cleanUpUserspaceTracing();
1471 if (!onlyUserspace)
1472 cleanUpKernelTracing();
1473 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001474
1475 return g_traceAborted ? 1 : 0;
1476}