blob: 24217a46ab0f6afbdfcf79777cc26dd99e93d110 [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";
sergeyv4144eff2016-04-28 11:40:04 -070061
62const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
63const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070064const char* k_coreServiceCategory = "core_services";
Corey Tabakaa6c0a722017-05-31 16:37:40 -070065const char* k_pdxServiceCategory = "pdx";
sergeyvdb404152016-05-02 19:26:07 -070066const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080067
68typedef enum { OPT, REQ } requiredness ;
69
70struct TracingCategory {
71 // The name identifying the category.
72 const char* name;
73
74 // A longer description of the category.
75 const char* longname;
76
77 // The userland tracing tags that the category enables.
78 uint64_t tags;
79
80 // The fname==NULL terminated list of /sys/ files that the category
81 // enables.
82 struct {
83 // Whether the file must be writable in order to enable the tracing
84 // category.
85 requiredness required;
86
87 // The path to the enable file.
88 const char* path;
89 } sysfiles[MAX_SYS_FILES];
90};
91
92/* Tracing categories */
93static const TracingCategory k_categories[] = {
John Reck732a29a2017-05-24 16:09:21 -070094 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, {
95 { OPT, "events/mdss/enable" },
Wei Wangbcfb4872018-02-13 10:47:23 -080096 { OPT, "events/sde/enable" },
John Reck732a29a2017-05-24 16:09:21 -070097 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070098 { "input", "Input", ATRACE_TAG_INPUT, { } },
99 { "view", "View System", ATRACE_TAG_VIEW, { } },
100 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
101 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
102 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -0500103 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700104 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
105 { "video", "Video", ATRACE_TAG_VIDEO, { } },
106 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
107 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -0700108 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -0700109 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -0700110 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -0700111 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700112 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 14:36:20 -0700113 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-07-01 01:46:25 +0900114 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Greg Hackmannbbd7d992014-12-01 14:43:34 -0800115 { "database", "Database", ATRACE_TAG_DATABASE, { } },
Felipe Leme0f97c1d2016-09-07 11:33:26 -0700116 { "network", "Network", ATRACE_TAG_NETWORK, { } },
Josh Gao468b4cb2016-11-29 10:55:21 -0800117 { "adb", "ADB", ATRACE_TAG_ADB, { } },
Martijn Coenen42f2ab42018-03-09 09:27:32 +0100118 { "vibrator", "Vibrator", ATRACE_TAG_VIBRATOR, { } },
119 { "aidl", "AIDL calls", ATRACE_TAG_AIDL, { } },
Mika Raentob363cf52018-04-23 22:09:13 +0100120 { "nnapi", "NNAPI", ATRACE_TAG_NNAPI, { } },
sergeyvdb404152016-05-02 19:26:07 -0700121 { k_coreServiceCategory, "Core services", 0, { } },
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700122 { k_pdxServiceCategory, "PDX services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700123 { "sched", "CPU Scheduling", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800124 { REQ, "events/sched/sched_switch/enable" },
125 { REQ, "events/sched/sched_wakeup/enable" },
Joel Fernandesee593e22017-06-04 13:05:59 -0700126 { OPT, "events/sched/sched_waking/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800127 { OPT, "events/sched/sched_blocked_reason/enable" },
128 { OPT, "events/sched/sched_cpu_hotplug/enable" },
Wei Wangca49dfc2018-05-03 15:45:20 -0700129 { OPT, "events/sched/sched_pi_setprio/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, {
Jesse Hallae001a32018-05-15 12:02:15 -0700190 // before linux kernel 4.9
191 { OPT, "events/sync/enable" },
192 // starting in linux kernel 4.9
193 { OPT, "events/fence/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800194 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700195 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800196 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800197 } },
Colin Cross580407f2014-08-18 15:22:13 -0700198 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800199 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
200 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
201 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
202 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Marc Hittingerf1f62e32017-05-17 15:57:43 -0700203 { REQ, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700204 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800205 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800206 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800207 } },
Scott Bauerae473362015-06-08 16:32:36 -0700208 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800209 { REQ, "events/binder/binder_transaction/enable" },
210 { REQ, "events/binder/binder_transaction_received/enable" },
Martijn Coenen7f3d7a22017-05-26 09:50:55 -0700211 { OPT, "events/binder/binder_set_priority/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700212 } },
213 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800214 { OPT, "events/binder/binder_lock/enable" },
215 { OPT, "events/binder/binder_locked/enable" },
216 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700217 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200218 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800219 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200220 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800221};
222
223/* Command line options */
224static int g_traceDurationSeconds = 5;
225static bool g_traceOverwrite = false;
226static int g_traceBufferSizeKB = 2048;
227static bool g_compress = false;
228static bool g_nohup = false;
229static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900230static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700231static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700232static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700233static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800234
235/* Global state */
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700236static bool g_tracePdx = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800237static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700238static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800239static std::string g_traceFolder;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800240
241/* Sys file paths */
242static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800243 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800244
245static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800246 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800247
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700248#if 0
249// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700250static const char* k_traceCmdlineSizePath =
251 "saved_cmdlines_size";
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700252#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700253
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800254static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800255 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800256
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700257static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800258 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700259
260static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800261 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700262
263static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800264 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700265
266static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800267 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700268
269static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800270 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700271
272static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800273 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700274
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700275static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800276 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700277
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800278static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800279 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800280
281static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800282 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800283
Martijn Coenend9535872015-11-26 10:00:55 +0100284static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800285 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100286
John Reck469a1942015-03-26 15:31:35 -0700287static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800288 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700289
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800290// Check whether a file exists.
291static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800292 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800293}
294
295// Check whether a file is writable.
296static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800297 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800298}
299
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700300// Truncate a file.
301static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800302{
Jamie Gennis43122e72013-03-21 14:06:31 -0700303 // This uses creat rather than truncate because some of the debug kernel
304 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
305 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800306 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700307 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800308 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700309 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700310 return false;
311 }
312
Jamie Gennis43122e72013-03-21 14:06:31 -0700313 close(traceFD);
314
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700315 return true;
316}
317
318static bool _writeStr(const char* filename, const char* str, int flags)
319{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800320 std::string fullFilename = g_traceFolder + filename;
321 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800322 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800323 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800324 strerror(errno), errno);
325 return false;
326 }
327
328 bool ok = true;
329 ssize_t len = strlen(str);
330 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800331 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800332 strerror(errno), errno);
333 ok = false;
334 }
335
336 close(fd);
337
338 return ok;
339}
340
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700341// Write a string to a file, returning true if the write was successful.
342static bool writeStr(const char* filename, const char* str)
343{
344 return _writeStr(filename, str, O_WRONLY);
345}
346
347// Append a string to a file, returning true if the write was successful.
348static bool appendStr(const char* filename, const char* str)
349{
350 return _writeStr(filename, str, O_APPEND|O_WRONLY);
351}
352
John Reck469a1942015-03-26 15:31:35 -0700353static void writeClockSyncMarker()
354{
355 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200356 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800357 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200358 if (fd == -1) {
359 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
360 strerror(errno), errno);
361 return;
362 }
John Reck469a1942015-03-26 15:31:35 -0700363 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200364
365 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
366 if (write(fd, buffer, len) != len) {
367 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
368 }
369
370 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
371 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
372 if (write(fd, buffer, len) != len) {
373 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
374 }
375
376 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700377}
378
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800379// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
380// file.
381static bool setKernelOptionEnable(const char* filename, bool enable)
382{
383 return writeStr(filename, enable ? "1" : "0");
384}
385
386// Check whether the category is supported on the device with the current
387// rootness. A category is supported only if all its required /sys/ files are
388// writable and if enabling the category will enable one or more tracing tags
389// or /sys/ files.
390static bool isCategorySupported(const TracingCategory& category)
391{
sergeyvdb404152016-05-02 19:26:07 -0700392 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700393 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700394 }
395
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700396 if (strcmp(category.name, k_pdxServiceCategory) == 0) {
397 return true;
398 }
399
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800400 bool ok = category.tags != 0;
401 for (int i = 0; i < MAX_SYS_FILES; i++) {
402 const char* path = category.sysfiles[i].path;
403 bool req = category.sysfiles[i].required == REQ;
404 if (path != NULL) {
405 if (req) {
406 if (!fileIsWritable(path)) {
407 return false;
408 } else {
409 ok = true;
410 }
411 } else {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800412 ok = true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800413 }
414 }
415 }
416 return ok;
417}
418
419// Check whether the category would be supported on the device if the user
420// were root. This function assumes that root is able to write to any file
421// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700422// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800423static bool isCategorySupportedForRoot(const TracingCategory& category)
424{
425 bool ok = category.tags != 0;
426 for (int i = 0; i < MAX_SYS_FILES; i++) {
427 const char* path = category.sysfiles[i].path;
428 bool req = category.sysfiles[i].required == REQ;
429 if (path != NULL) {
430 if (req) {
431 if (!fileExists(path)) {
432 return false;
433 } else {
434 ok = true;
435 }
436 } else {
437 ok |= fileExists(path);
438 }
439 }
440 }
441 return ok;
442}
443
444// Enable or disable overwriting of the kernel trace buffers. Disabling this
445// will cause tracing to stop once the trace buffers have filled up.
446static bool setTraceOverwriteEnable(bool enable)
447{
448 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
449}
450
451// Enable or disable kernel tracing.
452static bool setTracingEnabled(bool enable)
453{
454 return setKernelOptionEnable(k_tracingOnPath, enable);
455}
456
457// Clear the contents of the kernel trace.
458static bool clearTrace()
459{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700460 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800461}
462
463// Set the size of the kernel's trace buffer in kilobytes.
464static bool setTraceBufferSizeKB(int size)
465{
466 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800467 if (size < 1) {
468 size = 1;
469 }
470 snprintf(str, 32, "%d", size);
471 return writeStr(k_traceBufferSizePath, str);
472}
473
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700474#if 0
475// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700476// Set the default size of cmdline hashtable
477static bool setCmdlineSize()
478{
Joel Fernandesce964f22017-06-06 12:20:29 -0700479 if (fileExists(k_traceCmdlineSizePath)) {
480 return writeStr(k_traceCmdlineSizePath, "8192");
481 }
482 return true;
Joel Fernandesed80bd02017-06-02 10:19:28 -0700483}
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700484#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700485
Carmen Jacksonea826792017-05-05 11:42:32 -0700486// Set the clock to the best available option while tracing. Use 'boot' if it's
487// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700488// Any write to the trace_clock sysfs file will reset the buffer, so only
489// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700490static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800491{
Carmen Jacksonea826792017-05-05 11:42:32 -0700492 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
493 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
494 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700495
Carmen Jacksonea826792017-05-05 11:42:32 -0700496 std::string newClock;
497 if (clockStr.find("boot") != std::string::npos) {
498 newClock = "boot";
499 } else if (clockStr.find("mono") != std::string::npos) {
500 newClock = "mono";
501 } else {
502 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700503 }
504
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700505 size_t begin = clockStr.find('[') + 1;
506 size_t end = clockStr.find(']');
Carmen Jacksonea826792017-05-05 11:42:32 -0700507 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
508 return true;
509 }
510 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800511}
512
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700513static bool setPrintTgidEnableIfPresent(bool enable)
514{
515 if (fileExists(k_printTgidPath)) {
516 return setKernelOptionEnable(k_printTgidPath, enable);
517 }
518 return true;
519}
520
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800521// Poke all the binder-enabled processes in the system to get them to re-read
522// their system properties.
523static bool pokeBinderServices()
524{
525 sp<IServiceManager> sm = defaultServiceManager();
526 Vector<String16> services = sm->listServices();
527 for (size_t i = 0; i < services.size(); i++) {
528 sp<IBinder> obj = sm->checkService(services[i]);
529 if (obj != NULL) {
530 Parcel data;
531 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
532 NULL, 0) != OK) {
533 if (false) {
534 // XXX: For some reason this fails on tablets trying to
535 // poke the "phone" service. It's not clear whether some
536 // are expected to fail.
537 String8 svc(services[i]);
538 fprintf(stderr, "error poking binder service %s\n",
539 svc.string());
540 return false;
541 }
542 }
543 }
544 }
545 return true;
546}
547
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100548// Poke all the HAL processes in the system to get them to re-read
549// their system properties.
550static void pokeHalServices()
551{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100552 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100553 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100554 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100555 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100556
557 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800558
559 if (sm == nullptr) {
560 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
561 return;
562 }
563
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800564 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100565 for (size_t i = 0; i < interfaces.size(); i++) {
566 string fqInstanceName = interfaces[i];
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700567 string::size_type n = fqInstanceName.find('/');
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100568 if (n == std::string::npos || interfaces[i].size() == n+1)
569 continue;
570 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
571 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100572 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
573 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100574 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100575 continue;
576 }
Carmen Jackson73206122017-04-18 15:37:57 -0700577
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100578 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700579 if (interface == nullptr) {
580 // ignore
581 continue;
582 }
583
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100584 auto notifyRet = interface->notifySyspropsChanged();
585 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100586 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800587 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100588 }
589 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800590 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100591 // TODO(b/34242478) fix this when we determine the correct ACL
592 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800593 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100594}
595
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800596// Set the trace tags that userland tracing uses, and poke the running
597// processes to pick up the new value.
598static bool setTagsProperty(uint64_t tags)
599{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700600 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
601 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800602 fprintf(stderr, "error setting trace tags system property\n");
603 return false;
604 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700605 return true;
606}
607
sergeyv4144eff2016-04-28 11:40:04 -0700608static void clearAppProperties()
609{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700610 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700611 fprintf(stderr, "failed to clear system property: %s",
612 k_traceAppsNumberProperty);
613 }
614}
615
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700616// Set the system property that indicates which apps should perform
617// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700618static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700619{
sergeyv4144eff2016-04-28 11:40:04 -0700620 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700621 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700622 while (start != NULL) {
sergeyv4144eff2016-04-28 11:40:04 -0700623 char* end = strchr(start, ',');
624 if (end != NULL) {
625 *end = '\0';
626 end++;
627 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700628 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
629 if (!android::base::SetProperty(key, start)) {
630 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700631 clearAppProperties();
632 return false;
633 }
634 start = end;
635 i++;
636 }
637
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700638 std::string value = android::base::StringPrintf("%d", i);
639 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
640 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700641 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700642 return false;
643 }
644 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800645}
646
647// Disable all /sys/ enable files.
648static bool disableKernelTraceEvents() {
649 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700650 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800651 const TracingCategory &c = k_categories[i];
652 for (int j = 0; j < MAX_SYS_FILES; j++) {
653 const char* path = c.sysfiles[j].path;
654 if (path != NULL && fileIsWritable(path)) {
655 ok &= setKernelOptionEnable(path, false);
656 }
657 }
658 }
659 return ok;
660}
661
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700662// Verify that the comma separated list of functions are being traced by the
663// kernel.
664static bool verifyKernelTraceFuncs(const char* funcs)
665{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100666 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800667 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100668 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700669 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100670 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700671 }
672
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100673 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700674
675 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100676 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700677 bool ok = true;
678 char* myFuncs = strdup(funcs);
679 char* func = strtok(myFuncs, ",");
680 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100681 if (!strchr(func, '*')) {
682 String8 fancyFunc = String8::format("\n%s\n", func);
683 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
684 if (!found || func[0] == '\0') {
685 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
686 "to trace.\n", func);
687 ok = false;
688 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700689 }
690 func = strtok(NULL, ",");
691 }
692 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700693 return ok;
694}
695
696// Set the comma separated list of functions that the kernel is to trace.
697static bool setKernelTraceFuncs(const char* funcs)
698{
699 bool ok = true;
700
701 if (funcs == NULL || funcs[0] == '\0') {
702 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700703 if (fileIsWritable(k_currentTracerPath)) {
704 ok &= writeStr(k_currentTracerPath, "nop");
705 }
706 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700707 ok &= truncateFile(k_ftraceFilterPath);
708 }
709 } else {
710 // Enable kernel function tracing.
711 ok &= writeStr(k_currentTracerPath, "function_graph");
712 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
713 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
714 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
715 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
716
717 // Set the requested filter functions.
718 ok &= truncateFile(k_ftraceFilterPath);
719 char* myFuncs = strdup(funcs);
720 char* func = strtok(myFuncs, ",");
721 while (func) {
722 ok &= appendStr(k_ftraceFilterPath, func);
723 func = strtok(NULL, ",");
724 }
725 free(myFuncs);
726
727 // Verify that the set functions are being traced.
728 if (ok) {
729 ok &= verifyKernelTraceFuncs(funcs);
730 }
731 }
732
733 return ok;
734}
735
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900736static bool setCategoryEnable(const char* name, bool enable)
737{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700738 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900739 const TracingCategory& c = k_categories[i];
740 if (strcmp(name, c.name) == 0) {
741 if (isCategorySupported(c)) {
742 g_categoryEnables[i] = enable;
743 return true;
744 } else {
745 if (isCategorySupportedForRoot(c)) {
746 fprintf(stderr, "error: category \"%s\" requires root "
747 "privileges.\n", name);
748 } else {
749 fprintf(stderr, "error: category \"%s\" is not supported "
750 "on this device.\n", name);
751 }
752 return false;
753 }
754 }
755 }
756 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
757 return false;
758}
759
760static bool setCategoriesEnableFromFile(const char* categories_file)
761{
762 if (!categories_file) {
763 return true;
764 }
765 Tokenizer* tokenizer = NULL;
766 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
767 return false;
768 }
769 bool ok = true;
770 while (!tokenizer->isEol()) {
771 String8 token = tokenizer->nextToken(" ");
772 if (token.isEmpty()) {
773 tokenizer->skipDelimiters(" ");
774 continue;
775 }
776 ok &= setCategoryEnable(token.string(), true);
777 }
778 delete tokenizer;
779 return ok;
780}
781
Hector Dearman11845782018-03-08 14:35:44 +0000782static bool setUpUserspaceTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800783{
784 bool ok = true;
785
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800786 // Set up the tags property.
787 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700788 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800789 if (g_categoryEnables[i]) {
790 const TracingCategory &c = k_categories[i];
791 tags |= c.tags;
792 }
793 }
794 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700795
796 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700797 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700798 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
799 coreServicesTagEnabled = g_categoryEnables[i];
800 }
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700801
802 // Set whether to poke PDX services in this session.
803 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
804 g_tracePdx = g_categoryEnables[i];
805 }
sergeyvdb404152016-05-02 19:26:07 -0700806 }
807
808 std::string packageList(g_debugAppCmdLine);
809 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700810 if (!packageList.empty()) {
811 packageList += ",";
812 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700813 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700814 }
Dan Austin09a79872016-05-31 13:27:03 -0700815 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700816 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100817 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800818
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700819 if (g_tracePdx) {
820 ok &= ServiceUtility::PokeServices();
821 }
822
Hector Dearman11845782018-03-08 14:35:44 +0000823 return ok;
824}
825
826static void cleanUpUserspaceTracing()
827{
828 setTagsProperty(0);
829 clearAppProperties();
830 pokeBinderServices();
831
832 if (g_tracePdx) {
833 ServiceUtility::PokeServices();
834 }
835}
836
837
838// Set all the kernel tracing settings to the desired state for this trace
839// capture.
840static bool setUpKernelTracing()
841{
842 bool ok = true;
843
844 // Set up the tracing options.
845 ok &= setCategoriesEnableFromFile(g_categoriesFile);
846 ok &= setTraceOverwriteEnable(g_traceOverwrite);
847 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
848 // TODO: Re-enable after stabilization
849 //ok &= setCmdlineSize();
850 ok &= setClock();
851 ok &= setPrintTgidEnableIfPresent(true);
852 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
853
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800854 // Disable all the sysfs enables. This is done as a separate loop from
855 // the enables to allow the same enable to exist in multiple categories.
856 ok &= disableKernelTraceEvents();
857
858 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700859 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800860 if (g_categoryEnables[i]) {
861 const TracingCategory &c = k_categories[i];
862 for (int j = 0; j < MAX_SYS_FILES; j++) {
863 const char* path = c.sysfiles[j].path;
864 bool required = c.sysfiles[j].required == REQ;
865 if (path != NULL) {
866 if (fileIsWritable(path)) {
867 ok &= setKernelOptionEnable(path, true);
868 } else if (required) {
869 fprintf(stderr, "error writing file %s\n", path);
870 ok = false;
871 }
872 }
873 }
874 }
875 }
876
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800877 return ok;
878}
879
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700880// Reset all the kernel tracing settings to their default state.
Hector Dearman11845782018-03-08 14:35:44 +0000881static void cleanUpKernelTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800882{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800883 // Disable all tracing that we're able to.
884 disableKernelTraceEvents();
885
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800886 // Set the options back to their defaults.
887 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700888 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700889 setPrintTgidEnableIfPresent(false);
890 setKernelTraceFuncs(NULL);
891}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800892
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700893// Enable tracing in the kernel.
894static bool startTrace()
895{
896 return setTracingEnabled(true);
897}
898
899// Disable tracing in the kernel.
900static void stopTrace()
901{
902 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800903}
904
Martijn Coenend9535872015-11-26 10:00:55 +0100905// Read data from the tracing pipe and forward to stdout
906static void streamTrace()
907{
908 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800909 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100910 if (traceFD == -1) {
911 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
912 strerror(errno), errno);
913 return;
914 }
915 while (!g_traceAborted) {
916 ssize_t bytes_read = read(traceFD, trace_data, 4096);
917 if (bytes_read > 0) {
918 write(STDOUT_FILENO, trace_data, bytes_read);
919 fflush(stdout);
920 } else {
921 if (!g_traceAborted) {
922 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
923 bytes_read, errno, strerror(errno));
924 }
925 break;
926 }
927 }
928}
929
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800930// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700931static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800932{
John Reck6c8ac922016-03-28 11:25:30 -0700933 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800934 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800935 if (traceFD == -1) {
936 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
937 strerror(errno), errno);
938 return;
939 }
940
941 if (g_compress) {
942 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800943 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700944
945 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800946 if (result != Z_OK) {
947 fprintf(stderr, "error initializing zlib: %d\n", result);
948 close(traceFD);
949 return;
950 }
951
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700952 constexpr size_t bufSize = 64*1024;
953 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
954 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
955 if (!in || !out) {
956 fprintf(stderr, "couldn't allocate buffers\n");
957 close(traceFD);
958 return;
959 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800960
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700961 int flush = Z_NO_FLUSH;
962
963 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800964 zs.avail_out = bufSize;
965
966 do {
967
968 if (zs.avail_in == 0) {
969 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700970 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800971 if (result < 0) {
972 fprintf(stderr, "error reading trace: %s (%d)\n",
973 strerror(errno), errno);
974 result = Z_STREAM_END;
975 break;
976 } else if (result == 0) {
977 flush = Z_FINISH;
978 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700979 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800980 zs.avail_in = result;
981 }
982 }
983
984 if (zs.avail_out == 0) {
985 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700986 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800987 if ((size_t)result < bufSize) {
988 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
989 strerror(errno), errno);
990 result = Z_STREAM_END; // skip deflate error message
991 zs.avail_out = bufSize; // skip the final write
992 break;
993 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700994 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800995 zs.avail_out = bufSize;
996 }
997
998 } while ((result = deflate(&zs, flush)) == Z_OK);
999
1000 if (result != Z_STREAM_END) {
1001 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
1002 }
1003
1004 if (zs.avail_out < bufSize) {
1005 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -07001006 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001007 if ((size_t)result < bytes) {
1008 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1009 strerror(errno), errno);
1010 }
1011 }
1012
1013 result = deflateEnd(&zs);
1014 if (result != Z_OK) {
1015 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1016 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001017 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001018 char buf[4096];
1019 ssize_t rc;
1020 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1021 if (!android::base::WriteFully(outFd, buf, rc)) {
1022 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1023 break;
1024 }
1025 }
1026 if (rc == -1) {
1027 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001028 }
1029 }
1030
1031 close(traceFD);
1032}
1033
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001034static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001035{
1036 if (!g_nohup) {
1037 g_traceAborted = true;
1038 }
1039}
1040
1041static void registerSigHandler()
1042{
1043 struct sigaction sa;
1044 sigemptyset(&sa.sa_mask);
1045 sa.sa_flags = 0;
1046 sa.sa_handler = handleSignal;
1047 sigaction(SIGHUP, &sa, NULL);
1048 sigaction(SIGINT, &sa, NULL);
1049 sigaction(SIGQUIT, &sa, NULL);
1050 sigaction(SIGTERM, &sa, NULL);
1051}
1052
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001053static void listSupportedCategories()
1054{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001055 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001056 const TracingCategory& c = k_categories[i];
1057 if (isCategorySupported(c)) {
1058 printf(" %10s - %s\n", c.name, c.longname);
1059 }
1060 }
1061}
1062
1063// Print the command usage help to stderr.
1064static void showHelp(const char *cmd)
1065{
1066 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1067 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001068 " -a appname enable app-level tracing for a comma "
Daniel Colascione519a0792018-02-09 20:05:39 -08001069 "separated list of cmdlines; * is a wildcard matching any process\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001070 " -b N use a trace buffer size of N KB\n"
1071 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001072 " -f filename use the categories written in a file as space-separated\n"
1073 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001074 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001075 " -n ignore signals\n"
1076 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001077 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001078 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001079 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001080 " --async_dump dump the current contents of circular trace buffer\n"
1081 " --async_stop stop tracing and dump the current contents of circular\n"
1082 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001083 " --stream stream trace to stdout as it enters the trace buffer\n"
1084 " Note: this can take significant CPU time, and is best\n"
1085 " used for measuring things that are not affected by\n"
1086 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001087 " --list_categories\n"
1088 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001089 " -o filename write the trace to the specified file instead\n"
1090 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001091 );
1092}
1093
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001094bool findTraceFiles()
1095{
1096 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1097 static const std::string tracefs_path = "/sys/kernel/tracing/";
1098 static const std::string trace_file = "trace_marker";
1099
1100 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1101 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1102
1103 if (!tracefs && !debugfs) {
1104 fprintf(stderr, "Error: Did not find trace folder\n");
1105 return false;
1106 }
1107
1108 if (tracefs) {
1109 g_traceFolder = tracefs_path;
1110 } else {
1111 g_traceFolder = debugfs_path;
1112 }
1113
1114 return true;
1115}
1116
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001117int main(int argc, char **argv)
1118{
1119 bool async = false;
1120 bool traceStart = true;
1121 bool traceStop = true;
1122 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001123 bool traceStream = false;
Hector Dearman11845782018-03-08 14:35:44 +00001124 bool onlyUserspace = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001125
1126 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1127 showHelp(argv[0]);
1128 exit(0);
1129 }
1130
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001131 if (!findTraceFiles()) {
1132 fprintf(stderr, "No trace folder found\n");
1133 exit(-1);
1134 }
1135
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001136 for (;;) {
1137 int ret;
1138 int option_index = 0;
1139 static struct option long_options[] = {
Hector Dearman11845782018-03-08 14:35:44 +00001140 {"async_start", no_argument, 0, 0 },
1141 {"async_stop", no_argument, 0, 0 },
1142 {"async_dump", no_argument, 0, 0 },
1143 {"only_userspace", no_argument, 0, 0 },
1144 {"list_categories", no_argument, 0, 0 },
1145 {"stream", no_argument, 0, 0 },
1146 { 0, 0, 0, 0 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001147 };
1148
John Reck40b26b42016-03-30 09:44:36 -07001149 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001150 long_options, &option_index);
1151
1152 if (ret < 0) {
1153 for (int i = optind; i < argc; i++) {
1154 if (!setCategoryEnable(argv[i], true)) {
1155 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1156 exit(1);
1157 }
1158 }
1159 break;
1160 }
1161
1162 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001163 case 'a':
1164 g_debugAppCmdLine = optarg;
1165 break;
1166
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001167 case 'b':
1168 g_traceBufferSizeKB = atoi(optarg);
1169 break;
1170
1171 case 'c':
1172 g_traceOverwrite = true;
1173 break;
1174
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001175 case 'f':
1176 g_categoriesFile = optarg;
1177 break;
1178
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001179 case 'k':
1180 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001181 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001182
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001183 case 'n':
1184 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001185 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001186
1187 case 's':
1188 g_initialSleepSecs = atoi(optarg);
1189 break;
1190
1191 case 't':
1192 g_traceDurationSeconds = atoi(optarg);
1193 break;
1194
1195 case 'z':
1196 g_compress = true;
1197 break;
1198
John Reck40b26b42016-03-30 09:44:36 -07001199 case 'o':
1200 g_outputFile = optarg;
1201 break;
1202
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001203 case 0:
1204 if (!strcmp(long_options[option_index].name, "async_start")) {
1205 async = true;
1206 traceStop = false;
1207 traceDump = false;
1208 g_traceOverwrite = true;
1209 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1210 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001211 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001212 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1213 async = true;
1214 traceStart = false;
1215 traceStop = false;
Hector Dearman11845782018-03-08 14:35:44 +00001216 } else if (!strcmp(long_options[option_index].name, "only_userspace")) {
1217 onlyUserspace = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001218 } else if (!strcmp(long_options[option_index].name, "stream")) {
1219 traceStream = true;
1220 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001221 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1222 listSupportedCategories();
1223 exit(0);
1224 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001225 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001226
1227 default:
1228 fprintf(stderr, "\n");
1229 showHelp(argv[0]);
1230 exit(-1);
1231 break;
1232 }
1233 }
1234
Hector Dearman11845782018-03-08 14:35:44 +00001235 if (onlyUserspace) {
1236 if (!async || !(traceStart || traceStop)) {
1237 fprintf(stderr, "--only_userspace can only be used with "
1238 "--async_start or --async_stop\n");
1239 exit(1);
1240 }
1241 }
1242
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001243 registerSigHandler();
1244
1245 if (g_initialSleepSecs > 0) {
1246 sleep(g_initialSleepSecs);
1247 }
1248
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001249 bool ok = true;
Hector Dearman11845782018-03-08 14:35:44 +00001250
Wei Wang5b73b742018-03-08 13:33:12 -08001251 if (traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001252 ok &= setUpUserspaceTracing();
1253 }
1254
1255 if (ok && traceStart && !onlyUserspace) {
1256 ok &= setUpKernelTracing();
Wei Wang5b73b742018-03-08 13:33:12 -08001257 ok &= startTrace();
1258 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001259
1260 if (ok && traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001261
1262 if (!traceStream && !onlyUserspace) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001263 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001264 fflush(stdout);
1265 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001266
1267 // We clear the trace after starting it because tracing gets enabled for
1268 // each CPU individually in the kernel. Having the beginning of the trace
1269 // contain entries from only one CPU can cause "begin" entries without a
1270 // matching "end" entry to show up if a task gets migrated from one CPU to
1271 // another.
Hector Dearman11845782018-03-08 14:35:44 +00001272 if (!onlyUserspace)
1273 ok = clearTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001274
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001275 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001276 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001277 // Sleep to allow the trace to be captured.
1278 struct timespec timeLeft;
1279 timeLeft.tv_sec = g_traceDurationSeconds;
1280 timeLeft.tv_nsec = 0;
1281 do {
1282 if (g_traceAborted) {
1283 break;
1284 }
1285 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1286 }
Martijn Coenend9535872015-11-26 10:00:55 +01001287
1288 if (traceStream) {
1289 streamTrace();
1290 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001291 }
1292
1293 // Stop the trace and restore the default settings.
Hector Dearman11845782018-03-08 14:35:44 +00001294 if (traceStop && !onlyUserspace)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001295 stopTrace();
1296
Hector Dearman11845782018-03-08 14:35:44 +00001297 if (ok && traceDump && !onlyUserspace) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001298 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001299 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001300 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001301 int outFd = STDOUT_FILENO;
1302 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001303 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001304 }
1305 if (outFd == -1) {
1306 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1307 } else {
1308 dprintf(outFd, "TRACE:\n");
1309 dumpTrace(outFd);
1310 if (g_outputFile) {
1311 close(outFd);
1312 }
1313 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001314 } else {
1315 printf("\ntrace aborted.\n");
1316 fflush(stdout);
1317 }
1318 clearTrace();
1319 } else if (!ok) {
1320 fprintf(stderr, "unable to start tracing\n");
1321 }
1322
1323 // Reset the trace buffer size to 1.
Hector Dearman11845782018-03-08 14:35:44 +00001324 if (traceStop) {
1325 cleanUpUserspaceTracing();
1326 if (!onlyUserspace)
1327 cleanUpKernelTracing();
1328 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001329
1330 return g_traceAborted ? 1 : 0;
1331}