blob: 94dbebc4c09b73b34884f371c27a2945709dc874 [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
Martijn Coenenee9b97e2016-11-16 16:00:26 +010040#include <android/hidl/manager/1.0/IServiceManager.h>
41#include <hidl/ServiceManagement.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080042
Corey Tabakaa6c0a722017-05-31 16:37:40 -070043#include <pdx/default_transport/service_utility.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080044#include <utils/String8.h>
John Reck469a1942015-03-26 15:31:35 -070045#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +090046#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080047#include <utils/Trace.h>
Stephane Gasparinid8419c22016-03-02 13:45:15 +010048#include <android-base/file.h>
Elliott Hughes5fd6ff62017-03-28 14:55:31 -070049#include <android-base/macros.h>
50#include <android-base/properties.h>
51#include <android-base/stringprintf.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080052
53using namespace android;
Corey Tabakaa6c0a722017-05-31 16:37:40 -070054using pdx::default_transport::ServiceUtility;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080055
Martijn Coenenee9b97e2016-11-16 16:00:26 +010056using std::string;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080057
sergeyv4144eff2016-04-28 11:40:04 -070058#define MAX_SYS_FILES 10
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080059
60const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
Carmen Jackson65ecfbb2018-05-22 10:29:47 -070061const char* k_userInitiatedTraceProperty = "debug.atrace.user_initiated";
sergeyv4144eff2016-04-28 11:40:04 -070062
63const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
64const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070065const char* k_coreServiceCategory = "core_services";
Corey Tabakaa6c0a722017-05-31 16:37:40 -070066const char* k_pdxServiceCategory = "pdx";
sergeyvdb404152016-05-02 19:26:07 -070067const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080068
69typedef enum { OPT, REQ } requiredness ;
70
71struct TracingCategory {
72 // The name identifying the category.
73 const char* name;
74
75 // A longer description of the category.
76 const char* longname;
77
78 // The userland tracing tags that the category enables.
79 uint64_t tags;
80
81 // The fname==NULL terminated list of /sys/ files that the category
82 // enables.
83 struct {
84 // Whether the file must be writable in order to enable the tracing
85 // category.
86 requiredness required;
87
88 // The path to the enable file.
89 const char* path;
90 } sysfiles[MAX_SYS_FILES];
91};
92
93/* Tracing categories */
94static const TracingCategory k_categories[] = {
John Reck732a29a2017-05-24 16:09:21 -070095 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, {
96 { OPT, "events/mdss/enable" },
Wei Wangbcfb4872018-02-13 10:47:23 -080097 { OPT, "events/sde/enable" },
Jesse Hall5731aaa2018-07-27 12:01:08 -070098 { OPT, "events/mali_systrace/enable" },
John Reck732a29a2017-05-24 16:09:21 -070099 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700100 { "input", "Input", ATRACE_TAG_INPUT, { } },
101 { "view", "View System", ATRACE_TAG_VIEW, { } },
102 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
103 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
104 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -0500105 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700106 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
107 { "video", "Video", ATRACE_TAG_VIDEO, { } },
108 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
109 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -0700110 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -0700111 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -0700112 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -0700113 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700114 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 14:36:20 -0700115 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-07-01 01:46:25 +0900116 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Greg Hackmannbbd7d992014-12-01 14:43:34 -0800117 { "database", "Database", ATRACE_TAG_DATABASE, { } },
Felipe Leme0f97c1d2016-09-07 11:33:26 -0700118 { "network", "Network", ATRACE_TAG_NETWORK, { } },
Josh Gao468b4cb2016-11-29 10:55:21 -0800119 { "adb", "ADB", ATRACE_TAG_ADB, { } },
Martijn Coenen42f2ab42018-03-09 09:27:32 +0100120 { "vibrator", "Vibrator", ATRACE_TAG_VIBRATOR, { } },
121 { "aidl", "AIDL calls", ATRACE_TAG_AIDL, { } },
Mika Raentob363cf52018-04-23 22:09:13 +0100122 { "nnapi", "NNAPI", ATRACE_TAG_NNAPI, { } },
sergeyvdb404152016-05-02 19:26:07 -0700123 { k_coreServiceCategory, "Core services", 0, { } },
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700124 { k_pdxServiceCategory, "PDX services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700125 { "sched", "CPU Scheduling", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800126 { REQ, "events/sched/sched_switch/enable" },
127 { REQ, "events/sched/sched_wakeup/enable" },
Joel Fernandesee593e22017-06-04 13:05:59 -0700128 { OPT, "events/sched/sched_waking/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800129 { OPT, "events/sched/sched_blocked_reason/enable" },
130 { OPT, "events/sched/sched_cpu_hotplug/enable" },
Wei Wangca49dfc2018-05-03 15:45:20 -0700131 { OPT, "events/sched/sched_pi_setprio/enable" },
Joel Fernandes4dfca7c2017-06-15 16:53:52 -0700132 { OPT, "events/cgroup/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800133 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700134 { "irq", "IRQ Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800135 { REQ, "events/irq/enable" },
136 { OPT, "events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700137 } },
Joel Fernandes6ccad102017-08-31 08:35:05 -0700138 { "irqoff", "IRQ-disabled code section tracing", 0, {
139 { REQ, "events/preemptirq/irq_enable/enable" },
140 { REQ, "events/preemptirq/irq_disable/enable" },
141 } },
142 { "preemptoff", "Preempt-disabled code section tracing", 0, {
143 { REQ, "events/preemptirq/preempt_enable/enable" },
144 { REQ, "events/preemptirq/preempt_disable/enable" },
145 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100146 { "i2c", "I2C Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800147 { REQ, "events/i2c/enable" },
148 { REQ, "events/i2c/i2c_read/enable" },
149 { REQ, "events/i2c/i2c_write/enable" },
150 { REQ, "events/i2c/i2c_result/enable" },
151 { REQ, "events/i2c/i2c_reply/enable" },
152 { OPT, "events/i2c/smbus_read/enable" },
153 { OPT, "events/i2c/smbus_write/enable" },
154 { OPT, "events/i2c/smbus_result/enable" },
155 { OPT, "events/i2c/smbus_reply/enable" },
Michael Wright43fb6782016-08-18 19:56:43 +0100156 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700157 { "freq", "CPU Frequency", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800158 { REQ, "events/power/cpu_frequency/enable" },
159 { OPT, "events/power/clock_set_rate/enable" },
Kevin DuBois062e0b92017-11-03 15:44:08 -0700160 { OPT, "events/power/clock_disable/enable" },
161 { OPT, "events/power/clock_enable/enable" },
Wei Wang53305dd2018-02-22 11:40:07 -0800162 { OPT, "events/clk/clk_set_rate/enable" },
163 { OPT, "events/clk/clk_disable/enable" },
164 { OPT, "events/clk/clk_enable/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800165 { OPT, "events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800166 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700167 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800168 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800169 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700170 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800171 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800172 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700173 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800174 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
175 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
176 { OPT, "events/f2fs/f2fs_write_begin/enable" },
177 { OPT, "events/f2fs/f2fs_write_end/enable" },
178 { OPT, "events/ext4/ext4_da_write_begin/enable" },
179 { OPT, "events/ext4/ext4_da_write_end/enable" },
180 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
181 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
182 { REQ, "events/block/block_rq_issue/enable" },
183 { REQ, "events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800184 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700185 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800186 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700187 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700188 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800189 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800190 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700191 { "sync", "Synchronization", 0, {
Jesse Hallae001a32018-05-15 12:02:15 -0700192 // before linux kernel 4.9
193 { OPT, "events/sync/enable" },
194 // starting in linux kernel 4.9
195 { OPT, "events/fence/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800196 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700197 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800198 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800199 } },
Colin Cross580407f2014-08-18 15:22:13 -0700200 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800201 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
202 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
203 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
204 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Carmen Jackson7a23eb72018-07-02 13:14:56 -0700205 { OPT, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700206 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800207 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800208 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800209 } },
Scott Bauerae473362015-06-08 16:32:36 -0700210 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800211 { REQ, "events/binder/binder_transaction/enable" },
212 { REQ, "events/binder/binder_transaction_received/enable" },
Mika Raento80c3e5d2018-06-25 16:47:24 +0100213 { REQ, "events/binder/binder_transaction_alloc_buf/enable" },
Martijn Coenen7f3d7a22017-05-26 09:50:55 -0700214 { OPT, "events/binder/binder_set_priority/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700215 } },
216 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800217 { OPT, "events/binder/binder_lock/enable" },
218 { OPT, "events/binder/binder_locked/enable" },
219 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700220 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200221 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800222 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200223 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800224};
225
226/* Command line options */
227static int g_traceDurationSeconds = 5;
228static bool g_traceOverwrite = false;
229static int g_traceBufferSizeKB = 2048;
230static bool g_compress = false;
231static bool g_nohup = false;
232static int g_initialSleepSecs = 0;
Yi Kong19d5c002018-07-20 13:39:55 -0700233static const char* g_categoriesFile = nullptr;
234static const char* g_kernelTraceFuncs = nullptr;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700235static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700236static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800237
238/* Global state */
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700239static bool g_tracePdx = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800240static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700241static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800242static std::string g_traceFolder;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800243
244/* Sys file paths */
245static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800246 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800247
248static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800249 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800250
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700251#if 0
252// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700253static const char* k_traceCmdlineSizePath =
254 "saved_cmdlines_size";
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700255#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700256
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800257static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800258 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800259
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700260static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800261 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700262
263static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800264 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700265
John Recke757b1c2018-06-28 12:24:33 -0700266static const char* k_recordTgidPath =
267 "options/record-tgid";
268
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700269static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800270 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700271
272static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800273 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700274
275static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800276 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700277
278static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800279 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700280
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700281static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800282 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700283
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800284static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800285 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800286
287static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800288 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800289
Martijn Coenend9535872015-11-26 10:00:55 +0100290static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800291 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100292
John Reck469a1942015-03-26 15:31:35 -0700293static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800294 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700295
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800296// Check whether a file exists.
297static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800298 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800299}
300
301// Check whether a file is writable.
302static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800303 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800304}
305
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700306// Truncate a file.
307static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800308{
Jamie Gennis43122e72013-03-21 14:06:31 -0700309 // This uses creat rather than truncate because some of the debug kernel
310 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
311 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800312 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700313 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800314 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700315 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700316 return false;
317 }
318
Jamie Gennis43122e72013-03-21 14:06:31 -0700319 close(traceFD);
320
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700321 return true;
322}
323
324static bool _writeStr(const char* filename, const char* str, int flags)
325{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800326 std::string fullFilename = g_traceFolder + filename;
327 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800328 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800329 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800330 strerror(errno), errno);
331 return false;
332 }
333
334 bool ok = true;
335 ssize_t len = strlen(str);
336 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800337 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800338 strerror(errno), errno);
339 ok = false;
340 }
341
342 close(fd);
343
344 return ok;
345}
346
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700347// Write a string to a file, returning true if the write was successful.
348static bool writeStr(const char* filename, const char* str)
349{
350 return _writeStr(filename, str, O_WRONLY);
351}
352
353// Append a string to a file, returning true if the write was successful.
354static bool appendStr(const char* filename, const char* str)
355{
356 return _writeStr(filename, str, O_APPEND|O_WRONLY);
357}
358
John Reck469a1942015-03-26 15:31:35 -0700359static void writeClockSyncMarker()
360{
361 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200362 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800363 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200364 if (fd == -1) {
365 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
366 strerror(errno), errno);
367 return;
368 }
John Reck469a1942015-03-26 15:31:35 -0700369 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200370
371 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
372 if (write(fd, buffer, len) != len) {
373 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
374 }
375
376 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
377 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
378 if (write(fd, buffer, len) != len) {
379 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
380 }
381
382 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700383}
384
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800385// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
386// file.
387static bool setKernelOptionEnable(const char* filename, bool enable)
388{
389 return writeStr(filename, enable ? "1" : "0");
390}
391
392// Check whether the category is supported on the device with the current
393// rootness. A category is supported only if all its required /sys/ files are
394// writable and if enabling the category will enable one or more tracing tags
395// or /sys/ files.
396static bool isCategorySupported(const TracingCategory& category)
397{
sergeyvdb404152016-05-02 19:26:07 -0700398 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700399 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700400 }
401
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700402 if (strcmp(category.name, k_pdxServiceCategory) == 0) {
403 return true;
404 }
405
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800406 bool ok = category.tags != 0;
407 for (int i = 0; i < MAX_SYS_FILES; i++) {
408 const char* path = category.sysfiles[i].path;
409 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700410 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800411 if (req) {
412 if (!fileIsWritable(path)) {
413 return false;
414 } else {
415 ok = true;
416 }
417 } else {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800418 ok = true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800419 }
420 }
421 }
422 return ok;
423}
424
425// Check whether the category would be supported on the device if the user
426// were root. This function assumes that root is able to write to any file
427// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700428// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800429static bool isCategorySupportedForRoot(const TracingCategory& category)
430{
431 bool ok = category.tags != 0;
432 for (int i = 0; i < MAX_SYS_FILES; i++) {
433 const char* path = category.sysfiles[i].path;
434 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700435 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800436 if (req) {
437 if (!fileExists(path)) {
438 return false;
439 } else {
440 ok = true;
441 }
442 } else {
443 ok |= fileExists(path);
444 }
445 }
446 }
447 return ok;
448}
449
450// Enable or disable overwriting of the kernel trace buffers. Disabling this
451// will cause tracing to stop once the trace buffers have filled up.
452static bool setTraceOverwriteEnable(bool enable)
453{
454 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
455}
456
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700457// Set the user initiated trace property
458static bool setUserInitiatedTraceProperty(bool enable)
459{
460 if (!android::base::SetProperty(k_userInitiatedTraceProperty, enable ? "1" : "")) {
461 fprintf(stderr, "error setting user initiated strace system property\n");
462 return false;
463 }
464 return true;
465}
466
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800467// Enable or disable kernel tracing.
468static bool setTracingEnabled(bool enable)
469{
470 return setKernelOptionEnable(k_tracingOnPath, enable);
471}
472
473// Clear the contents of the kernel trace.
474static bool clearTrace()
475{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700476 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800477}
478
479// Set the size of the kernel's trace buffer in kilobytes.
480static bool setTraceBufferSizeKB(int size)
481{
482 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800483 if (size < 1) {
484 size = 1;
485 }
486 snprintf(str, 32, "%d", size);
487 return writeStr(k_traceBufferSizePath, str);
488}
489
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700490#if 0
491// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700492// Set the default size of cmdline hashtable
493static bool setCmdlineSize()
494{
Joel Fernandesce964f22017-06-06 12:20:29 -0700495 if (fileExists(k_traceCmdlineSizePath)) {
496 return writeStr(k_traceCmdlineSizePath, "8192");
497 }
498 return true;
Joel Fernandesed80bd02017-06-02 10:19:28 -0700499}
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700500#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700501
Carmen Jacksonea826792017-05-05 11:42:32 -0700502// Set the clock to the best available option while tracing. Use 'boot' if it's
503// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700504// Any write to the trace_clock sysfs file will reset the buffer, so only
505// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700506static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800507{
Carmen Jacksonea826792017-05-05 11:42:32 -0700508 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
509 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
510 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700511
Carmen Jacksonea826792017-05-05 11:42:32 -0700512 std::string newClock;
513 if (clockStr.find("boot") != std::string::npos) {
514 newClock = "boot";
515 } else if (clockStr.find("mono") != std::string::npos) {
516 newClock = "mono";
517 } else {
518 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700519 }
520
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700521 size_t begin = clockStr.find('[') + 1;
522 size_t end = clockStr.find(']');
Carmen Jacksonea826792017-05-05 11:42:32 -0700523 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
524 return true;
525 }
526 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800527}
528
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700529static bool setPrintTgidEnableIfPresent(bool enable)
530{
John Reckedbf9ec2018-06-29 11:15:17 -0700531 // Pre-4.13 this was options/print-tgid as an android-specific option.
532 // In 4.13+ this is an upstream option called options/record-tgid
533 // Both options produce the same ftrace format change
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700534 if (fileExists(k_printTgidPath)) {
535 return setKernelOptionEnable(k_printTgidPath, enable);
536 }
John Recke757b1c2018-06-28 12:24:33 -0700537 if (fileExists(k_recordTgidPath)) {
538 return setKernelOptionEnable(k_recordTgidPath, enable);
539 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700540 return true;
541}
542
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800543// Poke all the binder-enabled processes in the system to get them to re-read
544// their system properties.
545static bool pokeBinderServices()
546{
547 sp<IServiceManager> sm = defaultServiceManager();
548 Vector<String16> services = sm->listServices();
549 for (size_t i = 0; i < services.size(); i++) {
550 sp<IBinder> obj = sm->checkService(services[i]);
Yi Kong19d5c002018-07-20 13:39:55 -0700551 if (obj != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800552 Parcel data;
553 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
Yi Kong19d5c002018-07-20 13:39:55 -0700554 nullptr, 0) != OK) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800555 if (false) {
556 // XXX: For some reason this fails on tablets trying to
557 // poke the "phone" service. It's not clear whether some
558 // are expected to fail.
559 String8 svc(services[i]);
560 fprintf(stderr, "error poking binder service %s\n",
561 svc.string());
562 return false;
563 }
564 }
565 }
566 }
567 return true;
568}
569
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100570// Poke all the HAL processes in the system to get them to re-read
571// their system properties.
572static void pokeHalServices()
573{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100574 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100575 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100576 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100577 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100578
579 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800580
581 if (sm == nullptr) {
582 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
583 return;
584 }
585
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800586 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100587 for (size_t i = 0; i < interfaces.size(); i++) {
588 string fqInstanceName = interfaces[i];
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700589 string::size_type n = fqInstanceName.find('/');
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100590 if (n == std::string::npos || interfaces[i].size() == n+1)
591 continue;
592 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
593 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100594 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
595 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100596 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100597 continue;
598 }
Carmen Jackson73206122017-04-18 15:37:57 -0700599
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100600 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700601 if (interface == nullptr) {
602 // ignore
603 continue;
604 }
605
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100606 auto notifyRet = interface->notifySyspropsChanged();
607 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100608 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800609 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100610 }
611 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800612 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100613 // TODO(b/34242478) fix this when we determine the correct ACL
614 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800615 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100616}
617
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800618// Set the trace tags that userland tracing uses, and poke the running
619// processes to pick up the new value.
620static bool setTagsProperty(uint64_t tags)
621{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700622 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
623 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800624 fprintf(stderr, "error setting trace tags system property\n");
625 return false;
626 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700627 return true;
628}
629
sergeyv4144eff2016-04-28 11:40:04 -0700630static void clearAppProperties()
631{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700632 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700633 fprintf(stderr, "failed to clear system property: %s",
634 k_traceAppsNumberProperty);
635 }
636}
637
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700638// Set the system property that indicates which apps should perform
639// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700640static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700641{
sergeyv4144eff2016-04-28 11:40:04 -0700642 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700643 char* start = cmdline;
Yi Kong19d5c002018-07-20 13:39:55 -0700644 while (start != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700645 char* end = strchr(start, ',');
Yi Kong19d5c002018-07-20 13:39:55 -0700646 if (end != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700647 *end = '\0';
648 end++;
649 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700650 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
651 if (!android::base::SetProperty(key, start)) {
652 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700653 clearAppProperties();
654 return false;
655 }
656 start = end;
657 i++;
658 }
659
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700660 std::string value = android::base::StringPrintf("%d", i);
661 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
662 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700663 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700664 return false;
665 }
666 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800667}
668
669// Disable all /sys/ enable files.
670static bool disableKernelTraceEvents() {
671 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700672 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800673 const TracingCategory &c = k_categories[i];
674 for (int j = 0; j < MAX_SYS_FILES; j++) {
675 const char* path = c.sysfiles[j].path;
Yi Kong19d5c002018-07-20 13:39:55 -0700676 if (path != nullptr && fileIsWritable(path)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800677 ok &= setKernelOptionEnable(path, false);
678 }
679 }
680 }
681 return ok;
682}
683
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700684// Verify that the comma separated list of functions are being traced by the
685// kernel.
686static bool verifyKernelTraceFuncs(const char* funcs)
687{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100688 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800689 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100690 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700691 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100692 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700693 }
694
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100695 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700696
697 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100698 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700699 bool ok = true;
700 char* myFuncs = strdup(funcs);
701 char* func = strtok(myFuncs, ",");
702 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100703 if (!strchr(func, '*')) {
704 String8 fancyFunc = String8::format("\n%s\n", func);
705 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
706 if (!found || func[0] == '\0') {
707 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
708 "to trace.\n", func);
709 ok = false;
710 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700711 }
Yi Kong19d5c002018-07-20 13:39:55 -0700712 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700713 }
714 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700715 return ok;
716}
717
718// Set the comma separated list of functions that the kernel is to trace.
719static bool setKernelTraceFuncs(const char* funcs)
720{
721 bool ok = true;
722
Yi Kong19d5c002018-07-20 13:39:55 -0700723 if (funcs == nullptr || funcs[0] == '\0') {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700724 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700725 if (fileIsWritable(k_currentTracerPath)) {
726 ok &= writeStr(k_currentTracerPath, "nop");
727 }
728 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700729 ok &= truncateFile(k_ftraceFilterPath);
730 }
731 } else {
732 // Enable kernel function tracing.
733 ok &= writeStr(k_currentTracerPath, "function_graph");
734 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
735 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
736 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
737 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
738
739 // Set the requested filter functions.
740 ok &= truncateFile(k_ftraceFilterPath);
741 char* myFuncs = strdup(funcs);
742 char* func = strtok(myFuncs, ",");
743 while (func) {
744 ok &= appendStr(k_ftraceFilterPath, func);
Yi Kong19d5c002018-07-20 13:39:55 -0700745 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700746 }
747 free(myFuncs);
748
749 // Verify that the set functions are being traced.
750 if (ok) {
751 ok &= verifyKernelTraceFuncs(funcs);
752 }
753 }
754
755 return ok;
756}
757
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900758static bool setCategoryEnable(const char* name, bool enable)
759{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700760 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900761 const TracingCategory& c = k_categories[i];
762 if (strcmp(name, c.name) == 0) {
763 if (isCategorySupported(c)) {
764 g_categoryEnables[i] = enable;
765 return true;
766 } else {
767 if (isCategorySupportedForRoot(c)) {
768 fprintf(stderr, "error: category \"%s\" requires root "
769 "privileges.\n", name);
770 } else {
771 fprintf(stderr, "error: category \"%s\" is not supported "
772 "on this device.\n", name);
773 }
774 return false;
775 }
776 }
777 }
778 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
779 return false;
780}
781
782static bool setCategoriesEnableFromFile(const char* categories_file)
783{
784 if (!categories_file) {
785 return true;
786 }
Yi Kong19d5c002018-07-20 13:39:55 -0700787 Tokenizer* tokenizer = nullptr;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900788 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
789 return false;
790 }
791 bool ok = true;
792 while (!tokenizer->isEol()) {
793 String8 token = tokenizer->nextToken(" ");
794 if (token.isEmpty()) {
795 tokenizer->skipDelimiters(" ");
796 continue;
797 }
798 ok &= setCategoryEnable(token.string(), true);
799 }
800 delete tokenizer;
801 return ok;
802}
803
Hector Dearman11845782018-03-08 14:35:44 +0000804static bool setUpUserspaceTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800805{
806 bool ok = true;
807
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800808 // Set up the tags property.
809 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700810 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800811 if (g_categoryEnables[i]) {
812 const TracingCategory &c = k_categories[i];
813 tags |= c.tags;
814 }
815 }
816 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700817
818 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700819 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700820 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
821 coreServicesTagEnabled = g_categoryEnables[i];
822 }
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700823
824 // Set whether to poke PDX services in this session.
825 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
826 g_tracePdx = g_categoryEnables[i];
827 }
sergeyvdb404152016-05-02 19:26:07 -0700828 }
829
830 std::string packageList(g_debugAppCmdLine);
831 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700832 if (!packageList.empty()) {
833 packageList += ",";
834 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700835 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700836 }
Dan Austin09a79872016-05-31 13:27:03 -0700837 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700838 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100839 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800840
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700841 if (g_tracePdx) {
842 ok &= ServiceUtility::PokeServices();
843 }
844
Hector Dearman11845782018-03-08 14:35:44 +0000845 return ok;
846}
847
848static void cleanUpUserspaceTracing()
849{
850 setTagsProperty(0);
851 clearAppProperties();
852 pokeBinderServices();
853
854 if (g_tracePdx) {
855 ServiceUtility::PokeServices();
856 }
857}
858
859
860// Set all the kernel tracing settings to the desired state for this trace
861// capture.
862static bool setUpKernelTracing()
863{
864 bool ok = true;
865
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700866 ok &= setUserInitiatedTraceProperty(true);
867
Hector Dearman11845782018-03-08 14:35:44 +0000868 // Set up the tracing options.
869 ok &= setCategoriesEnableFromFile(g_categoriesFile);
870 ok &= setTraceOverwriteEnable(g_traceOverwrite);
871 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
872 // TODO: Re-enable after stabilization
873 //ok &= setCmdlineSize();
874 ok &= setClock();
875 ok &= setPrintTgidEnableIfPresent(true);
876 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
877
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800878 // Disable all the sysfs enables. This is done as a separate loop from
879 // the enables to allow the same enable to exist in multiple categories.
880 ok &= disableKernelTraceEvents();
881
882 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700883 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800884 if (g_categoryEnables[i]) {
885 const TracingCategory &c = k_categories[i];
886 for (int j = 0; j < MAX_SYS_FILES; j++) {
887 const char* path = c.sysfiles[j].path;
888 bool required = c.sysfiles[j].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700889 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800890 if (fileIsWritable(path)) {
891 ok &= setKernelOptionEnable(path, true);
892 } else if (required) {
893 fprintf(stderr, "error writing file %s\n", path);
894 ok = false;
895 }
896 }
897 }
898 }
899 }
900
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800901 return ok;
902}
903
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700904// Reset all the kernel tracing settings to their default state.
Hector Dearman11845782018-03-08 14:35:44 +0000905static void cleanUpKernelTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800906{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800907 // Disable all tracing that we're able to.
908 disableKernelTraceEvents();
909
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800910 // Set the options back to their defaults.
911 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700912 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700913 setPrintTgidEnableIfPresent(false);
Yi Kong19d5c002018-07-20 13:39:55 -0700914 setKernelTraceFuncs(nullptr);
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700915 setUserInitiatedTraceProperty(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700916}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800917
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700918// Enable tracing in the kernel.
919static bool startTrace()
920{
921 return setTracingEnabled(true);
922}
923
924// Disable tracing in the kernel.
925static void stopTrace()
926{
927 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800928}
929
Martijn Coenend9535872015-11-26 10:00:55 +0100930// Read data from the tracing pipe and forward to stdout
931static void streamTrace()
932{
933 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800934 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100935 if (traceFD == -1) {
936 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
937 strerror(errno), errno);
938 return;
939 }
940 while (!g_traceAborted) {
941 ssize_t bytes_read = read(traceFD, trace_data, 4096);
942 if (bytes_read > 0) {
943 write(STDOUT_FILENO, trace_data, bytes_read);
944 fflush(stdout);
945 } else {
946 if (!g_traceAborted) {
947 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
948 bytes_read, errno, strerror(errno));
949 }
950 break;
951 }
952 }
953}
954
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800955// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700956static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800957{
John Reck6c8ac922016-03-28 11:25:30 -0700958 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800959 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800960 if (traceFD == -1) {
961 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
962 strerror(errno), errno);
963 return;
964 }
965
966 if (g_compress) {
967 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800968 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700969
970 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800971 if (result != Z_OK) {
972 fprintf(stderr, "error initializing zlib: %d\n", result);
973 close(traceFD);
974 return;
975 }
976
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700977 constexpr size_t bufSize = 64*1024;
978 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
979 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
980 if (!in || !out) {
981 fprintf(stderr, "couldn't allocate buffers\n");
982 close(traceFD);
983 return;
984 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800985
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700986 int flush = Z_NO_FLUSH;
987
988 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800989 zs.avail_out = bufSize;
990
991 do {
992
993 if (zs.avail_in == 0) {
994 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700995 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800996 if (result < 0) {
997 fprintf(stderr, "error reading trace: %s (%d)\n",
998 strerror(errno), errno);
999 result = Z_STREAM_END;
1000 break;
1001 } else if (result == 0) {
1002 flush = Z_FINISH;
1003 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001004 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001005 zs.avail_in = result;
1006 }
1007 }
1008
1009 if (zs.avail_out == 0) {
1010 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -07001011 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001012 if ((size_t)result < bufSize) {
1013 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1014 strerror(errno), errno);
1015 result = Z_STREAM_END; // skip deflate error message
1016 zs.avail_out = bufSize; // skip the final write
1017 break;
1018 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001019 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001020 zs.avail_out = bufSize;
1021 }
1022
1023 } while ((result = deflate(&zs, flush)) == Z_OK);
1024
1025 if (result != Z_STREAM_END) {
1026 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
1027 }
1028
1029 if (zs.avail_out < bufSize) {
1030 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -07001031 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001032 if ((size_t)result < bytes) {
1033 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1034 strerror(errno), errno);
1035 }
1036 }
1037
1038 result = deflateEnd(&zs);
1039 if (result != Z_OK) {
1040 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1041 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001042 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001043 char buf[4096];
1044 ssize_t rc;
1045 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1046 if (!android::base::WriteFully(outFd, buf, rc)) {
1047 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1048 break;
1049 }
1050 }
1051 if (rc == -1) {
1052 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001053 }
1054 }
1055
1056 close(traceFD);
1057}
1058
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001059static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001060{
1061 if (!g_nohup) {
1062 g_traceAborted = true;
1063 }
1064}
1065
1066static void registerSigHandler()
1067{
1068 struct sigaction sa;
1069 sigemptyset(&sa.sa_mask);
1070 sa.sa_flags = 0;
1071 sa.sa_handler = handleSignal;
Yi Kong19d5c002018-07-20 13:39:55 -07001072 sigaction(SIGHUP, &sa, nullptr);
1073 sigaction(SIGINT, &sa, nullptr);
1074 sigaction(SIGQUIT, &sa, nullptr);
1075 sigaction(SIGTERM, &sa, nullptr);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001076}
1077
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001078static void listSupportedCategories()
1079{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001080 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001081 const TracingCategory& c = k_categories[i];
1082 if (isCategorySupported(c)) {
1083 printf(" %10s - %s\n", c.name, c.longname);
1084 }
1085 }
1086}
1087
1088// Print the command usage help to stderr.
1089static void showHelp(const char *cmd)
1090{
1091 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1092 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001093 " -a appname enable app-level tracing for a comma "
Daniel Colascione519a0792018-02-09 20:05:39 -08001094 "separated list of cmdlines; * is a wildcard matching any process\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001095 " -b N use a trace buffer size of N KB\n"
1096 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001097 " -f filename use the categories written in a file as space-separated\n"
1098 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001099 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001100 " -n ignore signals\n"
1101 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001102 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001103 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001104 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001105 " --async_dump dump the current contents of circular trace buffer\n"
1106 " --async_stop stop tracing and dump the current contents of circular\n"
1107 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001108 " --stream stream trace to stdout as it enters the trace buffer\n"
1109 " Note: this can take significant CPU time, and is best\n"
1110 " used for measuring things that are not affected by\n"
1111 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001112 " --list_categories\n"
1113 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001114 " -o filename write the trace to the specified file instead\n"
1115 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001116 );
1117}
1118
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001119bool findTraceFiles()
1120{
1121 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1122 static const std::string tracefs_path = "/sys/kernel/tracing/";
1123 static const std::string trace_file = "trace_marker";
1124
1125 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1126 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1127
1128 if (!tracefs && !debugfs) {
1129 fprintf(stderr, "Error: Did not find trace folder\n");
1130 return false;
1131 }
1132
1133 if (tracefs) {
1134 g_traceFolder = tracefs_path;
1135 } else {
1136 g_traceFolder = debugfs_path;
1137 }
1138
1139 return true;
1140}
1141
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001142int main(int argc, char **argv)
1143{
1144 bool async = false;
1145 bool traceStart = true;
1146 bool traceStop = true;
1147 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001148 bool traceStream = false;
Hector Dearman11845782018-03-08 14:35:44 +00001149 bool onlyUserspace = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001150
1151 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1152 showHelp(argv[0]);
1153 exit(0);
1154 }
1155
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001156 if (!findTraceFiles()) {
1157 fprintf(stderr, "No trace folder found\n");
1158 exit(-1);
1159 }
1160
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001161 for (;;) {
1162 int ret;
1163 int option_index = 0;
1164 static struct option long_options[] = {
Yi Kong19d5c002018-07-20 13:39:55 -07001165 {"async_start", no_argument, nullptr, 0 },
1166 {"async_stop", no_argument, nullptr, 0 },
1167 {"async_dump", no_argument, nullptr, 0 },
1168 {"only_userspace", no_argument, nullptr, 0 },
1169 {"list_categories", no_argument, nullptr, 0 },
1170 {"stream", no_argument, nullptr, 0 },
1171 {nullptr, 0, nullptr, 0 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001172 };
1173
John Reck40b26b42016-03-30 09:44:36 -07001174 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001175 long_options, &option_index);
1176
1177 if (ret < 0) {
1178 for (int i = optind; i < argc; i++) {
1179 if (!setCategoryEnable(argv[i], true)) {
1180 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1181 exit(1);
1182 }
1183 }
1184 break;
1185 }
1186
1187 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001188 case 'a':
1189 g_debugAppCmdLine = optarg;
1190 break;
1191
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001192 case 'b':
1193 g_traceBufferSizeKB = atoi(optarg);
1194 break;
1195
1196 case 'c':
1197 g_traceOverwrite = true;
1198 break;
1199
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001200 case 'f':
1201 g_categoriesFile = optarg;
1202 break;
1203
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001204 case 'k':
1205 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001206 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001207
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001208 case 'n':
1209 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001210 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001211
1212 case 's':
1213 g_initialSleepSecs = atoi(optarg);
1214 break;
1215
1216 case 't':
1217 g_traceDurationSeconds = atoi(optarg);
1218 break;
1219
1220 case 'z':
1221 g_compress = true;
1222 break;
1223
John Reck40b26b42016-03-30 09:44:36 -07001224 case 'o':
1225 g_outputFile = optarg;
1226 break;
1227
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001228 case 0:
1229 if (!strcmp(long_options[option_index].name, "async_start")) {
1230 async = true;
1231 traceStop = false;
1232 traceDump = false;
1233 g_traceOverwrite = true;
1234 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1235 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001236 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001237 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1238 async = true;
1239 traceStart = false;
1240 traceStop = false;
Hector Dearman11845782018-03-08 14:35:44 +00001241 } else if (!strcmp(long_options[option_index].name, "only_userspace")) {
1242 onlyUserspace = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001243 } else if (!strcmp(long_options[option_index].name, "stream")) {
1244 traceStream = true;
1245 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001246 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1247 listSupportedCategories();
1248 exit(0);
1249 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001250 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001251
1252 default:
1253 fprintf(stderr, "\n");
1254 showHelp(argv[0]);
1255 exit(-1);
1256 break;
1257 }
1258 }
1259
Hector Dearman11845782018-03-08 14:35:44 +00001260 if (onlyUserspace) {
1261 if (!async || !(traceStart || traceStop)) {
1262 fprintf(stderr, "--only_userspace can only be used with "
1263 "--async_start or --async_stop\n");
1264 exit(1);
1265 }
1266 }
1267
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001268 registerSigHandler();
1269
1270 if (g_initialSleepSecs > 0) {
1271 sleep(g_initialSleepSecs);
1272 }
1273
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001274 bool ok = true;
Hector Dearman11845782018-03-08 14:35:44 +00001275
Wei Wang5b73b742018-03-08 13:33:12 -08001276 if (traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001277 ok &= setUpUserspaceTracing();
1278 }
1279
1280 if (ok && traceStart && !onlyUserspace) {
1281 ok &= setUpKernelTracing();
Wei Wang5b73b742018-03-08 13:33:12 -08001282 ok &= startTrace();
1283 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001284
1285 if (ok && traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001286
1287 if (!traceStream && !onlyUserspace) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001288 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001289 fflush(stdout);
1290 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001291
1292 // We clear the trace after starting it because tracing gets enabled for
1293 // each CPU individually in the kernel. Having the beginning of the trace
1294 // contain entries from only one CPU can cause "begin" entries without a
1295 // matching "end" entry to show up if a task gets migrated from one CPU to
1296 // another.
Hector Dearman11845782018-03-08 14:35:44 +00001297 if (!onlyUserspace)
1298 ok = clearTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001299
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001300 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001301 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001302 // Sleep to allow the trace to be captured.
1303 struct timespec timeLeft;
1304 timeLeft.tv_sec = g_traceDurationSeconds;
1305 timeLeft.tv_nsec = 0;
1306 do {
1307 if (g_traceAborted) {
1308 break;
1309 }
1310 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1311 }
Martijn Coenend9535872015-11-26 10:00:55 +01001312
1313 if (traceStream) {
1314 streamTrace();
1315 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001316 }
1317
1318 // Stop the trace and restore the default settings.
Hector Dearman11845782018-03-08 14:35:44 +00001319 if (traceStop && !onlyUserspace)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001320 stopTrace();
1321
Hector Dearman11845782018-03-08 14:35:44 +00001322 if (ok && traceDump && !onlyUserspace) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001323 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001324 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001325 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001326 int outFd = STDOUT_FILENO;
1327 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001328 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001329 }
1330 if (outFd == -1) {
1331 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1332 } else {
1333 dprintf(outFd, "TRACE:\n");
1334 dumpTrace(outFd);
1335 if (g_outputFile) {
1336 close(outFd);
1337 }
1338 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001339 } else {
1340 printf("\ntrace aborted.\n");
1341 fflush(stdout);
1342 }
1343 clearTrace();
1344 } else if (!ok) {
1345 fprintf(stderr, "unable to start tracing\n");
1346 }
1347
1348 // Reset the trace buffer size to 1.
Hector Dearman11845782018-03-08 14:35:44 +00001349 if (traceStop) {
1350 cleanUpUserspaceTracing();
1351 if (!onlyUserspace)
1352 cleanUpKernelTracing();
1353 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001354
1355 return g_traceAborted ? 1 : 0;
1356}