blob: bd3d2d89d9a331e5873c1757a571197a5d69d1d9 [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
sergeyv4144eff2016-04-28 11:40:04 -070065#define MAX_SYS_FILES 10
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" },
Joel Fernandes4dfca7c2017-06-15 16:53:52 -0700136 { OPT, "events/cgroup/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800137 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700138 { "irq", "IRQ Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800139 { REQ, "events/irq/enable" },
140 { OPT, "events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700141 } },
Joel Fernandes6ccad102017-08-31 08:35:05 -0700142 { "irqoff", "IRQ-disabled code section tracing", 0, {
143 { REQ, "events/preemptirq/irq_enable/enable" },
144 { REQ, "events/preemptirq/irq_disable/enable" },
145 } },
146 { "preemptoff", "Preempt-disabled code section tracing", 0, {
147 { REQ, "events/preemptirq/preempt_enable/enable" },
148 { REQ, "events/preemptirq/preempt_disable/enable" },
149 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100150 { "i2c", "I2C Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800151 { REQ, "events/i2c/enable" },
152 { REQ, "events/i2c/i2c_read/enable" },
153 { REQ, "events/i2c/i2c_write/enable" },
154 { REQ, "events/i2c/i2c_result/enable" },
155 { REQ, "events/i2c/i2c_reply/enable" },
156 { OPT, "events/i2c/smbus_read/enable" },
157 { OPT, "events/i2c/smbus_write/enable" },
158 { OPT, "events/i2c/smbus_result/enable" },
159 { OPT, "events/i2c/smbus_reply/enable" },
Michael Wright43fb6782016-08-18 19:56:43 +0100160 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700161 { "freq", "CPU Frequency", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800162 { REQ, "events/power/cpu_frequency/enable" },
163 { OPT, "events/power/clock_set_rate/enable" },
Kevin DuBois062e0b92017-11-03 15:44:08 -0700164 { OPT, "events/power/clock_disable/enable" },
165 { OPT, "events/power/clock_enable/enable" },
Wei Wang53305dd2018-02-22 11:40:07 -0800166 { OPT, "events/clk/clk_set_rate/enable" },
167 { OPT, "events/clk/clk_disable/enable" },
168 { OPT, "events/clk/clk_enable/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800169 { OPT, "events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800170 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700171 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800172 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800173 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700174 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800175 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800176 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700177 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800178 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
179 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
180 { OPT, "events/f2fs/f2fs_write_begin/enable" },
181 { OPT, "events/f2fs/f2fs_write_end/enable" },
182 { OPT, "events/ext4/ext4_da_write_begin/enable" },
183 { OPT, "events/ext4/ext4_da_write_end/enable" },
184 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
185 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
186 { REQ, "events/block/block_rq_issue/enable" },
187 { REQ, "events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800188 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700189 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800190 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700191 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700192 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800193 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800194 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700195 { "sync", "Synchronization", 0, {
Jesse Hallae001a32018-05-15 12:02:15 -0700196 // before linux kernel 4.9
197 { OPT, "events/sync/enable" },
198 // starting in linux kernel 4.9
199 { OPT, "events/fence/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800200 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700201 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800202 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800203 } },
Colin Cross580407f2014-08-18 15:22:13 -0700204 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800205 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
206 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
207 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
208 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Carmen Jackson7a23eb72018-07-02 13:14:56 -0700209 { OPT, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700210 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800211 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800212 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800213 } },
Scott Bauerae473362015-06-08 16:32:36 -0700214 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800215 { REQ, "events/binder/binder_transaction/enable" },
216 { REQ, "events/binder/binder_transaction_received/enable" },
Mika Raento80c3e5d2018-06-25 16:47:24 +0100217 { REQ, "events/binder/binder_transaction_alloc_buf/enable" },
Martijn Coenen7f3d7a22017-05-26 09:50:55 -0700218 { OPT, "events/binder/binder_set_priority/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700219 } },
220 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800221 { OPT, "events/binder/binder_lock/enable" },
222 { OPT, "events/binder/binder_locked/enable" },
223 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700224 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200225 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800226 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200227 } },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700228 { "memory", "Memory", 0, {
229 { OPT, "events/kmem/rss_stat/enable" },
230 { OPT, "events/kmem/ion_heap_grow/enable" },
231 { OPT, "events/kmem/ion_heap_shrink/enable" },
Carmen Jacksonb690b5a2018-11-21 13:04:50 -0800232 { OPT, "events/oom/oom_score_adj_update/enable" },
233 { OPT, "events/sched/sched_process_exit/enable" },
234 { OPT, "events/task/task_rename/enable" },
235 { OPT, "events/task/task_newtask/enable" },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700236 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800237};
238
Wei Wang16a63a42018-09-21 15:47:45 -0700239struct TracingVendorCategory {
240 // The name identifying the category.
241 std::string name;
242
243 // A longer description of the category.
244 std::string description;
245
246 // If the category is enabled through command.
247 bool enabled;
248
249 TracingVendorCategory(string &&name, string &&description, bool enabled)
250 : name(std::move(name))
251 , description(std::move(description))
252 , enabled(enabled)
253 {}
254};
255
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800256/* Command line options */
257static int g_traceDurationSeconds = 5;
258static bool g_traceOverwrite = false;
259static int g_traceBufferSizeKB = 2048;
260static bool g_compress = false;
261static bool g_nohup = false;
262static int g_initialSleepSecs = 0;
Yi Kong19d5c002018-07-20 13:39:55 -0700263static const char* g_categoriesFile = nullptr;
264static const char* g_kernelTraceFuncs = nullptr;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700265static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700266static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800267
268/* Global state */
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700269static bool g_tracePdx = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800270static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700271static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800272static std::string g_traceFolder;
Wei Wang16a63a42018-09-21 15:47:45 -0700273static sp<IAtraceDevice> g_atraceHal;
274static std::vector<TracingVendorCategory> g_vendorCategories;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800275
276/* Sys file paths */
277static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800278 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800279
280static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800281 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800282
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700283#if 0
284// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700285static const char* k_traceCmdlineSizePath =
286 "saved_cmdlines_size";
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700287#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700288
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800289static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800290 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800291
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700292static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800293 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700294
295static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800296 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700297
John Recke757b1c2018-06-28 12:24:33 -0700298static const char* k_recordTgidPath =
299 "options/record-tgid";
300
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700301static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800302 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700303
304static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800305 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700306
307static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800308 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700309
310static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800311 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700312
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700313static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800314 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700315
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800316static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800317 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800318
319static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800320 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800321
Martijn Coenend9535872015-11-26 10:00:55 +0100322static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800323 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100324
John Reck469a1942015-03-26 15:31:35 -0700325static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800326 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700327
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800328// Check whether a file exists.
329static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800330 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800331}
332
333// Check whether a file is writable.
334static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800335 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800336}
337
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700338// Truncate a file.
339static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800340{
Jamie Gennis43122e72013-03-21 14:06:31 -0700341 // This uses creat rather than truncate because some of the debug kernel
342 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
343 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800344 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700345 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800346 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700347 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700348 return false;
349 }
350
Jamie Gennis43122e72013-03-21 14:06:31 -0700351 close(traceFD);
352
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700353 return true;
354}
355
356static bool _writeStr(const char* filename, const char* str, int flags)
357{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800358 std::string fullFilename = g_traceFolder + filename;
359 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800360 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800361 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800362 strerror(errno), errno);
363 return false;
364 }
365
366 bool ok = true;
367 ssize_t len = strlen(str);
368 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800369 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800370 strerror(errno), errno);
371 ok = false;
372 }
373
374 close(fd);
375
376 return ok;
377}
378
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700379// Write a string to a file, returning true if the write was successful.
380static bool writeStr(const char* filename, const char* str)
381{
382 return _writeStr(filename, str, O_WRONLY);
383}
384
385// Append a string to a file, returning true if the write was successful.
386static bool appendStr(const char* filename, const char* str)
387{
388 return _writeStr(filename, str, O_APPEND|O_WRONLY);
389}
390
John Reck469a1942015-03-26 15:31:35 -0700391static void writeClockSyncMarker()
392{
393 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200394 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800395 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200396 if (fd == -1) {
397 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
398 strerror(errno), errno);
399 return;
400 }
John Reck469a1942015-03-26 15:31:35 -0700401 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200402
403 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
404 if (write(fd, buffer, len) != len) {
405 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
406 }
407
408 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
409 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
410 if (write(fd, buffer, len) != len) {
411 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
412 }
413
414 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700415}
416
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800417// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
418// file.
419static bool setKernelOptionEnable(const char* filename, bool enable)
420{
421 return writeStr(filename, enable ? "1" : "0");
422}
423
424// Check whether the category is supported on the device with the current
425// rootness. A category is supported only if all its required /sys/ files are
426// writable and if enabling the category will enable one or more tracing tags
427// or /sys/ files.
428static bool isCategorySupported(const TracingCategory& category)
429{
sergeyvdb404152016-05-02 19:26:07 -0700430 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700431 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700432 }
433
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700434 if (strcmp(category.name, k_pdxServiceCategory) == 0) {
435 return true;
436 }
437
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800438 bool ok = category.tags != 0;
439 for (int i = 0; i < MAX_SYS_FILES; i++) {
440 const char* path = category.sysfiles[i].path;
441 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700442 if (path != nullptr) {
Carmen Jackson5bbc9a22018-12-06 13:47:18 -0800443 if (fileIsWritable(path)) {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800444 ok = true;
Carmen Jackson5bbc9a22018-12-06 13:47:18 -0800445 } else if (req) {
446 return false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800447 }
448 }
449 }
450 return ok;
451}
452
453// Check whether the category would be supported on the device if the user
454// were root. This function assumes that root is able to write to any file
455// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700456// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800457static bool isCategorySupportedForRoot(const TracingCategory& category)
458{
459 bool ok = category.tags != 0;
460 for (int i = 0; i < MAX_SYS_FILES; i++) {
461 const char* path = category.sysfiles[i].path;
462 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700463 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800464 if (req) {
465 if (!fileExists(path)) {
466 return false;
467 } else {
468 ok = true;
469 }
470 } else {
471 ok |= fileExists(path);
472 }
473 }
474 }
475 return ok;
476}
477
478// Enable or disable overwriting of the kernel trace buffers. Disabling this
479// will cause tracing to stop once the trace buffers have filled up.
480static bool setTraceOverwriteEnable(bool enable)
481{
482 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
483}
484
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700485// Set the user initiated trace property
486static bool setUserInitiatedTraceProperty(bool enable)
487{
488 if (!android::base::SetProperty(k_userInitiatedTraceProperty, enable ? "1" : "")) {
489 fprintf(stderr, "error setting user initiated strace system property\n");
490 return false;
491 }
492 return true;
493}
494
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800495// Enable or disable kernel tracing.
496static bool setTracingEnabled(bool enable)
497{
498 return setKernelOptionEnable(k_tracingOnPath, enable);
499}
500
501// Clear the contents of the kernel trace.
502static bool clearTrace()
503{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700504 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800505}
506
507// Set the size of the kernel's trace buffer in kilobytes.
508static bool setTraceBufferSizeKB(int size)
509{
510 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800511 if (size < 1) {
512 size = 1;
513 }
514 snprintf(str, 32, "%d", size);
515 return writeStr(k_traceBufferSizePath, str);
516}
517
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700518#if 0
519// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700520// Set the default size of cmdline hashtable
521static bool setCmdlineSize()
522{
Joel Fernandesce964f22017-06-06 12:20:29 -0700523 if (fileExists(k_traceCmdlineSizePath)) {
524 return writeStr(k_traceCmdlineSizePath, "8192");
525 }
526 return true;
Joel Fernandesed80bd02017-06-02 10:19:28 -0700527}
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700528#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700529
Carmen Jacksonea826792017-05-05 11:42:32 -0700530// Set the clock to the best available option while tracing. Use 'boot' if it's
531// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700532// Any write to the trace_clock sysfs file will reset the buffer, so only
533// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700534static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800535{
Carmen Jacksonea826792017-05-05 11:42:32 -0700536 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
537 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
538 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700539
Carmen Jacksonea826792017-05-05 11:42:32 -0700540 std::string newClock;
541 if (clockStr.find("boot") != std::string::npos) {
542 newClock = "boot";
543 } else if (clockStr.find("mono") != std::string::npos) {
544 newClock = "mono";
545 } else {
546 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700547 }
548
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700549 size_t begin = clockStr.find('[') + 1;
550 size_t end = clockStr.find(']');
Carmen Jacksonea826792017-05-05 11:42:32 -0700551 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
552 return true;
553 }
554 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800555}
556
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700557static bool setPrintTgidEnableIfPresent(bool enable)
558{
John Reckedbf9ec2018-06-29 11:15:17 -0700559 // Pre-4.13 this was options/print-tgid as an android-specific option.
560 // In 4.13+ this is an upstream option called options/record-tgid
561 // Both options produce the same ftrace format change
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700562 if (fileExists(k_printTgidPath)) {
563 return setKernelOptionEnable(k_printTgidPath, enable);
564 }
John Recke757b1c2018-06-28 12:24:33 -0700565 if (fileExists(k_recordTgidPath)) {
566 return setKernelOptionEnable(k_recordTgidPath, enable);
567 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700568 return true;
569}
570
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800571// Poke all the binder-enabled processes in the system to get them to re-read
572// their system properties.
573static bool pokeBinderServices()
574{
575 sp<IServiceManager> sm = defaultServiceManager();
576 Vector<String16> services = sm->listServices();
577 for (size_t i = 0; i < services.size(); i++) {
578 sp<IBinder> obj = sm->checkService(services[i]);
Yi Kong19d5c002018-07-20 13:39:55 -0700579 if (obj != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800580 Parcel data;
581 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
Yi Kong19d5c002018-07-20 13:39:55 -0700582 nullptr, 0) != OK) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800583 if (false) {
584 // XXX: For some reason this fails on tablets trying to
585 // poke the "phone" service. It's not clear whether some
586 // are expected to fail.
587 String8 svc(services[i]);
588 fprintf(stderr, "error poking binder service %s\n",
589 svc.string());
590 return false;
591 }
592 }
593 }
594 }
595 return true;
596}
597
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100598// Poke all the HAL processes in the system to get them to re-read
599// their system properties.
600static void pokeHalServices()
601{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100602 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100603 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100604 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100605 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100606
607 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800608
609 if (sm == nullptr) {
610 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
611 return;
612 }
613
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800614 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100615 for (size_t i = 0; i < interfaces.size(); i++) {
616 string fqInstanceName = interfaces[i];
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700617 string::size_type n = fqInstanceName.find('/');
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100618 if (n == std::string::npos || interfaces[i].size() == n+1)
619 continue;
620 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
621 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100622 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
623 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100624 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100625 continue;
626 }
Carmen Jackson73206122017-04-18 15:37:57 -0700627
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100628 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700629 if (interface == nullptr) {
630 // ignore
631 continue;
632 }
633
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100634 auto notifyRet = interface->notifySyspropsChanged();
635 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100636 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800637 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100638 }
639 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800640 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100641 // TODO(b/34242478) fix this when we determine the correct ACL
642 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800643 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100644}
645
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800646// Set the trace tags that userland tracing uses, and poke the running
647// processes to pick up the new value.
648static bool setTagsProperty(uint64_t tags)
649{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700650 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
651 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800652 fprintf(stderr, "error setting trace tags system property\n");
653 return false;
654 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700655 return true;
656}
657
sergeyv4144eff2016-04-28 11:40:04 -0700658static void clearAppProperties()
659{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700660 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700661 fprintf(stderr, "failed to clear system property: %s",
662 k_traceAppsNumberProperty);
663 }
664}
665
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700666// Set the system property that indicates which apps should perform
667// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700668static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700669{
sergeyv4144eff2016-04-28 11:40:04 -0700670 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700671 char* start = cmdline;
Yi Kong19d5c002018-07-20 13:39:55 -0700672 while (start != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700673 char* end = strchr(start, ',');
Yi Kong19d5c002018-07-20 13:39:55 -0700674 if (end != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700675 *end = '\0';
676 end++;
677 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700678 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
679 if (!android::base::SetProperty(key, start)) {
680 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700681 clearAppProperties();
682 return false;
683 }
684 start = end;
685 i++;
686 }
687
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700688 std::string value = android::base::StringPrintf("%d", i);
689 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
690 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700691 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700692 return false;
693 }
694 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800695}
696
697// Disable all /sys/ enable files.
698static bool disableKernelTraceEvents() {
699 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700700 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800701 const TracingCategory &c = k_categories[i];
702 for (int j = 0; j < MAX_SYS_FILES; j++) {
703 const char* path = c.sysfiles[j].path;
Yi Kong19d5c002018-07-20 13:39:55 -0700704 if (path != nullptr && fileIsWritable(path)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800705 ok &= setKernelOptionEnable(path, false);
706 }
707 }
708 }
709 return ok;
710}
711
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700712// Verify that the comma separated list of functions are being traced by the
713// kernel.
714static bool verifyKernelTraceFuncs(const char* funcs)
715{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100716 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800717 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100718 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700719 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100720 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700721 }
722
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100723 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700724
725 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100726 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700727 bool ok = true;
728 char* myFuncs = strdup(funcs);
729 char* func = strtok(myFuncs, ",");
730 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100731 if (!strchr(func, '*')) {
732 String8 fancyFunc = String8::format("\n%s\n", func);
733 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
734 if (!found || func[0] == '\0') {
735 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
736 "to trace.\n", func);
737 ok = false;
738 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700739 }
Yi Kong19d5c002018-07-20 13:39:55 -0700740 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700741 }
742 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700743 return ok;
744}
745
746// Set the comma separated list of functions that the kernel is to trace.
747static bool setKernelTraceFuncs(const char* funcs)
748{
749 bool ok = true;
750
Yi Kong19d5c002018-07-20 13:39:55 -0700751 if (funcs == nullptr || funcs[0] == '\0') {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700752 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700753 if (fileIsWritable(k_currentTracerPath)) {
754 ok &= writeStr(k_currentTracerPath, "nop");
755 }
756 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700757 ok &= truncateFile(k_ftraceFilterPath);
758 }
759 } else {
760 // Enable kernel function tracing.
761 ok &= writeStr(k_currentTracerPath, "function_graph");
762 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
763 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
764 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
765 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
766
767 // Set the requested filter functions.
768 ok &= truncateFile(k_ftraceFilterPath);
769 char* myFuncs = strdup(funcs);
770 char* func = strtok(myFuncs, ",");
771 while (func) {
772 ok &= appendStr(k_ftraceFilterPath, func);
Yi Kong19d5c002018-07-20 13:39:55 -0700773 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700774 }
775 free(myFuncs);
776
777 // Verify that the set functions are being traced.
778 if (ok) {
779 ok &= verifyKernelTraceFuncs(funcs);
780 }
781 }
782
783 return ok;
784}
785
Wei Wang16a63a42018-09-21 15:47:45 -0700786static bool setCategoryEnable(const char* name)
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900787{
Wei Wang16a63a42018-09-21 15:47:45 -0700788 bool vendor_found = false;
789 for (auto &c : g_vendorCategories) {
790 if (strcmp(name, c.name.c_str()) == 0) {
791 c.enabled = true;
792 vendor_found = true;
793 }
794 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700795 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900796 const TracingCategory& c = k_categories[i];
797 if (strcmp(name, c.name) == 0) {
798 if (isCategorySupported(c)) {
Wei Wang16a63a42018-09-21 15:47:45 -0700799 g_categoryEnables[i] = true;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900800 return true;
801 } else {
802 if (isCategorySupportedForRoot(c)) {
803 fprintf(stderr, "error: category \"%s\" requires root "
804 "privileges.\n", name);
805 } else {
806 fprintf(stderr, "error: category \"%s\" is not supported "
807 "on this device.\n", name);
808 }
809 return false;
810 }
811 }
812 }
Wei Wang16a63a42018-09-21 15:47:45 -0700813 if (vendor_found) {
814 return true;
815 }
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900816 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
817 return false;
818}
819
820static bool setCategoriesEnableFromFile(const char* categories_file)
821{
822 if (!categories_file) {
823 return true;
824 }
Yi Kong19d5c002018-07-20 13:39:55 -0700825 Tokenizer* tokenizer = nullptr;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900826 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
827 return false;
828 }
829 bool ok = true;
830 while (!tokenizer->isEol()) {
831 String8 token = tokenizer->nextToken(" ");
832 if (token.isEmpty()) {
833 tokenizer->skipDelimiters(" ");
834 continue;
835 }
Wei Wang16a63a42018-09-21 15:47:45 -0700836 ok &= setCategoryEnable(token.string());
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900837 }
838 delete tokenizer;
839 return ok;
840}
841
Hector Dearman11845782018-03-08 14:35:44 +0000842static bool setUpUserspaceTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800843{
844 bool ok = true;
845
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800846 // Set up the tags property.
847 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700848 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800849 if (g_categoryEnables[i]) {
850 const TracingCategory &c = k_categories[i];
851 tags |= c.tags;
852 }
853 }
854 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700855
856 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700857 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700858 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
859 coreServicesTagEnabled = g_categoryEnables[i];
860 }
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700861
862 // Set whether to poke PDX services in this session.
863 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
864 g_tracePdx = g_categoryEnables[i];
865 }
sergeyvdb404152016-05-02 19:26:07 -0700866 }
867
868 std::string packageList(g_debugAppCmdLine);
869 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700870 if (!packageList.empty()) {
871 packageList += ",";
872 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700873 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700874 }
Dan Austin09a79872016-05-31 13:27:03 -0700875 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700876 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100877 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800878
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700879 if (g_tracePdx) {
880 ok &= ServiceUtility::PokeServices();
881 }
882
Hector Dearman11845782018-03-08 14:35:44 +0000883 return ok;
884}
885
886static void cleanUpUserspaceTracing()
887{
888 setTagsProperty(0);
889 clearAppProperties();
890 pokeBinderServices();
891
892 if (g_tracePdx) {
893 ServiceUtility::PokeServices();
894 }
895}
896
897
898// Set all the kernel tracing settings to the desired state for this trace
899// capture.
900static bool setUpKernelTracing()
901{
902 bool ok = true;
903
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700904 ok &= setUserInitiatedTraceProperty(true);
905
Hector Dearman11845782018-03-08 14:35:44 +0000906 // Set up the tracing options.
907 ok &= setCategoriesEnableFromFile(g_categoriesFile);
908 ok &= setTraceOverwriteEnable(g_traceOverwrite);
909 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
910 // TODO: Re-enable after stabilization
911 //ok &= setCmdlineSize();
912 ok &= setClock();
913 ok &= setPrintTgidEnableIfPresent(true);
914 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
915
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800916 // Disable all the sysfs enables. This is done as a separate loop from
917 // the enables to allow the same enable to exist in multiple categories.
918 ok &= disableKernelTraceEvents();
919
920 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700921 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800922 if (g_categoryEnables[i]) {
923 const TracingCategory &c = k_categories[i];
924 for (int j = 0; j < MAX_SYS_FILES; j++) {
925 const char* path = c.sysfiles[j].path;
926 bool required = c.sysfiles[j].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700927 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800928 if (fileIsWritable(path)) {
929 ok &= setKernelOptionEnable(path, true);
930 } else if (required) {
931 fprintf(stderr, "error writing file %s\n", path);
932 ok = false;
933 }
934 }
935 }
936 }
937 }
938
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800939 return ok;
940}
941
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700942// Reset all the kernel tracing settings to their default state.
Hector Dearman11845782018-03-08 14:35:44 +0000943static void cleanUpKernelTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800944{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800945 // Disable all tracing that we're able to.
946 disableKernelTraceEvents();
947
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800948 // Set the options back to their defaults.
949 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700950 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700951 setPrintTgidEnableIfPresent(false);
Yi Kong19d5c002018-07-20 13:39:55 -0700952 setKernelTraceFuncs(nullptr);
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700953 setUserInitiatedTraceProperty(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700954}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800955
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700956// Enable tracing in the kernel.
957static bool startTrace()
958{
959 return setTracingEnabled(true);
960}
961
962// Disable tracing in the kernel.
963static void stopTrace()
964{
965 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800966}
967
Martijn Coenend9535872015-11-26 10:00:55 +0100968// Read data from the tracing pipe and forward to stdout
969static void streamTrace()
970{
971 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800972 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100973 if (traceFD == -1) {
974 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
975 strerror(errno), errno);
976 return;
977 }
978 while (!g_traceAborted) {
979 ssize_t bytes_read = read(traceFD, trace_data, 4096);
980 if (bytes_read > 0) {
981 write(STDOUT_FILENO, trace_data, bytes_read);
982 fflush(stdout);
983 } else {
984 if (!g_traceAborted) {
985 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
986 bytes_read, errno, strerror(errno));
987 }
988 break;
989 }
990 }
991}
992
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800993// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700994static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800995{
John Reck6c8ac922016-03-28 11:25:30 -0700996 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800997 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800998 if (traceFD == -1) {
999 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
1000 strerror(errno), errno);
1001 return;
1002 }
1003
1004 if (g_compress) {
1005 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -08001006 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001007
1008 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001009 if (result != Z_OK) {
1010 fprintf(stderr, "error initializing zlib: %d\n", result);
1011 close(traceFD);
1012 return;
1013 }
1014
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001015 constexpr size_t bufSize = 64*1024;
1016 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
1017 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
1018 if (!in || !out) {
1019 fprintf(stderr, "couldn't allocate buffers\n");
1020 close(traceFD);
1021 return;
1022 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001023
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001024 int flush = Z_NO_FLUSH;
1025
1026 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001027 zs.avail_out = bufSize;
1028
1029 do {
1030
1031 if (zs.avail_in == 0) {
1032 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001033 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001034 if (result < 0) {
1035 fprintf(stderr, "error reading trace: %s (%d)\n",
1036 strerror(errno), errno);
1037 result = Z_STREAM_END;
1038 break;
1039 } else if (result == 0) {
1040 flush = Z_FINISH;
1041 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001042 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001043 zs.avail_in = result;
1044 }
1045 }
1046
1047 if (zs.avail_out == 0) {
1048 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -07001049 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001050 if ((size_t)result < bufSize) {
1051 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1052 strerror(errno), errno);
1053 result = Z_STREAM_END; // skip deflate error message
1054 zs.avail_out = bufSize; // skip the final write
1055 break;
1056 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001057 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001058 zs.avail_out = bufSize;
1059 }
1060
1061 } while ((result = deflate(&zs, flush)) == Z_OK);
1062
1063 if (result != Z_STREAM_END) {
1064 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
1065 }
1066
1067 if (zs.avail_out < bufSize) {
1068 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -07001069 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001070 if ((size_t)result < bytes) {
1071 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1072 strerror(errno), errno);
1073 }
1074 }
1075
1076 result = deflateEnd(&zs);
1077 if (result != Z_OK) {
1078 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1079 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001080 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001081 char buf[4096];
1082 ssize_t rc;
1083 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1084 if (!android::base::WriteFully(outFd, buf, rc)) {
1085 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1086 break;
1087 }
1088 }
1089 if (rc == -1) {
1090 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001091 }
1092 }
1093
1094 close(traceFD);
1095}
1096
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001097static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001098{
1099 if (!g_nohup) {
1100 g_traceAborted = true;
1101 }
1102}
1103
1104static void registerSigHandler()
1105{
1106 struct sigaction sa;
1107 sigemptyset(&sa.sa_mask);
1108 sa.sa_flags = 0;
1109 sa.sa_handler = handleSignal;
Yi Kong19d5c002018-07-20 13:39:55 -07001110 sigaction(SIGHUP, &sa, nullptr);
1111 sigaction(SIGINT, &sa, nullptr);
1112 sigaction(SIGQUIT, &sa, nullptr);
1113 sigaction(SIGTERM, &sa, nullptr);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001114}
1115
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001116static void listSupportedCategories()
1117{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001118 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001119 const TracingCategory& c = k_categories[i];
1120 if (isCategorySupported(c)) {
1121 printf(" %10s - %s\n", c.name, c.longname);
1122 }
1123 }
Wei Wang16a63a42018-09-21 15:47:45 -07001124 for (const auto &c : g_vendorCategories) {
1125 printf(" %10s - %s (HAL)\n", c.name.c_str(), c.description.c_str());
1126 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001127}
1128
1129// Print the command usage help to stderr.
1130static void showHelp(const char *cmd)
1131{
1132 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1133 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001134 " -a appname enable app-level tracing for a comma "
Daniel Colascione519a0792018-02-09 20:05:39 -08001135 "separated list of cmdlines; * is a wildcard matching any process\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001136 " -b N use a trace buffer size of N KB\n"
1137 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001138 " -f filename use the categories written in a file as space-separated\n"
1139 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001140 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001141 " -n ignore signals\n"
1142 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001143 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001144 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001145 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001146 " --async_dump dump the current contents of circular trace buffer\n"
1147 " --async_stop stop tracing and dump the current contents of circular\n"
1148 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001149 " --stream stream trace to stdout as it enters the trace buffer\n"
1150 " Note: this can take significant CPU time, and is best\n"
1151 " used for measuring things that are not affected by\n"
1152 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001153 " --list_categories\n"
1154 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001155 " -o filename write the trace to the specified file instead\n"
1156 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001157 );
1158}
1159
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001160bool findTraceFiles()
1161{
1162 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1163 static const std::string tracefs_path = "/sys/kernel/tracing/";
1164 static const std::string trace_file = "trace_marker";
1165
1166 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1167 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1168
1169 if (!tracefs && !debugfs) {
1170 fprintf(stderr, "Error: Did not find trace folder\n");
1171 return false;
1172 }
1173
1174 if (tracefs) {
1175 g_traceFolder = tracefs_path;
1176 } else {
1177 g_traceFolder = debugfs_path;
1178 }
1179
1180 return true;
1181}
1182
Wei Wang16a63a42018-09-21 15:47:45 -07001183void initVendorCategories()
1184{
1185 g_atraceHal = IAtraceDevice::getService();
1186
1187 if (g_atraceHal == nullptr) {
1188 // No atrace HAL
1189 return;
1190 }
1191
1192 Return<void> ret = g_atraceHal->listCategories(
1193 [](const auto& list) {
1194 g_vendorCategories.reserve(list.size());
1195 for (const auto& category : list) {
1196 g_vendorCategories.emplace_back(category.name, category.description, false);
1197 }
1198 });
1199 if (!ret.isOk()) {
1200 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1201 }
1202}
1203
1204static bool setUpVendorTracing()
1205{
1206 if (g_atraceHal == nullptr) {
1207 // No atrace HAL
1208 return true;
1209 }
1210
1211 std::vector<hidl_string> categories;
1212 for (const auto &c : g_vendorCategories) {
1213 if (c.enabled) {
1214 categories.emplace_back(c.name);
1215 }
1216 }
1217
1218 if (!categories.size()) {
1219 return true;
1220 }
1221
1222 auto ret = g_atraceHal->enableCategories(categories);
1223 if (!ret.isOk()) {
1224 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1225 return false;
1226 } else if (ret != Status::SUCCESS) {
1227 fprintf(stderr, "calling atrace HAL failed: %s\n", toString(ret).c_str());
1228 return false;
1229 }
1230 return true;
1231}
1232
1233static bool cleanUpVendorTracing()
1234{
1235 if (g_atraceHal == nullptr) {
1236 // No atrace HAL
1237 return true;
1238 }
1239
1240 if (!g_vendorCategories.size()) {
1241 // No vendor categories
1242 return true;
1243 }
1244
1245 auto ret = g_atraceHal->disableAllCategories();
1246 if (!ret.isOk()) {
1247 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1248 return false;
1249 } else if (ret != Status::SUCCESS) {
1250 fprintf(stderr, "calling atrace HAL failed: %s\n", toString(ret).c_str());
1251 return false;
1252 }
1253 return true;
1254}
1255
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001256int main(int argc, char **argv)
1257{
1258 bool async = false;
1259 bool traceStart = true;
1260 bool traceStop = true;
1261 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001262 bool traceStream = false;
Hector Dearman11845782018-03-08 14:35:44 +00001263 bool onlyUserspace = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001264
1265 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1266 showHelp(argv[0]);
1267 exit(0);
1268 }
1269
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001270 if (!findTraceFiles()) {
1271 fprintf(stderr, "No trace folder found\n");
1272 exit(-1);
1273 }
1274
Wei Wang16a63a42018-09-21 15:47:45 -07001275 initVendorCategories();
1276
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001277 for (;;) {
1278 int ret;
1279 int option_index = 0;
1280 static struct option long_options[] = {
Yi Kong19d5c002018-07-20 13:39:55 -07001281 {"async_start", no_argument, nullptr, 0 },
1282 {"async_stop", no_argument, nullptr, 0 },
1283 {"async_dump", no_argument, nullptr, 0 },
1284 {"only_userspace", no_argument, nullptr, 0 },
1285 {"list_categories", no_argument, nullptr, 0 },
1286 {"stream", no_argument, nullptr, 0 },
1287 {nullptr, 0, nullptr, 0 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001288 };
1289
John Reck40b26b42016-03-30 09:44:36 -07001290 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001291 long_options, &option_index);
1292
1293 if (ret < 0) {
1294 for (int i = optind; i < argc; i++) {
Wei Wang16a63a42018-09-21 15:47:45 -07001295 if (!setCategoryEnable(argv[i])) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001296 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1297 exit(1);
1298 }
1299 }
1300 break;
1301 }
1302
1303 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001304 case 'a':
1305 g_debugAppCmdLine = optarg;
1306 break;
1307
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001308 case 'b':
1309 g_traceBufferSizeKB = atoi(optarg);
1310 break;
1311
1312 case 'c':
1313 g_traceOverwrite = true;
1314 break;
1315
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001316 case 'f':
1317 g_categoriesFile = optarg;
1318 break;
1319
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001320 case 'k':
1321 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001322 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001323
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001324 case 'n':
1325 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001326 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001327
1328 case 's':
1329 g_initialSleepSecs = atoi(optarg);
1330 break;
1331
1332 case 't':
1333 g_traceDurationSeconds = atoi(optarg);
1334 break;
1335
1336 case 'z':
1337 g_compress = true;
1338 break;
1339
John Reck40b26b42016-03-30 09:44:36 -07001340 case 'o':
1341 g_outputFile = optarg;
1342 break;
1343
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001344 case 0:
1345 if (!strcmp(long_options[option_index].name, "async_start")) {
1346 async = true;
1347 traceStop = false;
1348 traceDump = false;
1349 g_traceOverwrite = true;
1350 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1351 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001352 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001353 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1354 async = true;
1355 traceStart = false;
1356 traceStop = false;
Hector Dearman11845782018-03-08 14:35:44 +00001357 } else if (!strcmp(long_options[option_index].name, "only_userspace")) {
1358 onlyUserspace = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001359 } else if (!strcmp(long_options[option_index].name, "stream")) {
1360 traceStream = true;
1361 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001362 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1363 listSupportedCategories();
1364 exit(0);
1365 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001366 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001367
1368 default:
1369 fprintf(stderr, "\n");
1370 showHelp(argv[0]);
1371 exit(-1);
1372 break;
1373 }
1374 }
1375
Hector Dearman11845782018-03-08 14:35:44 +00001376 if (onlyUserspace) {
1377 if (!async || !(traceStart || traceStop)) {
1378 fprintf(stderr, "--only_userspace can only be used with "
1379 "--async_start or --async_stop\n");
1380 exit(1);
1381 }
1382 }
1383
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001384 registerSigHandler();
1385
1386 if (g_initialSleepSecs > 0) {
1387 sleep(g_initialSleepSecs);
1388 }
1389
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001390 bool ok = true;
Hector Dearman11845782018-03-08 14:35:44 +00001391
Wei Wang5b73b742018-03-08 13:33:12 -08001392 if (traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001393 ok &= setUpUserspaceTracing();
1394 }
1395
1396 if (ok && traceStart && !onlyUserspace) {
1397 ok &= setUpKernelTracing();
Wei Wang16a63a42018-09-21 15:47:45 -07001398 ok &= setUpVendorTracing();
Wei Wang5b73b742018-03-08 13:33:12 -08001399 ok &= startTrace();
1400 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001401
1402 if (ok && traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001403
1404 if (!traceStream && !onlyUserspace) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001405 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001406 fflush(stdout);
1407 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001408
1409 // We clear the trace after starting it because tracing gets enabled for
1410 // each CPU individually in the kernel. Having the beginning of the trace
1411 // contain entries from only one CPU can cause "begin" entries without a
1412 // matching "end" entry to show up if a task gets migrated from one CPU to
1413 // another.
Hector Dearman11845782018-03-08 14:35:44 +00001414 if (!onlyUserspace)
1415 ok = clearTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001416
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001417 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001418 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001419 // Sleep to allow the trace to be captured.
1420 struct timespec timeLeft;
1421 timeLeft.tv_sec = g_traceDurationSeconds;
1422 timeLeft.tv_nsec = 0;
1423 do {
1424 if (g_traceAborted) {
1425 break;
1426 }
1427 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1428 }
Martijn Coenend9535872015-11-26 10:00:55 +01001429
1430 if (traceStream) {
1431 streamTrace();
1432 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001433 }
1434
1435 // Stop the trace and restore the default settings.
Hector Dearman11845782018-03-08 14:35:44 +00001436 if (traceStop && !onlyUserspace)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001437 stopTrace();
1438
Hector Dearman11845782018-03-08 14:35:44 +00001439 if (ok && traceDump && !onlyUserspace) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001440 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001441 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001442 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001443 int outFd = STDOUT_FILENO;
1444 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001445 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001446 }
1447 if (outFd == -1) {
1448 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1449 } else {
1450 dprintf(outFd, "TRACE:\n");
1451 dumpTrace(outFd);
1452 if (g_outputFile) {
1453 close(outFd);
1454 }
1455 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001456 } else {
1457 printf("\ntrace aborted.\n");
1458 fflush(stdout);
1459 }
1460 clearTrace();
1461 } else if (!ok) {
1462 fprintf(stderr, "unable to start tracing\n");
1463 }
1464
1465 // Reset the trace buffer size to 1.
Hector Dearman11845782018-03-08 14:35:44 +00001466 if (traceStop) {
Wei Wang16a63a42018-09-21 15:47:45 -07001467 cleanUpVendorTracing();
Hector Dearman11845782018-03-08 14:35:44 +00001468 cleanUpUserspaceTracing();
1469 if (!onlyUserspace)
1470 cleanUpKernelTracing();
1471 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001472
1473 return g_traceAborted ? 1 : 0;
1474}