blob: 39b3aacc738cdf5e99d2831369ccba1b0d7732b1 [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 Halla978cef2019-02-25 16:24:10 -0800195 // linux kernel < 4.9
Jesse Hallae001a32018-05-15 12:02:15 -0700196 { OPT, "events/sync/enable" },
Jesse Halla978cef2019-02-25 16:24:10 -0800197 // linux kernel == 4.9.x
Jesse Hallae001a32018-05-15 12:02:15 -0700198 { OPT, "events/fence/enable" },
Jesse Halla978cef2019-02-25 16:24:10 -0800199 // linux kernel > 4.9
200 { OPT, "events/dma_fence/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800201 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700202 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800203 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800204 } },
Colin Cross580407f2014-08-18 15:22:13 -0700205 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800206 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
207 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
208 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
209 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Carmen Jackson7a23eb72018-07-02 13:14:56 -0700210 { OPT, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700211 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800212 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800213 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800214 } },
Scott Bauerae473362015-06-08 16:32:36 -0700215 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800216 { REQ, "events/binder/binder_transaction/enable" },
217 { REQ, "events/binder/binder_transaction_received/enable" },
Mika Raento80c3e5d2018-06-25 16:47:24 +0100218 { REQ, "events/binder/binder_transaction_alloc_buf/enable" },
Martijn Coenen7f3d7a22017-05-26 09:50:55 -0700219 { OPT, "events/binder/binder_set_priority/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700220 } },
221 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800222 { OPT, "events/binder/binder_lock/enable" },
223 { OPT, "events/binder/binder_locked/enable" },
224 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700225 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200226 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800227 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200228 } },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700229 { "memory", "Memory", 0, {
230 { OPT, "events/kmem/rss_stat/enable" },
231 { OPT, "events/kmem/ion_heap_grow/enable" },
232 { OPT, "events/kmem/ion_heap_shrink/enable" },
Carmen Jacksonb690b5a2018-11-21 13:04:50 -0800233 { OPT, "events/oom/oom_score_adj_update/enable" },
234 { OPT, "events/sched/sched_process_exit/enable" },
235 { OPT, "events/task/task_rename/enable" },
236 { OPT, "events/task/task_newtask/enable" },
Carmen Jackson4f42f212018-10-16 18:25:52 -0700237 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800238};
239
Wei Wang16a63a42018-09-21 15:47:45 -0700240struct TracingVendorCategory {
241 // The name identifying the category.
242 std::string name;
243
244 // A longer description of the category.
245 std::string description;
246
247 // If the category is enabled through command.
248 bool enabled;
249
250 TracingVendorCategory(string &&name, string &&description, bool enabled)
251 : name(std::move(name))
252 , description(std::move(description))
253 , enabled(enabled)
254 {}
255};
256
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800257/* Command line options */
258static int g_traceDurationSeconds = 5;
259static bool g_traceOverwrite = false;
260static int g_traceBufferSizeKB = 2048;
261static bool g_compress = false;
262static bool g_nohup = false;
263static int g_initialSleepSecs = 0;
Yi Kong19d5c002018-07-20 13:39:55 -0700264static const char* g_categoriesFile = nullptr;
265static const char* g_kernelTraceFuncs = nullptr;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700266static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700267static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800268
269/* Global state */
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700270static bool g_tracePdx = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800271static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700272static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800273static std::string g_traceFolder;
Wei Wang16a63a42018-09-21 15:47:45 -0700274static sp<IAtraceDevice> g_atraceHal;
275static std::vector<TracingVendorCategory> g_vendorCategories;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800276
277/* Sys file paths */
278static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800279 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800280
281static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800282 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800283
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700284#if 0
285// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700286static const char* k_traceCmdlineSizePath =
287 "saved_cmdlines_size";
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700288#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700289
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800290static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800291 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800292
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700293static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800294 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700295
296static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800297 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700298
John Recke757b1c2018-06-28 12:24:33 -0700299static const char* k_recordTgidPath =
300 "options/record-tgid";
301
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700302static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800303 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700304
305static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800306 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700307
308static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800309 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700310
311static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800312 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700313
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700314static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800315 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700316
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800317static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800318 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800319
320static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800321 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800322
Martijn Coenend9535872015-11-26 10:00:55 +0100323static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800324 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100325
John Reck469a1942015-03-26 15:31:35 -0700326static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800327 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700328
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800329// Check whether a file exists.
330static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800331 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800332}
333
334// Check whether a file is writable.
335static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800336 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800337}
338
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700339// Truncate a file.
340static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800341{
Jamie Gennis43122e72013-03-21 14:06:31 -0700342 // This uses creat rather than truncate because some of the debug kernel
343 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
344 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800345 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700346 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800347 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700348 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700349 return false;
350 }
351
Jamie Gennis43122e72013-03-21 14:06:31 -0700352 close(traceFD);
353
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700354 return true;
355}
356
357static bool _writeStr(const char* filename, const char* str, int flags)
358{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800359 std::string fullFilename = g_traceFolder + filename;
360 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800361 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800362 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800363 strerror(errno), errno);
364 return false;
365 }
366
367 bool ok = true;
368 ssize_t len = strlen(str);
369 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800370 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800371 strerror(errno), errno);
372 ok = false;
373 }
374
375 close(fd);
376
377 return ok;
378}
379
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700380// Write a string to a file, returning true if the write was successful.
381static bool writeStr(const char* filename, const char* str)
382{
383 return _writeStr(filename, str, O_WRONLY);
384}
385
386// Append a string to a file, returning true if the write was successful.
387static bool appendStr(const char* filename, const char* str)
388{
389 return _writeStr(filename, str, O_APPEND|O_WRONLY);
390}
391
John Reck469a1942015-03-26 15:31:35 -0700392static void writeClockSyncMarker()
393{
394 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200395 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800396 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200397 if (fd == -1) {
398 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
399 strerror(errno), errno);
400 return;
401 }
John Reck469a1942015-03-26 15:31:35 -0700402 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200403
404 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
405 if (write(fd, buffer, len) != len) {
406 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
407 }
408
409 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
410 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
411 if (write(fd, buffer, len) != len) {
412 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
413 }
414
415 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700416}
417
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800418// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
419// file.
420static bool setKernelOptionEnable(const char* filename, bool enable)
421{
422 return writeStr(filename, enable ? "1" : "0");
423}
424
425// Check whether the category is supported on the device with the current
426// rootness. A category is supported only if all its required /sys/ files are
427// writable and if enabling the category will enable one or more tracing tags
428// or /sys/ files.
429static bool isCategorySupported(const TracingCategory& category)
430{
sergeyvdb404152016-05-02 19:26:07 -0700431 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700432 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700433 }
434
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700435 if (strcmp(category.name, k_pdxServiceCategory) == 0) {
436 return true;
437 }
438
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800439 bool ok = category.tags != 0;
440 for (int i = 0; i < MAX_SYS_FILES; i++) {
441 const char* path = category.sysfiles[i].path;
442 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700443 if (path != nullptr) {
Carmen Jackson5bbc9a22018-12-06 13:47:18 -0800444 if (fileIsWritable(path)) {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800445 ok = true;
Carmen Jackson5bbc9a22018-12-06 13:47:18 -0800446 } else if (req) {
447 return false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800448 }
449 }
450 }
451 return ok;
452}
453
454// Check whether the category would be supported on the device if the user
455// were root. This function assumes that root is able to write to any file
456// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700457// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800458static bool isCategorySupportedForRoot(const TracingCategory& category)
459{
460 bool ok = category.tags != 0;
461 for (int i = 0; i < MAX_SYS_FILES; i++) {
462 const char* path = category.sysfiles[i].path;
463 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700464 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800465 if (req) {
466 if (!fileExists(path)) {
467 return false;
468 } else {
469 ok = true;
470 }
471 } else {
472 ok |= fileExists(path);
473 }
474 }
475 }
476 return ok;
477}
478
479// Enable or disable overwriting of the kernel trace buffers. Disabling this
480// will cause tracing to stop once the trace buffers have filled up.
481static bool setTraceOverwriteEnable(bool enable)
482{
483 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
484}
485
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700486// Set the user initiated trace property
487static bool setUserInitiatedTraceProperty(bool enable)
488{
489 if (!android::base::SetProperty(k_userInitiatedTraceProperty, enable ? "1" : "")) {
490 fprintf(stderr, "error setting user initiated strace system property\n");
491 return false;
492 }
493 return true;
494}
495
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800496// Enable or disable kernel tracing.
497static bool setTracingEnabled(bool enable)
498{
499 return setKernelOptionEnable(k_tracingOnPath, enable);
500}
501
502// Clear the contents of the kernel trace.
503static bool clearTrace()
504{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700505 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800506}
507
508// Set the size of the kernel's trace buffer in kilobytes.
509static bool setTraceBufferSizeKB(int size)
510{
511 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800512 if (size < 1) {
513 size = 1;
514 }
515 snprintf(str, 32, "%d", size);
516 return writeStr(k_traceBufferSizePath, str);
517}
518
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700519#if 0
520// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700521// Set the default size of cmdline hashtable
522static bool setCmdlineSize()
523{
Joel Fernandesce964f22017-06-06 12:20:29 -0700524 if (fileExists(k_traceCmdlineSizePath)) {
525 return writeStr(k_traceCmdlineSizePath, "8192");
526 }
527 return true;
Joel Fernandesed80bd02017-06-02 10:19:28 -0700528}
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700529#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700530
Carmen Jacksonea826792017-05-05 11:42:32 -0700531// Set the clock to the best available option while tracing. Use 'boot' if it's
532// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700533// Any write to the trace_clock sysfs file will reset the buffer, so only
534// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700535static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800536{
Carmen Jacksonea826792017-05-05 11:42:32 -0700537 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
538 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
539 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700540
Carmen Jacksonea826792017-05-05 11:42:32 -0700541 std::string newClock;
542 if (clockStr.find("boot") != std::string::npos) {
543 newClock = "boot";
544 } else if (clockStr.find("mono") != std::string::npos) {
545 newClock = "mono";
546 } else {
547 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700548 }
549
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700550 size_t begin = clockStr.find('[') + 1;
551 size_t end = clockStr.find(']');
Carmen Jacksonea826792017-05-05 11:42:32 -0700552 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
553 return true;
554 }
555 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800556}
557
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700558static bool setPrintTgidEnableIfPresent(bool enable)
559{
John Reckedbf9ec2018-06-29 11:15:17 -0700560 // Pre-4.13 this was options/print-tgid as an android-specific option.
561 // In 4.13+ this is an upstream option called options/record-tgid
562 // Both options produce the same ftrace format change
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700563 if (fileExists(k_printTgidPath)) {
564 return setKernelOptionEnable(k_printTgidPath, enable);
565 }
John Recke757b1c2018-06-28 12:24:33 -0700566 if (fileExists(k_recordTgidPath)) {
567 return setKernelOptionEnable(k_recordTgidPath, enable);
568 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700569 return true;
570}
571
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800572// Poke all the binder-enabled processes in the system to get them to re-read
573// their system properties.
574static bool pokeBinderServices()
575{
576 sp<IServiceManager> sm = defaultServiceManager();
577 Vector<String16> services = sm->listServices();
578 for (size_t i = 0; i < services.size(); i++) {
579 sp<IBinder> obj = sm->checkService(services[i]);
Yi Kong19d5c002018-07-20 13:39:55 -0700580 if (obj != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800581 Parcel data;
582 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
Yi Kong19d5c002018-07-20 13:39:55 -0700583 nullptr, 0) != OK) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800584 if (false) {
585 // XXX: For some reason this fails on tablets trying to
586 // poke the "phone" service. It's not clear whether some
587 // are expected to fail.
588 String8 svc(services[i]);
589 fprintf(stderr, "error poking binder service %s\n",
590 svc.string());
591 return false;
592 }
593 }
594 }
595 }
596 return true;
597}
598
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100599// Poke all the HAL processes in the system to get them to re-read
600// their system properties.
601static void pokeHalServices()
602{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100603 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100604 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100605 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100606 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100607
608 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800609
610 if (sm == nullptr) {
611 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
612 return;
613 }
614
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800615 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100616 for (size_t i = 0; i < interfaces.size(); i++) {
617 string fqInstanceName = interfaces[i];
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700618 string::size_type n = fqInstanceName.find('/');
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100619 if (n == std::string::npos || interfaces[i].size() == n+1)
620 continue;
621 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
622 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100623 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
624 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100625 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100626 continue;
627 }
Carmen Jackson73206122017-04-18 15:37:57 -0700628
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100629 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700630 if (interface == nullptr) {
631 // ignore
632 continue;
633 }
634
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100635 auto notifyRet = interface->notifySyspropsChanged();
636 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100637 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800638 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100639 }
640 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800641 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100642 // TODO(b/34242478) fix this when we determine the correct ACL
643 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800644 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100645}
646
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800647// Set the trace tags that userland tracing uses, and poke the running
648// processes to pick up the new value.
649static bool setTagsProperty(uint64_t tags)
650{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700651 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
652 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800653 fprintf(stderr, "error setting trace tags system property\n");
654 return false;
655 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700656 return true;
657}
658
sergeyv4144eff2016-04-28 11:40:04 -0700659static void clearAppProperties()
660{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700661 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700662 fprintf(stderr, "failed to clear system property: %s",
663 k_traceAppsNumberProperty);
664 }
665}
666
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700667// Set the system property that indicates which apps should perform
668// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700669static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700670{
sergeyv4144eff2016-04-28 11:40:04 -0700671 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700672 char* start = cmdline;
Yi Kong19d5c002018-07-20 13:39:55 -0700673 while (start != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700674 char* end = strchr(start, ',');
Yi Kong19d5c002018-07-20 13:39:55 -0700675 if (end != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700676 *end = '\0';
677 end++;
678 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700679 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
680 if (!android::base::SetProperty(key, start)) {
681 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700682 clearAppProperties();
683 return false;
684 }
685 start = end;
686 i++;
687 }
688
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700689 std::string value = android::base::StringPrintf("%d", i);
690 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
691 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700692 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700693 return false;
694 }
695 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800696}
697
698// Disable all /sys/ enable files.
699static bool disableKernelTraceEvents() {
700 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700701 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800702 const TracingCategory &c = k_categories[i];
703 for (int j = 0; j < MAX_SYS_FILES; j++) {
704 const char* path = c.sysfiles[j].path;
Yi Kong19d5c002018-07-20 13:39:55 -0700705 if (path != nullptr && fileIsWritable(path)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800706 ok &= setKernelOptionEnable(path, false);
707 }
708 }
709 }
710 return ok;
711}
712
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700713// Verify that the comma separated list of functions are being traced by the
714// kernel.
715static bool verifyKernelTraceFuncs(const char* funcs)
716{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100717 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800718 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100719 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700720 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100721 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700722 }
723
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100724 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700725
726 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100727 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700728 bool ok = true;
729 char* myFuncs = strdup(funcs);
730 char* func = strtok(myFuncs, ",");
731 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100732 if (!strchr(func, '*')) {
733 String8 fancyFunc = String8::format("\n%s\n", func);
734 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
735 if (!found || func[0] == '\0') {
736 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
737 "to trace.\n", func);
738 ok = false;
739 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700740 }
Yi Kong19d5c002018-07-20 13:39:55 -0700741 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700742 }
743 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700744 return ok;
745}
746
747// Set the comma separated list of functions that the kernel is to trace.
748static bool setKernelTraceFuncs(const char* funcs)
749{
750 bool ok = true;
751
Yi Kong19d5c002018-07-20 13:39:55 -0700752 if (funcs == nullptr || funcs[0] == '\0') {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700753 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700754 if (fileIsWritable(k_currentTracerPath)) {
755 ok &= writeStr(k_currentTracerPath, "nop");
756 }
757 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700758 ok &= truncateFile(k_ftraceFilterPath);
759 }
760 } else {
761 // Enable kernel function tracing.
762 ok &= writeStr(k_currentTracerPath, "function_graph");
763 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
764 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
765 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
766 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
767
768 // Set the requested filter functions.
769 ok &= truncateFile(k_ftraceFilterPath);
770 char* myFuncs = strdup(funcs);
771 char* func = strtok(myFuncs, ",");
772 while (func) {
773 ok &= appendStr(k_ftraceFilterPath, func);
Yi Kong19d5c002018-07-20 13:39:55 -0700774 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700775 }
776 free(myFuncs);
777
778 // Verify that the set functions are being traced.
779 if (ok) {
780 ok &= verifyKernelTraceFuncs(funcs);
781 }
782 }
783
784 return ok;
785}
786
Wei Wang16a63a42018-09-21 15:47:45 -0700787static bool setCategoryEnable(const char* name)
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900788{
Wei Wang16a63a42018-09-21 15:47:45 -0700789 bool vendor_found = false;
790 for (auto &c : g_vendorCategories) {
791 if (strcmp(name, c.name.c_str()) == 0) {
792 c.enabled = true;
793 vendor_found = true;
794 }
795 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700796 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900797 const TracingCategory& c = k_categories[i];
798 if (strcmp(name, c.name) == 0) {
799 if (isCategorySupported(c)) {
Wei Wang16a63a42018-09-21 15:47:45 -0700800 g_categoryEnables[i] = true;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900801 return true;
802 } else {
803 if (isCategorySupportedForRoot(c)) {
804 fprintf(stderr, "error: category \"%s\" requires root "
805 "privileges.\n", name);
806 } else {
807 fprintf(stderr, "error: category \"%s\" is not supported "
808 "on this device.\n", name);
809 }
810 return false;
811 }
812 }
813 }
Wei Wang16a63a42018-09-21 15:47:45 -0700814 if (vendor_found) {
815 return true;
816 }
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900817 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
818 return false;
819}
820
821static bool setCategoriesEnableFromFile(const char* categories_file)
822{
823 if (!categories_file) {
824 return true;
825 }
Yi Kong19d5c002018-07-20 13:39:55 -0700826 Tokenizer* tokenizer = nullptr;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900827 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
828 return false;
829 }
830 bool ok = true;
831 while (!tokenizer->isEol()) {
832 String8 token = tokenizer->nextToken(" ");
833 if (token.isEmpty()) {
834 tokenizer->skipDelimiters(" ");
835 continue;
836 }
Wei Wang16a63a42018-09-21 15:47:45 -0700837 ok &= setCategoryEnable(token.string());
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900838 }
839 delete tokenizer;
840 return ok;
841}
842
Hector Dearman11845782018-03-08 14:35:44 +0000843static bool setUpUserspaceTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800844{
845 bool ok = true;
846
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800847 // Set up the tags property.
848 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700849 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800850 if (g_categoryEnables[i]) {
851 const TracingCategory &c = k_categories[i];
852 tags |= c.tags;
853 }
854 }
855 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700856
857 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700858 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700859 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
860 coreServicesTagEnabled = g_categoryEnables[i];
861 }
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700862
863 // Set whether to poke PDX services in this session.
864 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
865 g_tracePdx = g_categoryEnables[i];
866 }
sergeyvdb404152016-05-02 19:26:07 -0700867 }
868
869 std::string packageList(g_debugAppCmdLine);
870 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700871 if (!packageList.empty()) {
872 packageList += ",";
873 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700874 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700875 }
Dan Austin09a79872016-05-31 13:27:03 -0700876 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700877 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100878 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800879
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700880 if (g_tracePdx) {
881 ok &= ServiceUtility::PokeServices();
882 }
883
Hector Dearman11845782018-03-08 14:35:44 +0000884 return ok;
885}
886
887static void cleanUpUserspaceTracing()
888{
889 setTagsProperty(0);
890 clearAppProperties();
891 pokeBinderServices();
892
893 if (g_tracePdx) {
894 ServiceUtility::PokeServices();
895 }
896}
897
898
899// Set all the kernel tracing settings to the desired state for this trace
900// capture.
901static bool setUpKernelTracing()
902{
903 bool ok = true;
904
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700905 ok &= setUserInitiatedTraceProperty(true);
906
Hector Dearman11845782018-03-08 14:35:44 +0000907 // Set up the tracing options.
908 ok &= setCategoriesEnableFromFile(g_categoriesFile);
909 ok &= setTraceOverwriteEnable(g_traceOverwrite);
910 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
911 // TODO: Re-enable after stabilization
912 //ok &= setCmdlineSize();
913 ok &= setClock();
914 ok &= setPrintTgidEnableIfPresent(true);
915 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
916
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800917 // Disable all the sysfs enables. This is done as a separate loop from
918 // the enables to allow the same enable to exist in multiple categories.
919 ok &= disableKernelTraceEvents();
920
921 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700922 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800923 if (g_categoryEnables[i]) {
924 const TracingCategory &c = k_categories[i];
925 for (int j = 0; j < MAX_SYS_FILES; j++) {
926 const char* path = c.sysfiles[j].path;
927 bool required = c.sysfiles[j].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700928 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800929 if (fileIsWritable(path)) {
930 ok &= setKernelOptionEnable(path, true);
931 } else if (required) {
932 fprintf(stderr, "error writing file %s\n", path);
933 ok = false;
934 }
935 }
936 }
937 }
938 }
939
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800940 return ok;
941}
942
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700943// Reset all the kernel tracing settings to their default state.
Hector Dearman11845782018-03-08 14:35:44 +0000944static void cleanUpKernelTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800945{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800946 // Disable all tracing that we're able to.
947 disableKernelTraceEvents();
948
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800949 // Set the options back to their defaults.
950 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700951 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700952 setPrintTgidEnableIfPresent(false);
Yi Kong19d5c002018-07-20 13:39:55 -0700953 setKernelTraceFuncs(nullptr);
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700954 setUserInitiatedTraceProperty(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700955}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800956
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700957// Enable tracing in the kernel.
958static bool startTrace()
959{
960 return setTracingEnabled(true);
961}
962
963// Disable tracing in the kernel.
964static void stopTrace()
965{
966 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800967}
968
Martijn Coenend9535872015-11-26 10:00:55 +0100969// Read data from the tracing pipe and forward to stdout
970static void streamTrace()
971{
972 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800973 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100974 if (traceFD == -1) {
975 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
976 strerror(errno), errno);
977 return;
978 }
979 while (!g_traceAborted) {
980 ssize_t bytes_read = read(traceFD, trace_data, 4096);
981 if (bytes_read > 0) {
982 write(STDOUT_FILENO, trace_data, bytes_read);
983 fflush(stdout);
984 } else {
985 if (!g_traceAborted) {
986 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
987 bytes_read, errno, strerror(errno));
988 }
989 break;
990 }
991 }
992}
993
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800994// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700995static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800996{
John Reck6c8ac922016-03-28 11:25:30 -0700997 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800998 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800999 if (traceFD == -1) {
1000 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
1001 strerror(errno), errno);
1002 return;
1003 }
1004
1005 if (g_compress) {
1006 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -08001007 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001008
1009 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001010 if (result != Z_OK) {
1011 fprintf(stderr, "error initializing zlib: %d\n", result);
1012 close(traceFD);
1013 return;
1014 }
1015
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001016 constexpr size_t bufSize = 64*1024;
1017 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
1018 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
1019 if (!in || !out) {
1020 fprintf(stderr, "couldn't allocate buffers\n");
1021 close(traceFD);
1022 return;
1023 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001024
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001025 int flush = Z_NO_FLUSH;
1026
1027 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001028 zs.avail_out = bufSize;
1029
1030 do {
1031
1032 if (zs.avail_in == 0) {
1033 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001034 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001035 if (result < 0) {
1036 fprintf(stderr, "error reading trace: %s (%d)\n",
1037 strerror(errno), errno);
1038 result = Z_STREAM_END;
1039 break;
1040 } else if (result == 0) {
1041 flush = Z_FINISH;
1042 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001043 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001044 zs.avail_in = result;
1045 }
1046 }
1047
1048 if (zs.avail_out == 0) {
1049 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -07001050 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001051 if ((size_t)result < bufSize) {
1052 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1053 strerror(errno), errno);
1054 result = Z_STREAM_END; // skip deflate error message
1055 zs.avail_out = bufSize; // skip the final write
1056 break;
1057 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001058 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001059 zs.avail_out = bufSize;
1060 }
1061
1062 } while ((result = deflate(&zs, flush)) == Z_OK);
1063
1064 if (result != Z_STREAM_END) {
1065 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
1066 }
1067
1068 if (zs.avail_out < bufSize) {
1069 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -07001070 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001071 if ((size_t)result < bytes) {
1072 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1073 strerror(errno), errno);
1074 }
1075 }
1076
1077 result = deflateEnd(&zs);
1078 if (result != Z_OK) {
1079 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1080 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001081 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001082 char buf[4096];
1083 ssize_t rc;
1084 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1085 if (!android::base::WriteFully(outFd, buf, rc)) {
1086 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1087 break;
1088 }
1089 }
1090 if (rc == -1) {
1091 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001092 }
1093 }
1094
1095 close(traceFD);
1096}
1097
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001098static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001099{
1100 if (!g_nohup) {
1101 g_traceAborted = true;
1102 }
1103}
1104
1105static void registerSigHandler()
1106{
1107 struct sigaction sa;
1108 sigemptyset(&sa.sa_mask);
1109 sa.sa_flags = 0;
1110 sa.sa_handler = handleSignal;
Yi Kong19d5c002018-07-20 13:39:55 -07001111 sigaction(SIGHUP, &sa, nullptr);
1112 sigaction(SIGINT, &sa, nullptr);
1113 sigaction(SIGQUIT, &sa, nullptr);
1114 sigaction(SIGTERM, &sa, nullptr);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001115}
1116
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001117static void listSupportedCategories()
1118{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001119 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001120 const TracingCategory& c = k_categories[i];
1121 if (isCategorySupported(c)) {
1122 printf(" %10s - %s\n", c.name, c.longname);
1123 }
1124 }
Wei Wang16a63a42018-09-21 15:47:45 -07001125 for (const auto &c : g_vendorCategories) {
1126 printf(" %10s - %s (HAL)\n", c.name.c_str(), c.description.c_str());
1127 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001128}
1129
1130// Print the command usage help to stderr.
1131static void showHelp(const char *cmd)
1132{
1133 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1134 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001135 " -a appname enable app-level tracing for a comma "
Daniel Colascione519a0792018-02-09 20:05:39 -08001136 "separated list of cmdlines; * is a wildcard matching any process\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001137 " -b N use a trace buffer size of N KB\n"
1138 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001139 " -f filename use the categories written in a file as space-separated\n"
1140 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001141 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001142 " -n ignore signals\n"
1143 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001144 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001145 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001146 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001147 " --async_dump dump the current contents of circular trace buffer\n"
1148 " --async_stop stop tracing and dump the current contents of circular\n"
1149 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001150 " --stream stream trace to stdout as it enters the trace buffer\n"
1151 " Note: this can take significant CPU time, and is best\n"
1152 " used for measuring things that are not affected by\n"
1153 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001154 " --list_categories\n"
1155 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001156 " -o filename write the trace to the specified file instead\n"
1157 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001158 );
1159}
1160
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001161bool findTraceFiles()
1162{
1163 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1164 static const std::string tracefs_path = "/sys/kernel/tracing/";
1165 static const std::string trace_file = "trace_marker";
1166
1167 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1168 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1169
1170 if (!tracefs && !debugfs) {
1171 fprintf(stderr, "Error: Did not find trace folder\n");
1172 return false;
1173 }
1174
1175 if (tracefs) {
1176 g_traceFolder = tracefs_path;
1177 } else {
1178 g_traceFolder = debugfs_path;
1179 }
1180
1181 return true;
1182}
1183
Wei Wang16a63a42018-09-21 15:47:45 -07001184void initVendorCategories()
1185{
1186 g_atraceHal = IAtraceDevice::getService();
1187
1188 if (g_atraceHal == nullptr) {
1189 // No atrace HAL
1190 return;
1191 }
1192
1193 Return<void> ret = g_atraceHal->listCategories(
1194 [](const auto& list) {
1195 g_vendorCategories.reserve(list.size());
1196 for (const auto& category : list) {
1197 g_vendorCategories.emplace_back(category.name, category.description, false);
1198 }
1199 });
1200 if (!ret.isOk()) {
1201 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1202 }
1203}
1204
1205static bool setUpVendorTracing()
1206{
1207 if (g_atraceHal == nullptr) {
1208 // No atrace HAL
1209 return true;
1210 }
1211
1212 std::vector<hidl_string> categories;
1213 for (const auto &c : g_vendorCategories) {
1214 if (c.enabled) {
1215 categories.emplace_back(c.name);
1216 }
1217 }
1218
1219 if (!categories.size()) {
1220 return true;
1221 }
1222
1223 auto ret = g_atraceHal->enableCategories(categories);
1224 if (!ret.isOk()) {
1225 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1226 return false;
1227 } else if (ret != Status::SUCCESS) {
1228 fprintf(stderr, "calling atrace HAL failed: %s\n", toString(ret).c_str());
1229 return false;
1230 }
1231 return true;
1232}
1233
1234static bool cleanUpVendorTracing()
1235{
1236 if (g_atraceHal == nullptr) {
1237 // No atrace HAL
1238 return true;
1239 }
1240
1241 if (!g_vendorCategories.size()) {
1242 // No vendor categories
1243 return true;
1244 }
1245
1246 auto ret = g_atraceHal->disableAllCategories();
1247 if (!ret.isOk()) {
1248 fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
1249 return false;
1250 } else if (ret != Status::SUCCESS) {
1251 fprintf(stderr, "calling atrace HAL failed: %s\n", toString(ret).c_str());
1252 return false;
1253 }
1254 return true;
1255}
1256
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001257int main(int argc, char **argv)
1258{
1259 bool async = false;
1260 bool traceStart = true;
1261 bool traceStop = true;
1262 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001263 bool traceStream = false;
Hector Dearman11845782018-03-08 14:35:44 +00001264 bool onlyUserspace = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001265
1266 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1267 showHelp(argv[0]);
1268 exit(0);
1269 }
1270
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001271 if (!findTraceFiles()) {
1272 fprintf(stderr, "No trace folder found\n");
1273 exit(-1);
1274 }
1275
Wei Wang16a63a42018-09-21 15:47:45 -07001276 initVendorCategories();
1277
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001278 for (;;) {
1279 int ret;
1280 int option_index = 0;
1281 static struct option long_options[] = {
Yi Kong19d5c002018-07-20 13:39:55 -07001282 {"async_start", no_argument, nullptr, 0 },
1283 {"async_stop", no_argument, nullptr, 0 },
1284 {"async_dump", no_argument, nullptr, 0 },
1285 {"only_userspace", no_argument, nullptr, 0 },
1286 {"list_categories", no_argument, nullptr, 0 },
1287 {"stream", no_argument, nullptr, 0 },
1288 {nullptr, 0, nullptr, 0 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001289 };
1290
John Reck40b26b42016-03-30 09:44:36 -07001291 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001292 long_options, &option_index);
1293
1294 if (ret < 0) {
1295 for (int i = optind; i < argc; i++) {
Wei Wang16a63a42018-09-21 15:47:45 -07001296 if (!setCategoryEnable(argv[i])) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001297 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1298 exit(1);
1299 }
1300 }
1301 break;
1302 }
1303
1304 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001305 case 'a':
1306 g_debugAppCmdLine = optarg;
1307 break;
1308
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001309 case 'b':
1310 g_traceBufferSizeKB = atoi(optarg);
1311 break;
1312
1313 case 'c':
1314 g_traceOverwrite = true;
1315 break;
1316
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001317 case 'f':
1318 g_categoriesFile = optarg;
1319 break;
1320
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001321 case 'k':
1322 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001323 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001324
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001325 case 'n':
1326 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001327 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001328
1329 case 's':
1330 g_initialSleepSecs = atoi(optarg);
1331 break;
1332
1333 case 't':
1334 g_traceDurationSeconds = atoi(optarg);
1335 break;
1336
1337 case 'z':
1338 g_compress = true;
1339 break;
1340
John Reck40b26b42016-03-30 09:44:36 -07001341 case 'o':
1342 g_outputFile = optarg;
1343 break;
1344
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001345 case 0:
1346 if (!strcmp(long_options[option_index].name, "async_start")) {
1347 async = true;
1348 traceStop = false;
1349 traceDump = false;
1350 g_traceOverwrite = true;
1351 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1352 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001353 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001354 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1355 async = true;
1356 traceStart = false;
1357 traceStop = false;
Hector Dearman11845782018-03-08 14:35:44 +00001358 } else if (!strcmp(long_options[option_index].name, "only_userspace")) {
1359 onlyUserspace = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001360 } else if (!strcmp(long_options[option_index].name, "stream")) {
1361 traceStream = true;
1362 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001363 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1364 listSupportedCategories();
1365 exit(0);
1366 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001367 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001368
1369 default:
1370 fprintf(stderr, "\n");
1371 showHelp(argv[0]);
1372 exit(-1);
1373 break;
1374 }
1375 }
1376
Hector Dearman11845782018-03-08 14:35:44 +00001377 if (onlyUserspace) {
1378 if (!async || !(traceStart || traceStop)) {
1379 fprintf(stderr, "--only_userspace can only be used with "
1380 "--async_start or --async_stop\n");
1381 exit(1);
1382 }
1383 }
1384
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001385 registerSigHandler();
1386
1387 if (g_initialSleepSecs > 0) {
1388 sleep(g_initialSleepSecs);
1389 }
1390
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001391 bool ok = true;
Hector Dearman11845782018-03-08 14:35:44 +00001392
Wei Wang5b73b742018-03-08 13:33:12 -08001393 if (traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001394 ok &= setUpUserspaceTracing();
1395 }
1396
1397 if (ok && traceStart && !onlyUserspace) {
1398 ok &= setUpKernelTracing();
Wei Wang16a63a42018-09-21 15:47:45 -07001399 ok &= setUpVendorTracing();
Wei Wang5b73b742018-03-08 13:33:12 -08001400 ok &= startTrace();
1401 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001402
1403 if (ok && traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001404
1405 if (!traceStream && !onlyUserspace) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001406 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001407 fflush(stdout);
1408 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001409
1410 // We clear the trace after starting it because tracing gets enabled for
1411 // each CPU individually in the kernel. Having the beginning of the trace
1412 // contain entries from only one CPU can cause "begin" entries without a
1413 // matching "end" entry to show up if a task gets migrated from one CPU to
1414 // another.
Hector Dearman11845782018-03-08 14:35:44 +00001415 if (!onlyUserspace)
1416 ok = clearTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001417
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001418 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001419 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001420 // Sleep to allow the trace to be captured.
1421 struct timespec timeLeft;
1422 timeLeft.tv_sec = g_traceDurationSeconds;
1423 timeLeft.tv_nsec = 0;
1424 do {
1425 if (g_traceAborted) {
1426 break;
1427 }
1428 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1429 }
Martijn Coenend9535872015-11-26 10:00:55 +01001430
1431 if (traceStream) {
1432 streamTrace();
1433 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001434 }
1435
1436 // Stop the trace and restore the default settings.
Hector Dearman11845782018-03-08 14:35:44 +00001437 if (traceStop && !onlyUserspace)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001438 stopTrace();
1439
Hector Dearman11845782018-03-08 14:35:44 +00001440 if (ok && traceDump && !onlyUserspace) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001441 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001442 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001443 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001444 int outFd = STDOUT_FILENO;
1445 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001446 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001447 }
1448 if (outFd == -1) {
1449 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1450 } else {
1451 dprintf(outFd, "TRACE:\n");
1452 dumpTrace(outFd);
1453 if (g_outputFile) {
1454 close(outFd);
1455 }
1456 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001457 } else {
1458 printf("\ntrace aborted.\n");
1459 fflush(stdout);
1460 }
1461 clearTrace();
1462 } else if (!ok) {
1463 fprintf(stderr, "unable to start tracing\n");
1464 }
1465
1466 // Reset the trace buffer size to 1.
Hector Dearman11845782018-03-08 14:35:44 +00001467 if (traceStop) {
Wei Wang16a63a42018-09-21 15:47:45 -07001468 cleanUpVendorTracing();
Hector Dearman11845782018-03-08 14:35:44 +00001469 cleanUpUserspaceTracing();
1470 if (!onlyUserspace)
1471 cleanUpKernelTracing();
1472 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001473
1474 return g_traceAborted ? 1 : 0;
1475}