blob: 53b3a00453bab9797eec8004e4aaab7c9d05e977 [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[] = {
Wei Wang16a63a42018-09-21 15:47:45 -0700102 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700103 { "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, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -0500108 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700109 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
110 { "video", "Video", ATRACE_TAG_VIDEO, { } },
111 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
112 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -0700113 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -0700114 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -0700115 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -0700116 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700117 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 14:36:20 -0700118 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-07-01 01:46:25 +0900119 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Greg Hackmannbbd7d992014-12-01 14:43:34 -0800120 { "database", "Database", ATRACE_TAG_DATABASE, { } },
Felipe Leme0f97c1d2016-09-07 11:33:26 -0700121 { "network", "Network", ATRACE_TAG_NETWORK, { } },
Josh Gao468b4cb2016-11-29 10:55:21 -0800122 { "adb", "ADB", ATRACE_TAG_ADB, { } },
Martijn Coenen42f2ab42018-03-09 09:27:32 +0100123 { "vibrator", "Vibrator", ATRACE_TAG_VIBRATOR, { } },
124 { "aidl", "AIDL calls", ATRACE_TAG_AIDL, { } },
Mika Raentob363cf52018-04-23 22:09:13 +0100125 { "nnapi", "NNAPI", ATRACE_TAG_NNAPI, { } },
sergeyvdb404152016-05-02 19:26:07 -0700126 { k_coreServiceCategory, "Core services", 0, { } },
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700127 { k_pdxServiceCategory, "PDX services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700128 { "sched", "CPU Scheduling", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800129 { REQ, "events/sched/sched_switch/enable" },
130 { REQ, "events/sched/sched_wakeup/enable" },
Joel Fernandesee593e22017-06-04 13:05:59 -0700131 { OPT, "events/sched/sched_waking/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800132 { OPT, "events/sched/sched_blocked_reason/enable" },
133 { OPT, "events/sched/sched_cpu_hotplug/enable" },
Wei Wangca49dfc2018-05-03 15:45:20 -0700134 { OPT, "events/sched/sched_pi_setprio/enable" },
Joel Fernandes4dfca7c2017-06-15 16:53:52 -0700135 { OPT, "events/cgroup/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800136 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700137 { "irq", "IRQ Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800138 { REQ, "events/irq/enable" },
139 { OPT, "events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700140 } },
Joel Fernandes6ccad102017-08-31 08:35:05 -0700141 { "irqoff", "IRQ-disabled code section tracing", 0, {
142 { REQ, "events/preemptirq/irq_enable/enable" },
143 { REQ, "events/preemptirq/irq_disable/enable" },
144 } },
145 { "preemptoff", "Preempt-disabled code section tracing", 0, {
146 { REQ, "events/preemptirq/preempt_enable/enable" },
147 { REQ, "events/preemptirq/preempt_disable/enable" },
148 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100149 { "i2c", "I2C Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800150 { REQ, "events/i2c/enable" },
151 { REQ, "events/i2c/i2c_read/enable" },
152 { REQ, "events/i2c/i2c_write/enable" },
153 { REQ, "events/i2c/i2c_result/enable" },
154 { REQ, "events/i2c/i2c_reply/enable" },
155 { OPT, "events/i2c/smbus_read/enable" },
156 { OPT, "events/i2c/smbus_write/enable" },
157 { OPT, "events/i2c/smbus_result/enable" },
158 { OPT, "events/i2c/smbus_reply/enable" },
Michael Wright43fb6782016-08-18 19:56:43 +0100159 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700160 { "freq", "CPU Frequency", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800161 { REQ, "events/power/cpu_frequency/enable" },
162 { OPT, "events/power/clock_set_rate/enable" },
Kevin DuBois062e0b92017-11-03 15:44:08 -0700163 { OPT, "events/power/clock_disable/enable" },
164 { OPT, "events/power/clock_enable/enable" },
Wei Wang53305dd2018-02-22 11:40:07 -0800165 { OPT, "events/clk/clk_set_rate/enable" },
166 { OPT, "events/clk/clk_disable/enable" },
167 { OPT, "events/clk/clk_enable/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800168 { OPT, "events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800169 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700170 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800171 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800172 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700173 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800174 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800175 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700176 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800177 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
178 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
179 { OPT, "events/f2fs/f2fs_write_begin/enable" },
180 { OPT, "events/f2fs/f2fs_write_end/enable" },
181 { OPT, "events/ext4/ext4_da_write_begin/enable" },
182 { OPT, "events/ext4/ext4_da_write_end/enable" },
183 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
184 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
185 { REQ, "events/block/block_rq_issue/enable" },
186 { REQ, "events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800187 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700188 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800189 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700190 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700191 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800192 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800193 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700194 { "sync", "Synchronization", 0, {
Jesse Hallae001a32018-05-15 12:02:15 -0700195 // before linux kernel 4.9
196 { OPT, "events/sync/enable" },
197 // starting in linux kernel 4.9
198 { OPT, "events/fence/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800199 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700200 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800201 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800202 } },
Colin Cross580407f2014-08-18 15:22:13 -0700203 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800204 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
205 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
206 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
207 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Carmen Jackson7a23eb72018-07-02 13:14:56 -0700208 { OPT, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700209 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800210 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800211 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800212 } },
Scott Bauerae473362015-06-08 16:32:36 -0700213 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800214 { REQ, "events/binder/binder_transaction/enable" },
215 { REQ, "events/binder/binder_transaction_received/enable" },
Mika Raento80c3e5d2018-06-25 16:47:24 +0100216 { REQ, "events/binder/binder_transaction_alloc_buf/enable" },
Martijn Coenen7f3d7a22017-05-26 09:50:55 -0700217 { OPT, "events/binder/binder_set_priority/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700218 } },
219 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800220 { OPT, "events/binder/binder_lock/enable" },
221 { OPT, "events/binder/binder_locked/enable" },
222 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700223 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200224 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800225 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200226 } },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700227 { "memory", "Memory", 0, {
228 { OPT, "events/kmem/rss_stat/enable" },
229 { OPT, "events/kmem/ion_heap_grow/enable" },
230 { OPT, "events/kmem/ion_heap_shrink/enable" },
Carmen Jacksonb690b5a2018-11-21 13:04:50 -0800231 { OPT, "events/oom/oom_score_adj_update/enable" },
232 { OPT, "events/sched/sched_process_exit/enable" },
233 { OPT, "events/task/task_rename/enable" },
234 { OPT, "events/task/task_newtask/enable" },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700235 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800236};
237
Wei Wang16a63a42018-09-21 15:47:45 -0700238struct TracingVendorCategory {
239 // The name identifying the category.
240 std::string name;
241
242 // A longer description of the category.
243 std::string description;
244
245 // If the category is enabled through command.
246 bool enabled;
247
248 TracingVendorCategory(string &&name, string &&description, bool enabled)
249 : name(std::move(name))
250 , description(std::move(description))
251 , enabled(enabled)
252 {}
253};
254
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800255/* Command line options */
256static int g_traceDurationSeconds = 5;
257static bool g_traceOverwrite = false;
258static int g_traceBufferSizeKB = 2048;
259static bool g_compress = false;
260static bool g_nohup = false;
261static int g_initialSleepSecs = 0;
Yi Kong19d5c002018-07-20 13:39:55 -0700262static const char* g_categoriesFile = nullptr;
263static const char* g_kernelTraceFuncs = nullptr;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700264static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700265static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800266
267/* Global state */
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700268static bool g_tracePdx = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800269static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700270static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800271static std::string g_traceFolder;
Wei Wang16a63a42018-09-21 15:47:45 -0700272static sp<IAtraceDevice> g_atraceHal;
273static std::vector<TracingVendorCategory> g_vendorCategories;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800274
275/* Sys file paths */
276static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800277 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800278
279static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800280 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800281
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700282#if 0
283// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700284static const char* k_traceCmdlineSizePath =
285 "saved_cmdlines_size";
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700286#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700287
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800288static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800289 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800290
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700291static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800292 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700293
294static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800295 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700296
John Recke757b1c2018-06-28 12:24:33 -0700297static const char* k_recordTgidPath =
298 "options/record-tgid";
299
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700300static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800301 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700302
303static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800304 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700305
306static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800307 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700308
309static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800310 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700311
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700312static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800313 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700314
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800315static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800316 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800317
318static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800319 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800320
Martijn Coenend9535872015-11-26 10:00:55 +0100321static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800322 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100323
John Reck469a1942015-03-26 15:31:35 -0700324static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800325 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700326
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800327// Check whether a file exists.
328static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800329 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800330}
331
332// Check whether a file is writable.
333static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800334 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800335}
336
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700337// Truncate a file.
338static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800339{
Jamie Gennis43122e72013-03-21 14:06:31 -0700340 // This uses creat rather than truncate because some of the debug kernel
341 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
342 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800343 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700344 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800345 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700346 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700347 return false;
348 }
349
Jamie Gennis43122e72013-03-21 14:06:31 -0700350 close(traceFD);
351
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700352 return true;
353}
354
355static bool _writeStr(const char* filename, const char* str, int flags)
356{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800357 std::string fullFilename = g_traceFolder + filename;
358 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800359 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800360 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800361 strerror(errno), errno);
362 return false;
363 }
364
365 bool ok = true;
366 ssize_t len = strlen(str);
367 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800368 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800369 strerror(errno), errno);
370 ok = false;
371 }
372
373 close(fd);
374
375 return ok;
376}
377
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700378// Write a string to a file, returning true if the write was successful.
379static bool writeStr(const char* filename, const char* str)
380{
381 return _writeStr(filename, str, O_WRONLY);
382}
383
384// Append a string to a file, returning true if the write was successful.
385static bool appendStr(const char* filename, const char* str)
386{
387 return _writeStr(filename, str, O_APPEND|O_WRONLY);
388}
389
John Reck469a1942015-03-26 15:31:35 -0700390static void writeClockSyncMarker()
391{
392 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200393 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800394 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200395 if (fd == -1) {
396 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
397 strerror(errno), errno);
398 return;
399 }
John Reck469a1942015-03-26 15:31:35 -0700400 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200401
402 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
403 if (write(fd, buffer, len) != len) {
404 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
405 }
406
407 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
408 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
409 if (write(fd, buffer, len) != len) {
410 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
411 }
412
413 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700414}
415
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800416// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
417// file.
418static bool setKernelOptionEnable(const char* filename, bool enable)
419{
420 return writeStr(filename, enable ? "1" : "0");
421}
422
423// Check whether the category is supported on the device with the current
424// rootness. A category is supported only if all its required /sys/ files are
425// writable and if enabling the category will enable one or more tracing tags
426// or /sys/ files.
427static bool isCategorySupported(const TracingCategory& category)
428{
sergeyvdb404152016-05-02 19:26:07 -0700429 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700430 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700431 }
432
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700433 if (strcmp(category.name, k_pdxServiceCategory) == 0) {
434 return true;
435 }
436
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800437 bool ok = category.tags != 0;
438 for (int i = 0; i < MAX_SYS_FILES; i++) {
439 const char* path = category.sysfiles[i].path;
440 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700441 if (path != nullptr) {
Carmen Jackson5bbc9a22018-12-06 13:47:18 -0800442 if (fileIsWritable(path)) {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800443 ok = true;
Carmen Jackson5bbc9a22018-12-06 13:47:18 -0800444 } else if (req) {
445 return false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800446 }
447 }
448 }
449 return ok;
450}
451
452// Check whether the category would be supported on the device if the user
453// were root. This function assumes that root is able to write to any file
454// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700455// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800456static bool isCategorySupportedForRoot(const TracingCategory& category)
457{
458 bool ok = category.tags != 0;
459 for (int i = 0; i < MAX_SYS_FILES; i++) {
460 const char* path = category.sysfiles[i].path;
461 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700462 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800463 if (req) {
464 if (!fileExists(path)) {
465 return false;
466 } else {
467 ok = true;
468 }
469 } else {
470 ok |= fileExists(path);
471 }
472 }
473 }
474 return ok;
475}
476
477// Enable or disable overwriting of the kernel trace buffers. Disabling this
478// will cause tracing to stop once the trace buffers have filled up.
479static bool setTraceOverwriteEnable(bool enable)
480{
481 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
482}
483
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700484// Set the user initiated trace property
485static bool setUserInitiatedTraceProperty(bool enable)
486{
487 if (!android::base::SetProperty(k_userInitiatedTraceProperty, enable ? "1" : "")) {
488 fprintf(stderr, "error setting user initiated strace system property\n");
489 return false;
490 }
491 return true;
492}
493
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800494// Enable or disable kernel tracing.
495static bool setTracingEnabled(bool enable)
496{
497 return setKernelOptionEnable(k_tracingOnPath, enable);
498}
499
500// Clear the contents of the kernel trace.
501static bool clearTrace()
502{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700503 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800504}
505
506// Set the size of the kernel's trace buffer in kilobytes.
507static bool setTraceBufferSizeKB(int size)
508{
509 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800510 if (size < 1) {
511 size = 1;
512 }
513 snprintf(str, 32, "%d", size);
514 return writeStr(k_traceBufferSizePath, str);
515}
516
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700517#if 0
518// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700519// Set the default size of cmdline hashtable
520static bool setCmdlineSize()
521{
Joel Fernandesce964f22017-06-06 12:20:29 -0700522 if (fileExists(k_traceCmdlineSizePath)) {
523 return writeStr(k_traceCmdlineSizePath, "8192");
524 }
525 return true;
Joel Fernandesed80bd02017-06-02 10:19:28 -0700526}
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700527#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700528
Carmen Jacksonea826792017-05-05 11:42:32 -0700529// Set the clock to the best available option while tracing. Use 'boot' if it's
530// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700531// Any write to the trace_clock sysfs file will reset the buffer, so only
532// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700533static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800534{
Carmen Jacksonea826792017-05-05 11:42:32 -0700535 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
536 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
537 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700538
Carmen Jacksonea826792017-05-05 11:42:32 -0700539 std::string newClock;
540 if (clockStr.find("boot") != std::string::npos) {
541 newClock = "boot";
542 } else if (clockStr.find("mono") != std::string::npos) {
543 newClock = "mono";
544 } else {
545 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700546 }
547
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700548 size_t begin = clockStr.find('[') + 1;
549 size_t end = clockStr.find(']');
Carmen Jacksonea826792017-05-05 11:42:32 -0700550 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
551 return true;
552 }
553 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800554}
555
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700556static bool setPrintTgidEnableIfPresent(bool enable)
557{
John Reckedbf9ec2018-06-29 11:15:17 -0700558 // Pre-4.13 this was options/print-tgid as an android-specific option.
559 // In 4.13+ this is an upstream option called options/record-tgid
560 // Both options produce the same ftrace format change
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700561 if (fileExists(k_printTgidPath)) {
562 return setKernelOptionEnable(k_printTgidPath, enable);
563 }
John Recke757b1c2018-06-28 12:24:33 -0700564 if (fileExists(k_recordTgidPath)) {
565 return setKernelOptionEnable(k_recordTgidPath, enable);
566 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700567 return true;
568}
569
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800570// Poke all the binder-enabled processes in the system to get them to re-read
571// their system properties.
572static bool pokeBinderServices()
573{
574 sp<IServiceManager> sm = defaultServiceManager();
575 Vector<String16> services = sm->listServices();
576 for (size_t i = 0; i < services.size(); i++) {
577 sp<IBinder> obj = sm->checkService(services[i]);
Yi Kong19d5c002018-07-20 13:39:55 -0700578 if (obj != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800579 Parcel data;
580 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
Yi Kong19d5c002018-07-20 13:39:55 -0700581 nullptr, 0) != OK) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800582 if (false) {
583 // XXX: For some reason this fails on tablets trying to
584 // poke the "phone" service. It's not clear whether some
585 // are expected to fail.
586 String8 svc(services[i]);
587 fprintf(stderr, "error poking binder service %s\n",
588 svc.string());
589 return false;
590 }
591 }
592 }
593 }
594 return true;
595}
596
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100597// Poke all the HAL processes in the system to get them to re-read
598// their system properties.
599static void pokeHalServices()
600{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100601 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100602 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100603 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100604 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100605
606 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800607
608 if (sm == nullptr) {
609 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
610 return;
611 }
612
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800613 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100614 for (size_t i = 0; i < interfaces.size(); i++) {
615 string fqInstanceName = interfaces[i];
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700616 string::size_type n = fqInstanceName.find('/');
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100617 if (n == std::string::npos || interfaces[i].size() == n+1)
618 continue;
619 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
620 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100621 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
622 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100623 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100624 continue;
625 }
Carmen Jackson73206122017-04-18 15:37:57 -0700626
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100627 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700628 if (interface == nullptr) {
629 // ignore
630 continue;
631 }
632
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100633 auto notifyRet = interface->notifySyspropsChanged();
634 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100635 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800636 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100637 }
638 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800639 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100640 // TODO(b/34242478) fix this when we determine the correct ACL
641 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800642 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100643}
644
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800645// Set the trace tags that userland tracing uses, and poke the running
646// processes to pick up the new value.
647static bool setTagsProperty(uint64_t tags)
648{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700649 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
650 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800651 fprintf(stderr, "error setting trace tags system property\n");
652 return false;
653 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700654 return true;
655}
656
sergeyv4144eff2016-04-28 11:40:04 -0700657static void clearAppProperties()
658{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700659 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700660 fprintf(stderr, "failed to clear system property: %s",
661 k_traceAppsNumberProperty);
662 }
663}
664
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700665// Set the system property that indicates which apps should perform
666// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700667static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700668{
sergeyv4144eff2016-04-28 11:40:04 -0700669 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700670 char* start = cmdline;
Yi Kong19d5c002018-07-20 13:39:55 -0700671 while (start != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700672 char* end = strchr(start, ',');
Yi Kong19d5c002018-07-20 13:39:55 -0700673 if (end != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700674 *end = '\0';
675 end++;
676 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700677 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
678 if (!android::base::SetProperty(key, start)) {
679 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700680 clearAppProperties();
681 return false;
682 }
683 start = end;
684 i++;
685 }
686
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700687 std::string value = android::base::StringPrintf("%d", i);
688 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
689 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700690 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700691 return false;
692 }
693 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800694}
695
696// Disable all /sys/ enable files.
697static bool disableKernelTraceEvents() {
698 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700699 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800700 const TracingCategory &c = k_categories[i];
701 for (int j = 0; j < MAX_SYS_FILES; j++) {
702 const char* path = c.sysfiles[j].path;
Yi Kong19d5c002018-07-20 13:39:55 -0700703 if (path != nullptr && fileIsWritable(path)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800704 ok &= setKernelOptionEnable(path, false);
705 }
706 }
707 }
708 return ok;
709}
710
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700711// Verify that the comma separated list of functions are being traced by the
712// kernel.
713static bool verifyKernelTraceFuncs(const char* funcs)
714{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100715 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800716 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100717 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700718 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100719 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700720 }
721
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100722 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700723
724 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100725 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700726 bool ok = true;
727 char* myFuncs = strdup(funcs);
728 char* func = strtok(myFuncs, ",");
729 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100730 if (!strchr(func, '*')) {
731 String8 fancyFunc = String8::format("\n%s\n", func);
732 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
733 if (!found || func[0] == '\0') {
734 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
735 "to trace.\n", func);
736 ok = false;
737 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700738 }
Yi Kong19d5c002018-07-20 13:39:55 -0700739 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700740 }
741 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700742 return ok;
743}
744
745// Set the comma separated list of functions that the kernel is to trace.
746static bool setKernelTraceFuncs(const char* funcs)
747{
748 bool ok = true;
749
Yi Kong19d5c002018-07-20 13:39:55 -0700750 if (funcs == nullptr || funcs[0] == '\0') {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700751 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700752 if (fileIsWritable(k_currentTracerPath)) {
753 ok &= writeStr(k_currentTracerPath, "nop");
754 }
755 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700756 ok &= truncateFile(k_ftraceFilterPath);
757 }
758 } else {
759 // Enable kernel function tracing.
760 ok &= writeStr(k_currentTracerPath, "function_graph");
761 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
762 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
763 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
764 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
765
766 // Set the requested filter functions.
767 ok &= truncateFile(k_ftraceFilterPath);
768 char* myFuncs = strdup(funcs);
769 char* func = strtok(myFuncs, ",");
770 while (func) {
771 ok &= appendStr(k_ftraceFilterPath, func);
Yi Kong19d5c002018-07-20 13:39:55 -0700772 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700773 }
774 free(myFuncs);
775
776 // Verify that the set functions are being traced.
777 if (ok) {
778 ok &= verifyKernelTraceFuncs(funcs);
779 }
780 }
781
782 return ok;
783}
784
Wei Wang16a63a42018-09-21 15:47:45 -0700785static bool setCategoryEnable(const char* name)
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900786{
Wei Wang16a63a42018-09-21 15:47:45 -0700787 bool vendor_found = false;
788 for (auto &c : g_vendorCategories) {
789 if (strcmp(name, c.name.c_str()) == 0) {
790 c.enabled = true;
791 vendor_found = true;
792 }
793 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700794 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900795 const TracingCategory& c = k_categories[i];
796 if (strcmp(name, c.name) == 0) {
797 if (isCategorySupported(c)) {
Wei Wang16a63a42018-09-21 15:47:45 -0700798 g_categoryEnables[i] = true;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900799 return true;
800 } else {
801 if (isCategorySupportedForRoot(c)) {
802 fprintf(stderr, "error: category \"%s\" requires root "
803 "privileges.\n", name);
804 } else {
805 fprintf(stderr, "error: category \"%s\" is not supported "
806 "on this device.\n", name);
807 }
808 return false;
809 }
810 }
811 }
Wei Wang16a63a42018-09-21 15:47:45 -0700812 if (vendor_found) {
813 return true;
814 }
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900815 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
816 return false;
817}
818
819static bool setCategoriesEnableFromFile(const char* categories_file)
820{
821 if (!categories_file) {
822 return true;
823 }
Yi Kong19d5c002018-07-20 13:39:55 -0700824 Tokenizer* tokenizer = nullptr;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900825 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
826 return false;
827 }
828 bool ok = true;
829 while (!tokenizer->isEol()) {
830 String8 token = tokenizer->nextToken(" ");
831 if (token.isEmpty()) {
832 tokenizer->skipDelimiters(" ");
833 continue;
834 }
Wei Wang16a63a42018-09-21 15:47:45 -0700835 ok &= setCategoryEnable(token.string());
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900836 }
837 delete tokenizer;
838 return ok;
839}
840
Hector Dearman11845782018-03-08 14:35:44 +0000841static bool setUpUserspaceTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800842{
843 bool ok = true;
844
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800845 // Set up the tags property.
846 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700847 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800848 if (g_categoryEnables[i]) {
849 const TracingCategory &c = k_categories[i];
850 tags |= c.tags;
851 }
852 }
853 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700854
855 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700856 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700857 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
858 coreServicesTagEnabled = g_categoryEnables[i];
859 }
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700860
861 // Set whether to poke PDX services in this session.
862 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
863 g_tracePdx = g_categoryEnables[i];
864 }
sergeyvdb404152016-05-02 19:26:07 -0700865 }
866
867 std::string packageList(g_debugAppCmdLine);
868 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700869 if (!packageList.empty()) {
870 packageList += ",";
871 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700872 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700873 }
Dan Austin09a79872016-05-31 13:27:03 -0700874 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700875 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100876 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800877
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700878 if (g_tracePdx) {
879 ok &= ServiceUtility::PokeServices();
880 }
881
Hector Dearman11845782018-03-08 14:35:44 +0000882 return ok;
883}
884
885static void cleanUpUserspaceTracing()
886{
887 setTagsProperty(0);
888 clearAppProperties();
889 pokeBinderServices();
890
891 if (g_tracePdx) {
892 ServiceUtility::PokeServices();
893 }
894}
895
896
897// Set all the kernel tracing settings to the desired state for this trace
898// capture.
899static bool setUpKernelTracing()
900{
901 bool ok = true;
902
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700903 ok &= setUserInitiatedTraceProperty(true);
904
Hector Dearman11845782018-03-08 14:35:44 +0000905 // Set up the tracing options.
906 ok &= setCategoriesEnableFromFile(g_categoriesFile);
907 ok &= setTraceOverwriteEnable(g_traceOverwrite);
908 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
909 // TODO: Re-enable after stabilization
910 //ok &= setCmdlineSize();
911 ok &= setClock();
912 ok &= setPrintTgidEnableIfPresent(true);
913 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
914
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800915 // Disable all the sysfs enables. This is done as a separate loop from
916 // the enables to allow the same enable to exist in multiple categories.
917 ok &= disableKernelTraceEvents();
918
919 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700920 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800921 if (g_categoryEnables[i]) {
922 const TracingCategory &c = k_categories[i];
923 for (int j = 0; j < MAX_SYS_FILES; j++) {
924 const char* path = c.sysfiles[j].path;
925 bool required = c.sysfiles[j].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700926 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800927 if (fileIsWritable(path)) {
928 ok &= setKernelOptionEnable(path, true);
929 } else if (required) {
930 fprintf(stderr, "error writing file %s\n", path);
931 ok = false;
932 }
933 }
934 }
935 }
936 }
937
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800938 return ok;
939}
940
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700941// Reset all the kernel tracing settings to their default state.
Hector Dearman11845782018-03-08 14:35:44 +0000942static void cleanUpKernelTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800943{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800944 // Disable all tracing that we're able to.
945 disableKernelTraceEvents();
946
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800947 // Set the options back to their defaults.
948 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700949 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700950 setPrintTgidEnableIfPresent(false);
Yi Kong19d5c002018-07-20 13:39:55 -0700951 setKernelTraceFuncs(nullptr);
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700952 setUserInitiatedTraceProperty(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700953}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800954
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700955// Enable tracing in the kernel.
956static bool startTrace()
957{
958 return setTracingEnabled(true);
959}
960
961// Disable tracing in the kernel.
962static void stopTrace()
963{
964 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800965}
966
Martijn Coenend9535872015-11-26 10:00:55 +0100967// Read data from the tracing pipe and forward to stdout
968static void streamTrace()
969{
970 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800971 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100972 if (traceFD == -1) {
973 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
974 strerror(errno), errno);
975 return;
976 }
977 while (!g_traceAborted) {
978 ssize_t bytes_read = read(traceFD, trace_data, 4096);
979 if (bytes_read > 0) {
980 write(STDOUT_FILENO, trace_data, bytes_read);
981 fflush(stdout);
982 } else {
983 if (!g_traceAborted) {
984 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
985 bytes_read, errno, strerror(errno));
986 }
987 break;
988 }
989 }
990}
991
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800992// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700993static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800994{
John Reck6c8ac922016-03-28 11:25:30 -0700995 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800996 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800997 if (traceFD == -1) {
998 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
999 strerror(errno), errno);
1000 return;
1001 }
1002
1003 if (g_compress) {
1004 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -08001005 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001006
1007 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001008 if (result != Z_OK) {
1009 fprintf(stderr, "error initializing zlib: %d\n", result);
1010 close(traceFD);
1011 return;
1012 }
1013
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001014 constexpr size_t bufSize = 64*1024;
1015 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
1016 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
1017 if (!in || !out) {
1018 fprintf(stderr, "couldn't allocate buffers\n");
1019 close(traceFD);
1020 return;
1021 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001022
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001023 int flush = Z_NO_FLUSH;
1024
1025 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001026 zs.avail_out = bufSize;
1027
1028 do {
1029
1030 if (zs.avail_in == 0) {
1031 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001032 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001033 if (result < 0) {
1034 fprintf(stderr, "error reading trace: %s (%d)\n",
1035 strerror(errno), errno);
1036 result = Z_STREAM_END;
1037 break;
1038 } else if (result == 0) {
1039 flush = Z_FINISH;
1040 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001041 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001042 zs.avail_in = result;
1043 }
1044 }
1045
1046 if (zs.avail_out == 0) {
1047 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -07001048 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001049 if ((size_t)result < bufSize) {
1050 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1051 strerror(errno), errno);
1052 result = Z_STREAM_END; // skip deflate error message
1053 zs.avail_out = bufSize; // skip the final write
1054 break;
1055 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001056 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001057 zs.avail_out = bufSize;
1058 }
1059
1060 } while ((result = deflate(&zs, flush)) == Z_OK);
1061
1062 if (result != Z_STREAM_END) {
1063 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
1064 }
1065
1066 if (zs.avail_out < bufSize) {
1067 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -07001068 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001069 if ((size_t)result < bytes) {
1070 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1071 strerror(errno), errno);
1072 }
1073 }
1074
1075 result = deflateEnd(&zs);
1076 if (result != Z_OK) {
1077 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1078 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001079 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001080 char buf[4096];
1081 ssize_t rc;
1082 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1083 if (!android::base::WriteFully(outFd, buf, rc)) {
1084 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1085 break;
1086 }
1087 }
1088 if (rc == -1) {
1089 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001090 }
1091 }
1092
1093 close(traceFD);
1094}
1095
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001096static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001097{
1098 if (!g_nohup) {
1099 g_traceAborted = true;
1100 }
1101}
1102
1103static void registerSigHandler()
1104{
1105 struct sigaction sa;
1106 sigemptyset(&sa.sa_mask);
1107 sa.sa_flags = 0;
1108 sa.sa_handler = handleSignal;
Yi Kong19d5c002018-07-20 13:39:55 -07001109 sigaction(SIGHUP, &sa, nullptr);
1110 sigaction(SIGINT, &sa, nullptr);
1111 sigaction(SIGQUIT, &sa, nullptr);
1112 sigaction(SIGTERM, &sa, nullptr);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001113}
1114
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001115static void listSupportedCategories()
1116{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001117 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001118 const TracingCategory& c = k_categories[i];
1119 if (isCategorySupported(c)) {
1120 printf(" %10s - %s\n", c.name, c.longname);
1121 }
1122 }
Wei Wang16a63a42018-09-21 15:47:45 -07001123 for (const auto &c : g_vendorCategories) {
1124 printf(" %10s - %s (HAL)\n", c.name.c_str(), c.description.c_str());
1125 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001126}
1127
1128// Print the command usage help to stderr.
1129static void showHelp(const char *cmd)
1130{
1131 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1132 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001133 " -a appname enable app-level tracing for a comma "
Daniel Colascione519a0792018-02-09 20:05:39 -08001134 "separated list of cmdlines; * is a wildcard matching any process\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001135 " -b N use a trace buffer size of N KB\n"
1136 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001137 " -f filename use the categories written in a file as space-separated\n"
1138 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001139 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001140 " -n ignore signals\n"
1141 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001142 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001143 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001144 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001145 " --async_dump dump the current contents of circular trace buffer\n"
1146 " --async_stop stop tracing and dump the current contents of circular\n"
1147 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001148 " --stream stream trace to stdout as it enters the trace buffer\n"
1149 " Note: this can take significant CPU time, and is best\n"
1150 " used for measuring things that are not affected by\n"
1151 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001152 " --list_categories\n"
1153 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001154 " -o filename write the trace to the specified file instead\n"
1155 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001156 );
1157}
1158
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001159bool findTraceFiles()
1160{
1161 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1162 static const std::string tracefs_path = "/sys/kernel/tracing/";
1163 static const std::string trace_file = "trace_marker";
1164
1165 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1166 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1167
1168 if (!tracefs && !debugfs) {
1169 fprintf(stderr, "Error: Did not find trace folder\n");
1170 return false;
1171 }
1172
1173 if (tracefs) {
1174 g_traceFolder = tracefs_path;
1175 } else {
1176 g_traceFolder = debugfs_path;
1177 }
1178
1179 return true;
1180}
1181
Wei Wang16a63a42018-09-21 15:47:45 -07001182void initVendorCategories()
1183{
1184 g_atraceHal = IAtraceDevice::getService();
1185
1186 if (g_atraceHal == nullptr) {
1187 // No atrace HAL
1188 return;
1189 }
1190
1191 Return<void> ret = g_atraceHal->listCategories(
1192 [](const auto& list) {
1193 g_vendorCategories.reserve(list.size());
1194 for (const auto& category : list) {
1195 g_vendorCategories.emplace_back(category.name, category.description, false);
1196 }
1197 });
1198 if (!ret.isOk()) {
1199 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1200 }
1201}
1202
1203static bool setUpVendorTracing()
1204{
1205 if (g_atraceHal == nullptr) {
1206 // No atrace HAL
1207 return true;
1208 }
1209
1210 std::vector<hidl_string> categories;
1211 for (const auto &c : g_vendorCategories) {
1212 if (c.enabled) {
1213 categories.emplace_back(c.name);
1214 }
1215 }
1216
1217 if (!categories.size()) {
1218 return true;
1219 }
1220
1221 auto ret = g_atraceHal->enableCategories(categories);
1222 if (!ret.isOk()) {
1223 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1224 return false;
1225 } else if (ret != Status::SUCCESS) {
1226 fprintf(stderr, "calling atrace HAL failed: %s\n", toString(ret).c_str());
1227 return false;
1228 }
1229 return true;
1230}
1231
1232static bool cleanUpVendorTracing()
1233{
1234 if (g_atraceHal == nullptr) {
1235 // No atrace HAL
1236 return true;
1237 }
1238
1239 if (!g_vendorCategories.size()) {
1240 // No vendor categories
1241 return true;
1242 }
1243
1244 auto ret = g_atraceHal->disableAllCategories();
1245 if (!ret.isOk()) {
1246 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1247 return false;
1248 } else if (ret != Status::SUCCESS) {
1249 fprintf(stderr, "calling atrace HAL failed: %s\n", toString(ret).c_str());
1250 return false;
1251 }
1252 return true;
1253}
1254
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001255int main(int argc, char **argv)
1256{
1257 bool async = false;
1258 bool traceStart = true;
1259 bool traceStop = true;
1260 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001261 bool traceStream = false;
Hector Dearman11845782018-03-08 14:35:44 +00001262 bool onlyUserspace = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001263
1264 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1265 showHelp(argv[0]);
1266 exit(0);
1267 }
1268
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001269 if (!findTraceFiles()) {
1270 fprintf(stderr, "No trace folder found\n");
1271 exit(-1);
1272 }
1273
Wei Wang16a63a42018-09-21 15:47:45 -07001274 initVendorCategories();
1275
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001276 for (;;) {
1277 int ret;
1278 int option_index = 0;
1279 static struct option long_options[] = {
Yi Kong19d5c002018-07-20 13:39:55 -07001280 {"async_start", no_argument, nullptr, 0 },
1281 {"async_stop", no_argument, nullptr, 0 },
1282 {"async_dump", no_argument, nullptr, 0 },
1283 {"only_userspace", no_argument, nullptr, 0 },
1284 {"list_categories", no_argument, nullptr, 0 },
1285 {"stream", no_argument, nullptr, 0 },
1286 {nullptr, 0, nullptr, 0 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001287 };
1288
John Reck40b26b42016-03-30 09:44:36 -07001289 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001290 long_options, &option_index);
1291
1292 if (ret < 0) {
1293 for (int i = optind; i < argc; i++) {
Wei Wang16a63a42018-09-21 15:47:45 -07001294 if (!setCategoryEnable(argv[i])) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001295 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1296 exit(1);
1297 }
1298 }
1299 break;
1300 }
1301
1302 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001303 case 'a':
1304 g_debugAppCmdLine = optarg;
1305 break;
1306
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001307 case 'b':
1308 g_traceBufferSizeKB = atoi(optarg);
1309 break;
1310
1311 case 'c':
1312 g_traceOverwrite = true;
1313 break;
1314
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001315 case 'f':
1316 g_categoriesFile = optarg;
1317 break;
1318
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001319 case 'k':
1320 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001321 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001322
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001323 case 'n':
1324 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001325 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001326
1327 case 's':
1328 g_initialSleepSecs = atoi(optarg);
1329 break;
1330
1331 case 't':
1332 g_traceDurationSeconds = atoi(optarg);
1333 break;
1334
1335 case 'z':
1336 g_compress = true;
1337 break;
1338
John Reck40b26b42016-03-30 09:44:36 -07001339 case 'o':
1340 g_outputFile = optarg;
1341 break;
1342
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001343 case 0:
1344 if (!strcmp(long_options[option_index].name, "async_start")) {
1345 async = true;
1346 traceStop = false;
1347 traceDump = false;
1348 g_traceOverwrite = true;
1349 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1350 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001351 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001352 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1353 async = true;
1354 traceStart = false;
1355 traceStop = false;
Hector Dearman11845782018-03-08 14:35:44 +00001356 } else if (!strcmp(long_options[option_index].name, "only_userspace")) {
1357 onlyUserspace = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001358 } else if (!strcmp(long_options[option_index].name, "stream")) {
1359 traceStream = true;
1360 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001361 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1362 listSupportedCategories();
1363 exit(0);
1364 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001365 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001366
1367 default:
1368 fprintf(stderr, "\n");
1369 showHelp(argv[0]);
1370 exit(-1);
1371 break;
1372 }
1373 }
1374
Hector Dearman11845782018-03-08 14:35:44 +00001375 if (onlyUserspace) {
1376 if (!async || !(traceStart || traceStop)) {
1377 fprintf(stderr, "--only_userspace can only be used with "
1378 "--async_start or --async_stop\n");
1379 exit(1);
1380 }
1381 }
1382
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001383 registerSigHandler();
1384
1385 if (g_initialSleepSecs > 0) {
1386 sleep(g_initialSleepSecs);
1387 }
1388
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001389 bool ok = true;
Hector Dearman11845782018-03-08 14:35:44 +00001390
Wei Wang5b73b742018-03-08 13:33:12 -08001391 if (traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001392 ok &= setUpUserspaceTracing();
1393 }
1394
1395 if (ok && traceStart && !onlyUserspace) {
1396 ok &= setUpKernelTracing();
Wei Wang16a63a42018-09-21 15:47:45 -07001397 ok &= setUpVendorTracing();
Wei Wang5b73b742018-03-08 13:33:12 -08001398 ok &= startTrace();
1399 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001400
1401 if (ok && traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001402
1403 if (!traceStream && !onlyUserspace) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001404 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001405 fflush(stdout);
1406 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001407
1408 // We clear the trace after starting it because tracing gets enabled for
1409 // each CPU individually in the kernel. Having the beginning of the trace
1410 // contain entries from only one CPU can cause "begin" entries without a
1411 // matching "end" entry to show up if a task gets migrated from one CPU to
1412 // another.
Hector Dearman11845782018-03-08 14:35:44 +00001413 if (!onlyUserspace)
1414 ok = clearTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001415
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001416 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001417 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001418 // Sleep to allow the trace to be captured.
1419 struct timespec timeLeft;
1420 timeLeft.tv_sec = g_traceDurationSeconds;
1421 timeLeft.tv_nsec = 0;
1422 do {
1423 if (g_traceAborted) {
1424 break;
1425 }
1426 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1427 }
Martijn Coenend9535872015-11-26 10:00:55 +01001428
1429 if (traceStream) {
1430 streamTrace();
1431 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001432 }
1433
1434 // Stop the trace and restore the default settings.
Hector Dearman11845782018-03-08 14:35:44 +00001435 if (traceStop && !onlyUserspace)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001436 stopTrace();
1437
Hector Dearman11845782018-03-08 14:35:44 +00001438 if (ok && traceDump && !onlyUserspace) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001439 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001440 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001441 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001442 int outFd = STDOUT_FILENO;
1443 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001444 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001445 }
1446 if (outFd == -1) {
1447 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1448 } else {
1449 dprintf(outFd, "TRACE:\n");
1450 dumpTrace(outFd);
1451 if (g_outputFile) {
1452 close(outFd);
1453 }
1454 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001455 } else {
1456 printf("\ntrace aborted.\n");
1457 fflush(stdout);
1458 }
1459 clearTrace();
1460 } else if (!ok) {
1461 fprintf(stderr, "unable to start tracing\n");
1462 }
1463
1464 // Reset the trace buffer size to 1.
Hector Dearman11845782018-03-08 14:35:44 +00001465 if (traceStop) {
Wei Wang16a63a42018-09-21 15:47:45 -07001466 cleanUpVendorTracing();
Hector Dearman11845782018-03-08 14:35:44 +00001467 cleanUpUserspaceTracing();
1468 if (!onlyUserspace)
1469 cleanUpKernelTracing();
1470 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001471
1472 return g_traceAborted ? 1 : 0;
1473}