blob: bce8b45cdbc1d3e498cec5e59f8e748784d9babb [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 Jacksonab1118e2018-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" },
John Reck732a29a2017-05-24 16:09:21 -070098 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070099 { "input", "Input", ATRACE_TAG_INPUT, { } },
100 { "view", "View System", ATRACE_TAG_VIEW, { } },
101 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
102 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
103 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -0500104 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700105 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
106 { "video", "Video", ATRACE_TAG_VIDEO, { } },
107 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
108 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -0700109 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -0700110 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -0700111 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -0700112 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700113 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 14:36:20 -0700114 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-07-01 01:46:25 +0900115 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Greg Hackmannbbd7d992014-12-01 14:43:34 -0800116 { "database", "Database", ATRACE_TAG_DATABASE, { } },
Felipe Leme0f97c1d2016-09-07 11:33:26 -0700117 { "network", "Network", ATRACE_TAG_NETWORK, { } },
Josh Gao468b4cb2016-11-29 10:55:21 -0800118 { "adb", "ADB", ATRACE_TAG_ADB, { } },
Martijn Coenen42f2ab42018-03-09 09:27:32 +0100119 { "vibrator", "Vibrator", ATRACE_TAG_VIBRATOR, { } },
120 { "aidl", "AIDL calls", ATRACE_TAG_AIDL, { } },
Mika Raentob363cf52018-04-23 22:09:13 +0100121 { "nnapi", "NNAPI", ATRACE_TAG_NNAPI, { } },
sergeyvdb404152016-05-02 19:26:07 -0700122 { k_coreServiceCategory, "Core services", 0, { } },
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700123 { k_pdxServiceCategory, "PDX services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700124 { "sched", "CPU Scheduling", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800125 { REQ, "events/sched/sched_switch/enable" },
126 { REQ, "events/sched/sched_wakeup/enable" },
Joel Fernandesee593e22017-06-04 13:05:59 -0700127 { OPT, "events/sched/sched_waking/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800128 { OPT, "events/sched/sched_blocked_reason/enable" },
129 { OPT, "events/sched/sched_cpu_hotplug/enable" },
Joel Fernandes4dfca7c2017-06-15 16:53:52 -0700130 { OPT, "events/cgroup/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800131 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700132 { "irq", "IRQ Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800133 { REQ, "events/irq/enable" },
134 { OPT, "events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700135 } },
Joel Fernandes6ccad102017-08-31 08:35:05 -0700136 { "irqoff", "IRQ-disabled code section tracing", 0, {
137 { REQ, "events/preemptirq/irq_enable/enable" },
138 { REQ, "events/preemptirq/irq_disable/enable" },
139 } },
140 { "preemptoff", "Preempt-disabled code section tracing", 0, {
141 { REQ, "events/preemptirq/preempt_enable/enable" },
142 { REQ, "events/preemptirq/preempt_disable/enable" },
143 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100144 { "i2c", "I2C Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800145 { REQ, "events/i2c/enable" },
146 { REQ, "events/i2c/i2c_read/enable" },
147 { REQ, "events/i2c/i2c_write/enable" },
148 { REQ, "events/i2c/i2c_result/enable" },
149 { REQ, "events/i2c/i2c_reply/enable" },
150 { OPT, "events/i2c/smbus_read/enable" },
151 { OPT, "events/i2c/smbus_write/enable" },
152 { OPT, "events/i2c/smbus_result/enable" },
153 { OPT, "events/i2c/smbus_reply/enable" },
Michael Wright43fb6782016-08-18 19:56:43 +0100154 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700155 { "freq", "CPU Frequency", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800156 { REQ, "events/power/cpu_frequency/enable" },
157 { OPT, "events/power/clock_set_rate/enable" },
Kevin DuBois062e0b92017-11-03 15:44:08 -0700158 { OPT, "events/power/clock_disable/enable" },
159 { OPT, "events/power/clock_enable/enable" },
Wei Wang53305dd2018-02-22 11:40:07 -0800160 { OPT, "events/clk/clk_set_rate/enable" },
161 { OPT, "events/clk/clk_disable/enable" },
162 { OPT, "events/clk/clk_enable/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800163 { OPT, "events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800164 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700165 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800166 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800167 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700168 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800169 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800170 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700171 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800172 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
173 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
174 { OPT, "events/f2fs/f2fs_write_begin/enable" },
175 { OPT, "events/f2fs/f2fs_write_end/enable" },
176 { OPT, "events/ext4/ext4_da_write_begin/enable" },
177 { OPT, "events/ext4/ext4_da_write_end/enable" },
178 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
179 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
180 { REQ, "events/block/block_rq_issue/enable" },
181 { REQ, "events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800182 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700183 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800184 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700185 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700186 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800187 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800188 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700189 { "sync", "Synchronization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800190 { REQ, "events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800191 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700192 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800193 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800194 } },
Colin Cross580407f2014-08-18 15:22:13 -0700195 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800196 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
197 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
198 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
199 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Marc Hittingerf1f62e32017-05-17 15:57:43 -0700200 { REQ, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700201 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800202 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800203 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800204 } },
Scott Bauerae473362015-06-08 16:32:36 -0700205 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800206 { REQ, "events/binder/binder_transaction/enable" },
207 { REQ, "events/binder/binder_transaction_received/enable" },
Mika Raento80c3e5d2018-06-25 16:47:24 +0100208 { REQ, "events/binder/binder_transaction_alloc_buf/enable" },
Martijn Coenen7f3d7a22017-05-26 09:50:55 -0700209 { OPT, "events/binder/binder_set_priority/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700210 } },
211 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800212 { OPT, "events/binder/binder_lock/enable" },
213 { OPT, "events/binder/binder_locked/enable" },
214 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700215 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200216 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800217 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200218 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800219};
220
221/* Command line options */
222static int g_traceDurationSeconds = 5;
223static bool g_traceOverwrite = false;
224static int g_traceBufferSizeKB = 2048;
225static bool g_compress = false;
226static bool g_nohup = false;
227static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900228static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700229static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700230static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700231static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800232
233/* Global state */
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700234static bool g_tracePdx = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800235static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700236static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800237static std::string g_traceFolder;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800238
239/* Sys file paths */
240static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800241 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800242
243static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800244 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800245
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700246#if 0
247// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700248static const char* k_traceCmdlineSizePath =
249 "saved_cmdlines_size";
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700250#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700251
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800252static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800253 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800254
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700255static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800256 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700257
258static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800259 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700260
261static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800262 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700263
264static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800265 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700266
267static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800268 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700269
270static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800271 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700272
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700273static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800274 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700275
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800276static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800277 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800278
279static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800280 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800281
Martijn Coenend9535872015-11-26 10:00:55 +0100282static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800283 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100284
John Reck469a1942015-03-26 15:31:35 -0700285static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800286 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700287
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800288// Check whether a file exists.
289static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800290 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800291}
292
293// Check whether a file is writable.
294static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800295 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800296}
297
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700298// Truncate a file.
299static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800300{
Jamie Gennis43122e72013-03-21 14:06:31 -0700301 // This uses creat rather than truncate because some of the debug kernel
302 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
303 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800304 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700305 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800306 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700307 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700308 return false;
309 }
310
Jamie Gennis43122e72013-03-21 14:06:31 -0700311 close(traceFD);
312
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700313 return true;
314}
315
316static bool _writeStr(const char* filename, const char* str, int flags)
317{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800318 std::string fullFilename = g_traceFolder + filename;
319 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800320 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800321 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800322 strerror(errno), errno);
323 return false;
324 }
325
326 bool ok = true;
327 ssize_t len = strlen(str);
328 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800329 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800330 strerror(errno), errno);
331 ok = false;
332 }
333
334 close(fd);
335
336 return ok;
337}
338
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700339// Write a string to a file, returning true if the write was successful.
340static bool writeStr(const char* filename, const char* str)
341{
342 return _writeStr(filename, str, O_WRONLY);
343}
344
345// Append a string to a file, returning true if the write was successful.
346static bool appendStr(const char* filename, const char* str)
347{
348 return _writeStr(filename, str, O_APPEND|O_WRONLY);
349}
350
John Reck469a1942015-03-26 15:31:35 -0700351static void writeClockSyncMarker()
352{
353 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200354 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800355 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200356 if (fd == -1) {
357 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
358 strerror(errno), errno);
359 return;
360 }
John Reck469a1942015-03-26 15:31:35 -0700361 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200362
363 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
364 if (write(fd, buffer, len) != len) {
365 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
366 }
367
368 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
369 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
370 if (write(fd, buffer, len) != len) {
371 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
372 }
373
374 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700375}
376
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800377// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
378// file.
379static bool setKernelOptionEnable(const char* filename, bool enable)
380{
381 return writeStr(filename, enable ? "1" : "0");
382}
383
384// Check whether the category is supported on the device with the current
385// rootness. A category is supported only if all its required /sys/ files are
386// writable and if enabling the category will enable one or more tracing tags
387// or /sys/ files.
388static bool isCategorySupported(const TracingCategory& category)
389{
sergeyvdb404152016-05-02 19:26:07 -0700390 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700391 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700392 }
393
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700394 if (strcmp(category.name, k_pdxServiceCategory) == 0) {
395 return true;
396 }
397
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800398 bool ok = category.tags != 0;
399 for (int i = 0; i < MAX_SYS_FILES; i++) {
400 const char* path = category.sysfiles[i].path;
401 bool req = category.sysfiles[i].required == REQ;
402 if (path != NULL) {
403 if (req) {
404 if (!fileIsWritable(path)) {
405 return false;
406 } else {
407 ok = true;
408 }
409 } else {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800410 ok = true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800411 }
412 }
413 }
414 return ok;
415}
416
417// Check whether the category would be supported on the device if the user
418// were root. This function assumes that root is able to write to any file
419// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700420// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800421static bool isCategorySupportedForRoot(const TracingCategory& category)
422{
423 bool ok = category.tags != 0;
424 for (int i = 0; i < MAX_SYS_FILES; i++) {
425 const char* path = category.sysfiles[i].path;
426 bool req = category.sysfiles[i].required == REQ;
427 if (path != NULL) {
428 if (req) {
429 if (!fileExists(path)) {
430 return false;
431 } else {
432 ok = true;
433 }
434 } else {
435 ok |= fileExists(path);
436 }
437 }
438 }
439 return ok;
440}
441
442// Enable or disable overwriting of the kernel trace buffers. Disabling this
443// will cause tracing to stop once the trace buffers have filled up.
444static bool setTraceOverwriteEnable(bool enable)
445{
446 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
447}
448
Carmen Jacksonab1118e2018-05-22 10:29:47 -0700449// Set the user initiated trace property
450static bool setUserInitiatedTraceProperty(bool enable)
451{
452 if (!android::base::SetProperty(k_userInitiatedTraceProperty, enable ? "1" : "")) {
453 fprintf(stderr, "error setting user initiated strace system property\n");
454 return false;
455 }
456 return true;
457}
458
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800459// Enable or disable kernel tracing.
460static bool setTracingEnabled(bool enable)
461{
462 return setKernelOptionEnable(k_tracingOnPath, enable);
463}
464
465// Clear the contents of the kernel trace.
466static bool clearTrace()
467{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700468 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800469}
470
471// Set the size of the kernel's trace buffer in kilobytes.
472static bool setTraceBufferSizeKB(int size)
473{
474 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800475 if (size < 1) {
476 size = 1;
477 }
478 snprintf(str, 32, "%d", size);
479 return writeStr(k_traceBufferSizePath, str);
480}
481
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700482#if 0
483// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700484// Set the default size of cmdline hashtable
485static bool setCmdlineSize()
486{
Joel Fernandesce964f22017-06-06 12:20:29 -0700487 if (fileExists(k_traceCmdlineSizePath)) {
488 return writeStr(k_traceCmdlineSizePath, "8192");
489 }
490 return true;
Joel Fernandesed80bd02017-06-02 10:19:28 -0700491}
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700492#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700493
Carmen Jacksonea826792017-05-05 11:42:32 -0700494// Set the clock to the best available option while tracing. Use 'boot' if it's
495// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700496// Any write to the trace_clock sysfs file will reset the buffer, so only
497// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700498static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800499{
Carmen Jacksonea826792017-05-05 11:42:32 -0700500 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
501 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
502 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700503
Carmen Jacksonea826792017-05-05 11:42:32 -0700504 std::string newClock;
505 if (clockStr.find("boot") != std::string::npos) {
506 newClock = "boot";
507 } else if (clockStr.find("mono") != std::string::npos) {
508 newClock = "mono";
509 } else {
510 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700511 }
512
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700513 size_t begin = clockStr.find('[') + 1;
514 size_t end = clockStr.find(']');
Carmen Jacksonea826792017-05-05 11:42:32 -0700515 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
516 return true;
517 }
518 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800519}
520
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700521static bool setPrintTgidEnableIfPresent(bool enable)
522{
523 if (fileExists(k_printTgidPath)) {
524 return setKernelOptionEnable(k_printTgidPath, enable);
525 }
526 return true;
527}
528
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800529// Poke all the binder-enabled processes in the system to get them to re-read
530// their system properties.
531static bool pokeBinderServices()
532{
533 sp<IServiceManager> sm = defaultServiceManager();
534 Vector<String16> services = sm->listServices();
535 for (size_t i = 0; i < services.size(); i++) {
536 sp<IBinder> obj = sm->checkService(services[i]);
537 if (obj != NULL) {
538 Parcel data;
539 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
540 NULL, 0) != OK) {
541 if (false) {
542 // XXX: For some reason this fails on tablets trying to
543 // poke the "phone" service. It's not clear whether some
544 // are expected to fail.
545 String8 svc(services[i]);
546 fprintf(stderr, "error poking binder service %s\n",
547 svc.string());
548 return false;
549 }
550 }
551 }
552 }
553 return true;
554}
555
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100556// Poke all the HAL processes in the system to get them to re-read
557// their system properties.
558static void pokeHalServices()
559{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100560 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100561 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100562 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100563 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100564
565 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800566
567 if (sm == nullptr) {
568 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
569 return;
570 }
571
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800572 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100573 for (size_t i = 0; i < interfaces.size(); i++) {
574 string fqInstanceName = interfaces[i];
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700575 string::size_type n = fqInstanceName.find('/');
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100576 if (n == std::string::npos || interfaces[i].size() == n+1)
577 continue;
578 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
579 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100580 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
581 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100582 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100583 continue;
584 }
Carmen Jackson73206122017-04-18 15:37:57 -0700585
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100586 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700587 if (interface == nullptr) {
588 // ignore
589 continue;
590 }
591
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100592 auto notifyRet = interface->notifySyspropsChanged();
593 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100594 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800595 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100596 }
597 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800598 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100599 // TODO(b/34242478) fix this when we determine the correct ACL
600 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800601 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100602}
603
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800604// Set the trace tags that userland tracing uses, and poke the running
605// processes to pick up the new value.
606static bool setTagsProperty(uint64_t tags)
607{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700608 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
609 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800610 fprintf(stderr, "error setting trace tags system property\n");
611 return false;
612 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700613 return true;
614}
615
sergeyv4144eff2016-04-28 11:40:04 -0700616static void clearAppProperties()
617{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700618 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700619 fprintf(stderr, "failed to clear system property: %s",
620 k_traceAppsNumberProperty);
621 }
622}
623
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700624// Set the system property that indicates which apps should perform
625// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700626static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700627{
sergeyv4144eff2016-04-28 11:40:04 -0700628 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700629 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700630 while (start != NULL) {
sergeyv4144eff2016-04-28 11:40:04 -0700631 char* end = strchr(start, ',');
632 if (end != NULL) {
633 *end = '\0';
634 end++;
635 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700636 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
637 if (!android::base::SetProperty(key, start)) {
638 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700639 clearAppProperties();
640 return false;
641 }
642 start = end;
643 i++;
644 }
645
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700646 std::string value = android::base::StringPrintf("%d", i);
647 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
648 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700649 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700650 return false;
651 }
652 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800653}
654
655// Disable all /sys/ enable files.
656static bool disableKernelTraceEvents() {
657 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700658 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800659 const TracingCategory &c = k_categories[i];
660 for (int j = 0; j < MAX_SYS_FILES; j++) {
661 const char* path = c.sysfiles[j].path;
662 if (path != NULL && fileIsWritable(path)) {
663 ok &= setKernelOptionEnable(path, false);
664 }
665 }
666 }
667 return ok;
668}
669
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700670// Verify that the comma separated list of functions are being traced by the
671// kernel.
672static bool verifyKernelTraceFuncs(const char* funcs)
673{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100674 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800675 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100676 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700677 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100678 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700679 }
680
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100681 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700682
683 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100684 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700685 bool ok = true;
686 char* myFuncs = strdup(funcs);
687 char* func = strtok(myFuncs, ",");
688 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100689 if (!strchr(func, '*')) {
690 String8 fancyFunc = String8::format("\n%s\n", func);
691 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
692 if (!found || func[0] == '\0') {
693 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
694 "to trace.\n", func);
695 ok = false;
696 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700697 }
698 func = strtok(NULL, ",");
699 }
700 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700701 return ok;
702}
703
704// Set the comma separated list of functions that the kernel is to trace.
705static bool setKernelTraceFuncs(const char* funcs)
706{
707 bool ok = true;
708
709 if (funcs == NULL || funcs[0] == '\0') {
710 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700711 if (fileIsWritable(k_currentTracerPath)) {
712 ok &= writeStr(k_currentTracerPath, "nop");
713 }
714 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700715 ok &= truncateFile(k_ftraceFilterPath);
716 }
717 } else {
718 // Enable kernel function tracing.
719 ok &= writeStr(k_currentTracerPath, "function_graph");
720 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
721 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
722 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
723 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
724
725 // Set the requested filter functions.
726 ok &= truncateFile(k_ftraceFilterPath);
727 char* myFuncs = strdup(funcs);
728 char* func = strtok(myFuncs, ",");
729 while (func) {
730 ok &= appendStr(k_ftraceFilterPath, func);
731 func = strtok(NULL, ",");
732 }
733 free(myFuncs);
734
735 // Verify that the set functions are being traced.
736 if (ok) {
737 ok &= verifyKernelTraceFuncs(funcs);
738 }
739 }
740
741 return ok;
742}
743
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900744static bool setCategoryEnable(const char* name, bool enable)
745{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700746 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900747 const TracingCategory& c = k_categories[i];
748 if (strcmp(name, c.name) == 0) {
749 if (isCategorySupported(c)) {
750 g_categoryEnables[i] = enable;
751 return true;
752 } else {
753 if (isCategorySupportedForRoot(c)) {
754 fprintf(stderr, "error: category \"%s\" requires root "
755 "privileges.\n", name);
756 } else {
757 fprintf(stderr, "error: category \"%s\" is not supported "
758 "on this device.\n", name);
759 }
760 return false;
761 }
762 }
763 }
764 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
765 return false;
766}
767
768static bool setCategoriesEnableFromFile(const char* categories_file)
769{
770 if (!categories_file) {
771 return true;
772 }
773 Tokenizer* tokenizer = NULL;
774 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
775 return false;
776 }
777 bool ok = true;
778 while (!tokenizer->isEol()) {
779 String8 token = tokenizer->nextToken(" ");
780 if (token.isEmpty()) {
781 tokenizer->skipDelimiters(" ");
782 continue;
783 }
784 ok &= setCategoryEnable(token.string(), true);
785 }
786 delete tokenizer;
787 return ok;
788}
789
Hector Dearman11845782018-03-08 14:35:44 +0000790static bool setUpUserspaceTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800791{
792 bool ok = true;
793
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800794 // Set up the tags property.
795 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700796 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800797 if (g_categoryEnables[i]) {
798 const TracingCategory &c = k_categories[i];
799 tags |= c.tags;
800 }
801 }
802 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700803
804 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700805 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700806 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
807 coreServicesTagEnabled = g_categoryEnables[i];
808 }
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700809
810 // Set whether to poke PDX services in this session.
811 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
812 g_tracePdx = g_categoryEnables[i];
813 }
sergeyvdb404152016-05-02 19:26:07 -0700814 }
815
816 std::string packageList(g_debugAppCmdLine);
817 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700818 if (!packageList.empty()) {
819 packageList += ",";
820 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700821 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700822 }
Dan Austin09a79872016-05-31 13:27:03 -0700823 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700824 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100825 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800826
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700827 if (g_tracePdx) {
828 ok &= ServiceUtility::PokeServices();
829 }
830
Hector Dearman11845782018-03-08 14:35:44 +0000831 return ok;
832}
833
834static void cleanUpUserspaceTracing()
835{
836 setTagsProperty(0);
837 clearAppProperties();
838 pokeBinderServices();
839
840 if (g_tracePdx) {
841 ServiceUtility::PokeServices();
842 }
843}
844
845
846// Set all the kernel tracing settings to the desired state for this trace
847// capture.
848static bool setUpKernelTracing()
849{
850 bool ok = true;
851
Carmen Jacksonab1118e2018-05-22 10:29:47 -0700852 ok &= setUserInitiatedTraceProperty(true);
853
Hector Dearman11845782018-03-08 14:35:44 +0000854 // Set up the tracing options.
855 ok &= setCategoriesEnableFromFile(g_categoriesFile);
856 ok &= setTraceOverwriteEnable(g_traceOverwrite);
857 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
858 // TODO: Re-enable after stabilization
859 //ok &= setCmdlineSize();
860 ok &= setClock();
861 ok &= setPrintTgidEnableIfPresent(true);
862 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
863
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800864 // Disable all the sysfs enables. This is done as a separate loop from
865 // the enables to allow the same enable to exist in multiple categories.
866 ok &= disableKernelTraceEvents();
867
868 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700869 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800870 if (g_categoryEnables[i]) {
871 const TracingCategory &c = k_categories[i];
872 for (int j = 0; j < MAX_SYS_FILES; j++) {
873 const char* path = c.sysfiles[j].path;
874 bool required = c.sysfiles[j].required == REQ;
875 if (path != NULL) {
876 if (fileIsWritable(path)) {
877 ok &= setKernelOptionEnable(path, true);
878 } else if (required) {
879 fprintf(stderr, "error writing file %s\n", path);
880 ok = false;
881 }
882 }
883 }
884 }
885 }
886
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800887 return ok;
888}
889
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700890// Reset all the kernel tracing settings to their default state.
Hector Dearman11845782018-03-08 14:35:44 +0000891static void cleanUpKernelTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800892{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800893 // Disable all tracing that we're able to.
894 disableKernelTraceEvents();
895
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800896 // Set the options back to their defaults.
897 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700898 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700899 setPrintTgidEnableIfPresent(false);
900 setKernelTraceFuncs(NULL);
Carmen Jacksonab1118e2018-05-22 10:29:47 -0700901 setUserInitiatedTraceProperty(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700902}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800903
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700904// Enable tracing in the kernel.
905static bool startTrace()
906{
907 return setTracingEnabled(true);
908}
909
910// Disable tracing in the kernel.
911static void stopTrace()
912{
913 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800914}
915
Martijn Coenend9535872015-11-26 10:00:55 +0100916// Read data from the tracing pipe and forward to stdout
917static void streamTrace()
918{
919 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800920 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100921 if (traceFD == -1) {
922 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
923 strerror(errno), errno);
924 return;
925 }
926 while (!g_traceAborted) {
927 ssize_t bytes_read = read(traceFD, trace_data, 4096);
928 if (bytes_read > 0) {
929 write(STDOUT_FILENO, trace_data, bytes_read);
930 fflush(stdout);
931 } else {
932 if (!g_traceAborted) {
933 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
934 bytes_read, errno, strerror(errno));
935 }
936 break;
937 }
938 }
939}
940
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800941// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700942static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800943{
John Reck6c8ac922016-03-28 11:25:30 -0700944 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800945 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800946 if (traceFD == -1) {
947 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
948 strerror(errno), errno);
949 return;
950 }
951
952 if (g_compress) {
953 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800954 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700955
956 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800957 if (result != Z_OK) {
958 fprintf(stderr, "error initializing zlib: %d\n", result);
959 close(traceFD);
960 return;
961 }
962
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700963 constexpr size_t bufSize = 64*1024;
964 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
965 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
966 if (!in || !out) {
967 fprintf(stderr, "couldn't allocate buffers\n");
968 close(traceFD);
969 return;
970 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800971
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700972 int flush = Z_NO_FLUSH;
973
974 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800975 zs.avail_out = bufSize;
976
977 do {
978
979 if (zs.avail_in == 0) {
980 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700981 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800982 if (result < 0) {
983 fprintf(stderr, "error reading trace: %s (%d)\n",
984 strerror(errno), errno);
985 result = Z_STREAM_END;
986 break;
987 } else if (result == 0) {
988 flush = Z_FINISH;
989 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700990 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800991 zs.avail_in = result;
992 }
993 }
994
995 if (zs.avail_out == 0) {
996 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700997 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800998 if ((size_t)result < bufSize) {
999 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1000 strerror(errno), errno);
1001 result = Z_STREAM_END; // skip deflate error message
1002 zs.avail_out = bufSize; // skip the final write
1003 break;
1004 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001005 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001006 zs.avail_out = bufSize;
1007 }
1008
1009 } while ((result = deflate(&zs, flush)) == Z_OK);
1010
1011 if (result != Z_STREAM_END) {
1012 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
1013 }
1014
1015 if (zs.avail_out < bufSize) {
1016 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -07001017 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001018 if ((size_t)result < bytes) {
1019 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1020 strerror(errno), errno);
1021 }
1022 }
1023
1024 result = deflateEnd(&zs);
1025 if (result != Z_OK) {
1026 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1027 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001028 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001029 char buf[4096];
1030 ssize_t rc;
1031 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1032 if (!android::base::WriteFully(outFd, buf, rc)) {
1033 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1034 break;
1035 }
1036 }
1037 if (rc == -1) {
1038 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001039 }
1040 }
1041
1042 close(traceFD);
1043}
1044
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001045static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001046{
1047 if (!g_nohup) {
1048 g_traceAborted = true;
1049 }
1050}
1051
1052static void registerSigHandler()
1053{
1054 struct sigaction sa;
1055 sigemptyset(&sa.sa_mask);
1056 sa.sa_flags = 0;
1057 sa.sa_handler = handleSignal;
1058 sigaction(SIGHUP, &sa, NULL);
1059 sigaction(SIGINT, &sa, NULL);
1060 sigaction(SIGQUIT, &sa, NULL);
1061 sigaction(SIGTERM, &sa, NULL);
1062}
1063
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001064static void listSupportedCategories()
1065{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001066 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001067 const TracingCategory& c = k_categories[i];
1068 if (isCategorySupported(c)) {
1069 printf(" %10s - %s\n", c.name, c.longname);
1070 }
1071 }
1072}
1073
1074// Print the command usage help to stderr.
1075static void showHelp(const char *cmd)
1076{
1077 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1078 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001079 " -a appname enable app-level tracing for a comma "
Daniel Colascione519a0792018-02-09 20:05:39 -08001080 "separated list of cmdlines; * is a wildcard matching any process\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001081 " -b N use a trace buffer size of N KB\n"
1082 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001083 " -f filename use the categories written in a file as space-separated\n"
1084 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001085 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001086 " -n ignore signals\n"
1087 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001088 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001089 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001090 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001091 " --async_dump dump the current contents of circular trace buffer\n"
1092 " --async_stop stop tracing and dump the current contents of circular\n"
1093 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001094 " --stream stream trace to stdout as it enters the trace buffer\n"
1095 " Note: this can take significant CPU time, and is best\n"
1096 " used for measuring things that are not affected by\n"
1097 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001098 " --list_categories\n"
1099 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001100 " -o filename write the trace to the specified file instead\n"
1101 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001102 );
1103}
1104
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001105bool findTraceFiles()
1106{
1107 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1108 static const std::string tracefs_path = "/sys/kernel/tracing/";
1109 static const std::string trace_file = "trace_marker";
1110
1111 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1112 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1113
1114 if (!tracefs && !debugfs) {
1115 fprintf(stderr, "Error: Did not find trace folder\n");
1116 return false;
1117 }
1118
1119 if (tracefs) {
1120 g_traceFolder = tracefs_path;
1121 } else {
1122 g_traceFolder = debugfs_path;
1123 }
1124
1125 return true;
1126}
1127
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001128int main(int argc, char **argv)
1129{
1130 bool async = false;
1131 bool traceStart = true;
1132 bool traceStop = true;
1133 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001134 bool traceStream = false;
Hector Dearman11845782018-03-08 14:35:44 +00001135 bool onlyUserspace = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001136
1137 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1138 showHelp(argv[0]);
1139 exit(0);
1140 }
1141
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001142 if (!findTraceFiles()) {
1143 fprintf(stderr, "No trace folder found\n");
1144 exit(-1);
1145 }
1146
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001147 for (;;) {
1148 int ret;
1149 int option_index = 0;
1150 static struct option long_options[] = {
Hector Dearman11845782018-03-08 14:35:44 +00001151 {"async_start", no_argument, 0, 0 },
1152 {"async_stop", no_argument, 0, 0 },
1153 {"async_dump", no_argument, 0, 0 },
1154 {"only_userspace", no_argument, 0, 0 },
1155 {"list_categories", no_argument, 0, 0 },
1156 {"stream", no_argument, 0, 0 },
1157 { 0, 0, 0, 0 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001158 };
1159
John Reck40b26b42016-03-30 09:44:36 -07001160 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001161 long_options, &option_index);
1162
1163 if (ret < 0) {
1164 for (int i = optind; i < argc; i++) {
1165 if (!setCategoryEnable(argv[i], true)) {
1166 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1167 exit(1);
1168 }
1169 }
1170 break;
1171 }
1172
1173 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001174 case 'a':
1175 g_debugAppCmdLine = optarg;
1176 break;
1177
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001178 case 'b':
1179 g_traceBufferSizeKB = atoi(optarg);
1180 break;
1181
1182 case 'c':
1183 g_traceOverwrite = true;
1184 break;
1185
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001186 case 'f':
1187 g_categoriesFile = optarg;
1188 break;
1189
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001190 case 'k':
1191 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001192 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001193
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001194 case 'n':
1195 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001196 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001197
1198 case 's':
1199 g_initialSleepSecs = atoi(optarg);
1200 break;
1201
1202 case 't':
1203 g_traceDurationSeconds = atoi(optarg);
1204 break;
1205
1206 case 'z':
1207 g_compress = true;
1208 break;
1209
John Reck40b26b42016-03-30 09:44:36 -07001210 case 'o':
1211 g_outputFile = optarg;
1212 break;
1213
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001214 case 0:
1215 if (!strcmp(long_options[option_index].name, "async_start")) {
1216 async = true;
1217 traceStop = false;
1218 traceDump = false;
1219 g_traceOverwrite = true;
1220 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1221 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001222 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001223 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1224 async = true;
1225 traceStart = false;
1226 traceStop = false;
Hector Dearman11845782018-03-08 14:35:44 +00001227 } else if (!strcmp(long_options[option_index].name, "only_userspace")) {
1228 onlyUserspace = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001229 } else if (!strcmp(long_options[option_index].name, "stream")) {
1230 traceStream = true;
1231 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001232 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1233 listSupportedCategories();
1234 exit(0);
1235 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001236 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001237
1238 default:
1239 fprintf(stderr, "\n");
1240 showHelp(argv[0]);
1241 exit(-1);
1242 break;
1243 }
1244 }
1245
Hector Dearman11845782018-03-08 14:35:44 +00001246 if (onlyUserspace) {
1247 if (!async || !(traceStart || traceStop)) {
1248 fprintf(stderr, "--only_userspace can only be used with "
1249 "--async_start or --async_stop\n");
1250 exit(1);
1251 }
1252 }
1253
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001254 registerSigHandler();
1255
1256 if (g_initialSleepSecs > 0) {
1257 sleep(g_initialSleepSecs);
1258 }
1259
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001260 bool ok = true;
Hector Dearman11845782018-03-08 14:35:44 +00001261
Wei Wang5b73b742018-03-08 13:33:12 -08001262 if (traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001263 ok &= setUpUserspaceTracing();
1264 }
1265
1266 if (ok && traceStart && !onlyUserspace) {
1267 ok &= setUpKernelTracing();
Wei Wang5b73b742018-03-08 13:33:12 -08001268 ok &= startTrace();
1269 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001270
1271 if (ok && traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001272
1273 if (!traceStream && !onlyUserspace) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001274 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001275 fflush(stdout);
1276 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001277
1278 // We clear the trace after starting it because tracing gets enabled for
1279 // each CPU individually in the kernel. Having the beginning of the trace
1280 // contain entries from only one CPU can cause "begin" entries without a
1281 // matching "end" entry to show up if a task gets migrated from one CPU to
1282 // another.
Hector Dearman11845782018-03-08 14:35:44 +00001283 if (!onlyUserspace)
1284 ok = clearTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001285
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001286 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001287 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001288 // Sleep to allow the trace to be captured.
1289 struct timespec timeLeft;
1290 timeLeft.tv_sec = g_traceDurationSeconds;
1291 timeLeft.tv_nsec = 0;
1292 do {
1293 if (g_traceAborted) {
1294 break;
1295 }
1296 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1297 }
Martijn Coenend9535872015-11-26 10:00:55 +01001298
1299 if (traceStream) {
1300 streamTrace();
1301 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001302 }
1303
1304 // Stop the trace and restore the default settings.
Hector Dearman11845782018-03-08 14:35:44 +00001305 if (traceStop && !onlyUserspace)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001306 stopTrace();
1307
Hector Dearman11845782018-03-08 14:35:44 +00001308 if (ok && traceDump && !onlyUserspace) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001309 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001310 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001311 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001312 int outFd = STDOUT_FILENO;
1313 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001314 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001315 }
1316 if (outFd == -1) {
1317 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1318 } else {
1319 dprintf(outFd, "TRACE:\n");
1320 dumpTrace(outFd);
1321 if (g_outputFile) {
1322 close(outFd);
1323 }
1324 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001325 } else {
1326 printf("\ntrace aborted.\n");
1327 fflush(stdout);
1328 }
1329 clearTrace();
1330 } else if (!ok) {
1331 fprintf(stderr, "unable to start tracing\n");
1332 }
1333
1334 // Reset the trace buffer size to 1.
Hector Dearman11845782018-03-08 14:35:44 +00001335 if (traceStop) {
1336 cleanUpUserspaceTracing();
1337 if (!onlyUserspace)
1338 cleanUpKernelTracing();
1339 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001340
1341 return g_traceAborted ? 1 : 0;
1342}