blob: 5d21f6a5596f712a5f323acb26724f96738e83b4 [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" },
Martijn Coenen7f3d7a22017-05-26 09:50:55 -0700208 { OPT, "events/binder/binder_set_priority/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700209 } },
210 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800211 { OPT, "events/binder/binder_lock/enable" },
212 { OPT, "events/binder/binder_locked/enable" },
213 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700214 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200215 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800216 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200217 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800218};
219
220/* Command line options */
221static int g_traceDurationSeconds = 5;
222static bool g_traceOverwrite = false;
223static int g_traceBufferSizeKB = 2048;
224static bool g_compress = false;
225static bool g_nohup = false;
226static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900227static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700228static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700229static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700230static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800231
232/* Global state */
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700233static bool g_tracePdx = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800234static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700235static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800236static std::string g_traceFolder;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800237
238/* Sys file paths */
239static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800240 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800241
242static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800243 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800244
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700245#if 0
246// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700247static const char* k_traceCmdlineSizePath =
248 "saved_cmdlines_size";
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700249#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700250
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800251static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800252 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800253
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700254static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800255 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700256
257static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800258 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700259
260static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800261 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700262
263static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800264 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700265
266static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800267 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700268
269static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800270 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700271
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700272static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800273 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700274
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800275static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800276 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800277
278static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800279 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800280
Martijn Coenend9535872015-11-26 10:00:55 +0100281static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800282 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100283
John Reck469a1942015-03-26 15:31:35 -0700284static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800285 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700286
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800287// Check whether a file exists.
288static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800289 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800290}
291
292// Check whether a file is writable.
293static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800294 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800295}
296
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700297// Truncate a file.
298static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800299{
Jamie Gennis43122e72013-03-21 14:06:31 -0700300 // This uses creat rather than truncate because some of the debug kernel
301 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
302 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800303 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700304 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800305 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700306 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700307 return false;
308 }
309
Jamie Gennis43122e72013-03-21 14:06:31 -0700310 close(traceFD);
311
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700312 return true;
313}
314
315static bool _writeStr(const char* filename, const char* str, int flags)
316{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800317 std::string fullFilename = g_traceFolder + filename;
318 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800319 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800320 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800321 strerror(errno), errno);
322 return false;
323 }
324
325 bool ok = true;
326 ssize_t len = strlen(str);
327 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800328 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800329 strerror(errno), errno);
330 ok = false;
331 }
332
333 close(fd);
334
335 return ok;
336}
337
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700338// Write a string to a file, returning true if the write was successful.
339static bool writeStr(const char* filename, const char* str)
340{
341 return _writeStr(filename, str, O_WRONLY);
342}
343
344// Append a string to a file, returning true if the write was successful.
345static bool appendStr(const char* filename, const char* str)
346{
347 return _writeStr(filename, str, O_APPEND|O_WRONLY);
348}
349
John Reck469a1942015-03-26 15:31:35 -0700350static void writeClockSyncMarker()
351{
352 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200353 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800354 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200355 if (fd == -1) {
356 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
357 strerror(errno), errno);
358 return;
359 }
John Reck469a1942015-03-26 15:31:35 -0700360 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200361
362 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
363 if (write(fd, buffer, len) != len) {
364 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
365 }
366
367 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
368 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
369 if (write(fd, buffer, len) != len) {
370 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
371 }
372
373 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700374}
375
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800376// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
377// file.
378static bool setKernelOptionEnable(const char* filename, bool enable)
379{
380 return writeStr(filename, enable ? "1" : "0");
381}
382
383// Check whether the category is supported on the device with the current
384// rootness. A category is supported only if all its required /sys/ files are
385// writable and if enabling the category will enable one or more tracing tags
386// or /sys/ files.
387static bool isCategorySupported(const TracingCategory& category)
388{
sergeyvdb404152016-05-02 19:26:07 -0700389 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700390 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700391 }
392
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700393 if (strcmp(category.name, k_pdxServiceCategory) == 0) {
394 return true;
395 }
396
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800397 bool ok = category.tags != 0;
398 for (int i = 0; i < MAX_SYS_FILES; i++) {
399 const char* path = category.sysfiles[i].path;
400 bool req = category.sysfiles[i].required == REQ;
401 if (path != NULL) {
402 if (req) {
403 if (!fileIsWritable(path)) {
404 return false;
405 } else {
406 ok = true;
407 }
408 } else {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800409 ok = true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800410 }
411 }
412 }
413 return ok;
414}
415
416// Check whether the category would be supported on the device if the user
417// were root. This function assumes that root is able to write to any file
418// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700419// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800420static bool isCategorySupportedForRoot(const TracingCategory& category)
421{
422 bool ok = category.tags != 0;
423 for (int i = 0; i < MAX_SYS_FILES; i++) {
424 const char* path = category.sysfiles[i].path;
425 bool req = category.sysfiles[i].required == REQ;
426 if (path != NULL) {
427 if (req) {
428 if (!fileExists(path)) {
429 return false;
430 } else {
431 ok = true;
432 }
433 } else {
434 ok |= fileExists(path);
435 }
436 }
437 }
438 return ok;
439}
440
441// Enable or disable overwriting of the kernel trace buffers. Disabling this
442// will cause tracing to stop once the trace buffers have filled up.
443static bool setTraceOverwriteEnable(bool enable)
444{
445 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
446}
447
Carmen Jacksonab1118e2018-05-22 10:29:47 -0700448// Set the user initiated trace property
449static bool setUserInitiatedTraceProperty(bool enable)
450{
451 if (!android::base::SetProperty(k_userInitiatedTraceProperty, enable ? "1" : "")) {
452 fprintf(stderr, "error setting user initiated strace system property\n");
453 return false;
454 }
455 return true;
456}
457
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800458// Enable or disable kernel tracing.
459static bool setTracingEnabled(bool enable)
460{
461 return setKernelOptionEnable(k_tracingOnPath, enable);
462}
463
464// Clear the contents of the kernel trace.
465static bool clearTrace()
466{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700467 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800468}
469
470// Set the size of the kernel's trace buffer in kilobytes.
471static bool setTraceBufferSizeKB(int size)
472{
473 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800474 if (size < 1) {
475 size = 1;
476 }
477 snprintf(str, 32, "%d", size);
478 return writeStr(k_traceBufferSizePath, str);
479}
480
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700481#if 0
482// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700483// Set the default size of cmdline hashtable
484static bool setCmdlineSize()
485{
Joel Fernandesce964f22017-06-06 12:20:29 -0700486 if (fileExists(k_traceCmdlineSizePath)) {
487 return writeStr(k_traceCmdlineSizePath, "8192");
488 }
489 return true;
Joel Fernandesed80bd02017-06-02 10:19:28 -0700490}
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700491#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700492
Carmen Jacksonea826792017-05-05 11:42:32 -0700493// Set the clock to the best available option while tracing. Use 'boot' if it's
494// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700495// Any write to the trace_clock sysfs file will reset the buffer, so only
496// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700497static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800498{
Carmen Jacksonea826792017-05-05 11:42:32 -0700499 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
500 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
501 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700502
Carmen Jacksonea826792017-05-05 11:42:32 -0700503 std::string newClock;
504 if (clockStr.find("boot") != std::string::npos) {
505 newClock = "boot";
506 } else if (clockStr.find("mono") != std::string::npos) {
507 newClock = "mono";
508 } else {
509 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700510 }
511
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700512 size_t begin = clockStr.find('[') + 1;
513 size_t end = clockStr.find(']');
Carmen Jacksonea826792017-05-05 11:42:32 -0700514 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
515 return true;
516 }
517 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800518}
519
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700520static bool setPrintTgidEnableIfPresent(bool enable)
521{
522 if (fileExists(k_printTgidPath)) {
523 return setKernelOptionEnable(k_printTgidPath, enable);
524 }
525 return true;
526}
527
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800528// Poke all the binder-enabled processes in the system to get them to re-read
529// their system properties.
530static bool pokeBinderServices()
531{
532 sp<IServiceManager> sm = defaultServiceManager();
533 Vector<String16> services = sm->listServices();
534 for (size_t i = 0; i < services.size(); i++) {
535 sp<IBinder> obj = sm->checkService(services[i]);
536 if (obj != NULL) {
537 Parcel data;
538 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
539 NULL, 0) != OK) {
540 if (false) {
541 // XXX: For some reason this fails on tablets trying to
542 // poke the "phone" service. It's not clear whether some
543 // are expected to fail.
544 String8 svc(services[i]);
545 fprintf(stderr, "error poking binder service %s\n",
546 svc.string());
547 return false;
548 }
549 }
550 }
551 }
552 return true;
553}
554
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100555// Poke all the HAL processes in the system to get them to re-read
556// their system properties.
557static void pokeHalServices()
558{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100559 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100560 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100561 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100562 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100563
564 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800565
566 if (sm == nullptr) {
567 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
568 return;
569 }
570
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800571 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100572 for (size_t i = 0; i < interfaces.size(); i++) {
573 string fqInstanceName = interfaces[i];
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700574 string::size_type n = fqInstanceName.find('/');
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100575 if (n == std::string::npos || interfaces[i].size() == n+1)
576 continue;
577 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
578 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100579 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
580 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100581 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100582 continue;
583 }
Carmen Jackson73206122017-04-18 15:37:57 -0700584
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100585 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700586 if (interface == nullptr) {
587 // ignore
588 continue;
589 }
590
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100591 auto notifyRet = interface->notifySyspropsChanged();
592 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100593 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800594 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100595 }
596 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800597 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100598 // TODO(b/34242478) fix this when we determine the correct ACL
599 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800600 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100601}
602
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800603// Set the trace tags that userland tracing uses, and poke the running
604// processes to pick up the new value.
605static bool setTagsProperty(uint64_t tags)
606{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700607 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
608 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800609 fprintf(stderr, "error setting trace tags system property\n");
610 return false;
611 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700612 return true;
613}
614
sergeyv4144eff2016-04-28 11:40:04 -0700615static void clearAppProperties()
616{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700617 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700618 fprintf(stderr, "failed to clear system property: %s",
619 k_traceAppsNumberProperty);
620 }
621}
622
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700623// Set the system property that indicates which apps should perform
624// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700625static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700626{
sergeyv4144eff2016-04-28 11:40:04 -0700627 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700628 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700629 while (start != NULL) {
sergeyv4144eff2016-04-28 11:40:04 -0700630 char* end = strchr(start, ',');
631 if (end != NULL) {
632 *end = '\0';
633 end++;
634 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700635 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
636 if (!android::base::SetProperty(key, start)) {
637 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700638 clearAppProperties();
639 return false;
640 }
641 start = end;
642 i++;
643 }
644
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700645 std::string value = android::base::StringPrintf("%d", i);
646 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
647 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700648 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700649 return false;
650 }
651 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800652}
653
654// Disable all /sys/ enable files.
655static bool disableKernelTraceEvents() {
656 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700657 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800658 const TracingCategory &c = k_categories[i];
659 for (int j = 0; j < MAX_SYS_FILES; j++) {
660 const char* path = c.sysfiles[j].path;
661 if (path != NULL && fileIsWritable(path)) {
662 ok &= setKernelOptionEnable(path, false);
663 }
664 }
665 }
666 return ok;
667}
668
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700669// Verify that the comma separated list of functions are being traced by the
670// kernel.
671static bool verifyKernelTraceFuncs(const char* funcs)
672{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100673 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800674 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100675 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700676 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100677 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700678 }
679
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100680 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700681
682 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100683 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700684 bool ok = true;
685 char* myFuncs = strdup(funcs);
686 char* func = strtok(myFuncs, ",");
687 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100688 if (!strchr(func, '*')) {
689 String8 fancyFunc = String8::format("\n%s\n", func);
690 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
691 if (!found || func[0] == '\0') {
692 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
693 "to trace.\n", func);
694 ok = false;
695 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700696 }
697 func = strtok(NULL, ",");
698 }
699 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700700 return ok;
701}
702
703// Set the comma separated list of functions that the kernel is to trace.
704static bool setKernelTraceFuncs(const char* funcs)
705{
706 bool ok = true;
707
708 if (funcs == NULL || funcs[0] == '\0') {
709 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700710 if (fileIsWritable(k_currentTracerPath)) {
711 ok &= writeStr(k_currentTracerPath, "nop");
712 }
713 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700714 ok &= truncateFile(k_ftraceFilterPath);
715 }
716 } else {
717 // Enable kernel function tracing.
718 ok &= writeStr(k_currentTracerPath, "function_graph");
719 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
720 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
721 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
722 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
723
724 // Set the requested filter functions.
725 ok &= truncateFile(k_ftraceFilterPath);
726 char* myFuncs = strdup(funcs);
727 char* func = strtok(myFuncs, ",");
728 while (func) {
729 ok &= appendStr(k_ftraceFilterPath, func);
730 func = strtok(NULL, ",");
731 }
732 free(myFuncs);
733
734 // Verify that the set functions are being traced.
735 if (ok) {
736 ok &= verifyKernelTraceFuncs(funcs);
737 }
738 }
739
740 return ok;
741}
742
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900743static bool setCategoryEnable(const char* name, bool enable)
744{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700745 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900746 const TracingCategory& c = k_categories[i];
747 if (strcmp(name, c.name) == 0) {
748 if (isCategorySupported(c)) {
749 g_categoryEnables[i] = enable;
750 return true;
751 } else {
752 if (isCategorySupportedForRoot(c)) {
753 fprintf(stderr, "error: category \"%s\" requires root "
754 "privileges.\n", name);
755 } else {
756 fprintf(stderr, "error: category \"%s\" is not supported "
757 "on this device.\n", name);
758 }
759 return false;
760 }
761 }
762 }
763 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
764 return false;
765}
766
767static bool setCategoriesEnableFromFile(const char* categories_file)
768{
769 if (!categories_file) {
770 return true;
771 }
772 Tokenizer* tokenizer = NULL;
773 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
774 return false;
775 }
776 bool ok = true;
777 while (!tokenizer->isEol()) {
778 String8 token = tokenizer->nextToken(" ");
779 if (token.isEmpty()) {
780 tokenizer->skipDelimiters(" ");
781 continue;
782 }
783 ok &= setCategoryEnable(token.string(), true);
784 }
785 delete tokenizer;
786 return ok;
787}
788
Hector Dearman11845782018-03-08 14:35:44 +0000789static bool setUpUserspaceTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800790{
791 bool ok = true;
792
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800793 // Set up the tags property.
794 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700795 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800796 if (g_categoryEnables[i]) {
797 const TracingCategory &c = k_categories[i];
798 tags |= c.tags;
799 }
800 }
801 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700802
803 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700804 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700805 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
806 coreServicesTagEnabled = g_categoryEnables[i];
807 }
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700808
809 // Set whether to poke PDX services in this session.
810 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
811 g_tracePdx = g_categoryEnables[i];
812 }
sergeyvdb404152016-05-02 19:26:07 -0700813 }
814
815 std::string packageList(g_debugAppCmdLine);
816 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700817 if (!packageList.empty()) {
818 packageList += ",";
819 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700820 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700821 }
Dan Austin09a79872016-05-31 13:27:03 -0700822 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700823 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100824 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800825
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700826 if (g_tracePdx) {
827 ok &= ServiceUtility::PokeServices();
828 }
829
Hector Dearman11845782018-03-08 14:35:44 +0000830 return ok;
831}
832
833static void cleanUpUserspaceTracing()
834{
835 setTagsProperty(0);
836 clearAppProperties();
837 pokeBinderServices();
838
839 if (g_tracePdx) {
840 ServiceUtility::PokeServices();
841 }
842}
843
844
845// Set all the kernel tracing settings to the desired state for this trace
846// capture.
847static bool setUpKernelTracing()
848{
849 bool ok = true;
850
Carmen Jacksonab1118e2018-05-22 10:29:47 -0700851 ok &= setUserInitiatedTraceProperty(true);
852
Hector Dearman11845782018-03-08 14:35:44 +0000853 // Set up the tracing options.
854 ok &= setCategoriesEnableFromFile(g_categoriesFile);
855 ok &= setTraceOverwriteEnable(g_traceOverwrite);
856 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
857 // TODO: Re-enable after stabilization
858 //ok &= setCmdlineSize();
859 ok &= setClock();
860 ok &= setPrintTgidEnableIfPresent(true);
861 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
862
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800863 // Disable all the sysfs enables. This is done as a separate loop from
864 // the enables to allow the same enable to exist in multiple categories.
865 ok &= disableKernelTraceEvents();
866
867 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700868 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800869 if (g_categoryEnables[i]) {
870 const TracingCategory &c = k_categories[i];
871 for (int j = 0; j < MAX_SYS_FILES; j++) {
872 const char* path = c.sysfiles[j].path;
873 bool required = c.sysfiles[j].required == REQ;
874 if (path != NULL) {
875 if (fileIsWritable(path)) {
876 ok &= setKernelOptionEnable(path, true);
877 } else if (required) {
878 fprintf(stderr, "error writing file %s\n", path);
879 ok = false;
880 }
881 }
882 }
883 }
884 }
885
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800886 return ok;
887}
888
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700889// Reset all the kernel tracing settings to their default state.
Hector Dearman11845782018-03-08 14:35:44 +0000890static void cleanUpKernelTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800891{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800892 // Disable all tracing that we're able to.
893 disableKernelTraceEvents();
894
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800895 // Set the options back to their defaults.
896 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700897 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700898 setPrintTgidEnableIfPresent(false);
899 setKernelTraceFuncs(NULL);
Carmen Jacksonab1118e2018-05-22 10:29:47 -0700900 setUserInitiatedTraceProperty(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700901}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800902
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700903// Enable tracing in the kernel.
904static bool startTrace()
905{
906 return setTracingEnabled(true);
907}
908
909// Disable tracing in the kernel.
910static void stopTrace()
911{
912 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800913}
914
Martijn Coenend9535872015-11-26 10:00:55 +0100915// Read data from the tracing pipe and forward to stdout
916static void streamTrace()
917{
918 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800919 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100920 if (traceFD == -1) {
921 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
922 strerror(errno), errno);
923 return;
924 }
925 while (!g_traceAborted) {
926 ssize_t bytes_read = read(traceFD, trace_data, 4096);
927 if (bytes_read > 0) {
928 write(STDOUT_FILENO, trace_data, bytes_read);
929 fflush(stdout);
930 } else {
931 if (!g_traceAborted) {
932 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
933 bytes_read, errno, strerror(errno));
934 }
935 break;
936 }
937 }
938}
939
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800940// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700941static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800942{
John Reck6c8ac922016-03-28 11:25:30 -0700943 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800944 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800945 if (traceFD == -1) {
946 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
947 strerror(errno), errno);
948 return;
949 }
950
951 if (g_compress) {
952 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800953 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700954
955 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800956 if (result != Z_OK) {
957 fprintf(stderr, "error initializing zlib: %d\n", result);
958 close(traceFD);
959 return;
960 }
961
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700962 constexpr size_t bufSize = 64*1024;
963 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
964 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
965 if (!in || !out) {
966 fprintf(stderr, "couldn't allocate buffers\n");
967 close(traceFD);
968 return;
969 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800970
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700971 int flush = Z_NO_FLUSH;
972
973 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800974 zs.avail_out = bufSize;
975
976 do {
977
978 if (zs.avail_in == 0) {
979 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700980 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800981 if (result < 0) {
982 fprintf(stderr, "error reading trace: %s (%d)\n",
983 strerror(errno), errno);
984 result = Z_STREAM_END;
985 break;
986 } else if (result == 0) {
987 flush = Z_FINISH;
988 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700989 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800990 zs.avail_in = result;
991 }
992 }
993
994 if (zs.avail_out == 0) {
995 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700996 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800997 if ((size_t)result < bufSize) {
998 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
999 strerror(errno), errno);
1000 result = Z_STREAM_END; // skip deflate error message
1001 zs.avail_out = bufSize; // skip the final write
1002 break;
1003 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001004 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001005 zs.avail_out = bufSize;
1006 }
1007
1008 } while ((result = deflate(&zs, flush)) == Z_OK);
1009
1010 if (result != Z_STREAM_END) {
1011 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
1012 }
1013
1014 if (zs.avail_out < bufSize) {
1015 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -07001016 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001017 if ((size_t)result < bytes) {
1018 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1019 strerror(errno), errno);
1020 }
1021 }
1022
1023 result = deflateEnd(&zs);
1024 if (result != Z_OK) {
1025 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1026 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001027 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001028 char buf[4096];
1029 ssize_t rc;
1030 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1031 if (!android::base::WriteFully(outFd, buf, rc)) {
1032 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1033 break;
1034 }
1035 }
1036 if (rc == -1) {
1037 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001038 }
1039 }
1040
1041 close(traceFD);
1042}
1043
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001044static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001045{
1046 if (!g_nohup) {
1047 g_traceAborted = true;
1048 }
1049}
1050
1051static void registerSigHandler()
1052{
1053 struct sigaction sa;
1054 sigemptyset(&sa.sa_mask);
1055 sa.sa_flags = 0;
1056 sa.sa_handler = handleSignal;
1057 sigaction(SIGHUP, &sa, NULL);
1058 sigaction(SIGINT, &sa, NULL);
1059 sigaction(SIGQUIT, &sa, NULL);
1060 sigaction(SIGTERM, &sa, NULL);
1061}
1062
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001063static void listSupportedCategories()
1064{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001065 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001066 const TracingCategory& c = k_categories[i];
1067 if (isCategorySupported(c)) {
1068 printf(" %10s - %s\n", c.name, c.longname);
1069 }
1070 }
1071}
1072
1073// Print the command usage help to stderr.
1074static void showHelp(const char *cmd)
1075{
1076 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1077 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001078 " -a appname enable app-level tracing for a comma "
Daniel Colascione519a0792018-02-09 20:05:39 -08001079 "separated list of cmdlines; * is a wildcard matching any process\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001080 " -b N use a trace buffer size of N KB\n"
1081 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001082 " -f filename use the categories written in a file as space-separated\n"
1083 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001084 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001085 " -n ignore signals\n"
1086 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001087 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001088 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001089 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001090 " --async_dump dump the current contents of circular trace buffer\n"
1091 " --async_stop stop tracing and dump the current contents of circular\n"
1092 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001093 " --stream stream trace to stdout as it enters the trace buffer\n"
1094 " Note: this can take significant CPU time, and is best\n"
1095 " used for measuring things that are not affected by\n"
1096 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001097 " --list_categories\n"
1098 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001099 " -o filename write the trace to the specified file instead\n"
1100 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001101 );
1102}
1103
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001104bool findTraceFiles()
1105{
1106 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1107 static const std::string tracefs_path = "/sys/kernel/tracing/";
1108 static const std::string trace_file = "trace_marker";
1109
1110 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1111 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1112
1113 if (!tracefs && !debugfs) {
1114 fprintf(stderr, "Error: Did not find trace folder\n");
1115 return false;
1116 }
1117
1118 if (tracefs) {
1119 g_traceFolder = tracefs_path;
1120 } else {
1121 g_traceFolder = debugfs_path;
1122 }
1123
1124 return true;
1125}
1126
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001127int main(int argc, char **argv)
1128{
1129 bool async = false;
1130 bool traceStart = true;
1131 bool traceStop = true;
1132 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001133 bool traceStream = false;
Hector Dearman11845782018-03-08 14:35:44 +00001134 bool onlyUserspace = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001135
1136 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1137 showHelp(argv[0]);
1138 exit(0);
1139 }
1140
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001141 if (!findTraceFiles()) {
1142 fprintf(stderr, "No trace folder found\n");
1143 exit(-1);
1144 }
1145
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001146 for (;;) {
1147 int ret;
1148 int option_index = 0;
1149 static struct option long_options[] = {
Hector Dearman11845782018-03-08 14:35:44 +00001150 {"async_start", no_argument, 0, 0 },
1151 {"async_stop", no_argument, 0, 0 },
1152 {"async_dump", no_argument, 0, 0 },
1153 {"only_userspace", no_argument, 0, 0 },
1154 {"list_categories", no_argument, 0, 0 },
1155 {"stream", no_argument, 0, 0 },
1156 { 0, 0, 0, 0 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001157 };
1158
John Reck40b26b42016-03-30 09:44:36 -07001159 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001160 long_options, &option_index);
1161
1162 if (ret < 0) {
1163 for (int i = optind; i < argc; i++) {
1164 if (!setCategoryEnable(argv[i], true)) {
1165 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1166 exit(1);
1167 }
1168 }
1169 break;
1170 }
1171
1172 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001173 case 'a':
1174 g_debugAppCmdLine = optarg;
1175 break;
1176
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001177 case 'b':
1178 g_traceBufferSizeKB = atoi(optarg);
1179 break;
1180
1181 case 'c':
1182 g_traceOverwrite = true;
1183 break;
1184
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001185 case 'f':
1186 g_categoriesFile = optarg;
1187 break;
1188
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001189 case 'k':
1190 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001191 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001192
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001193 case 'n':
1194 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001195 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001196
1197 case 's':
1198 g_initialSleepSecs = atoi(optarg);
1199 break;
1200
1201 case 't':
1202 g_traceDurationSeconds = atoi(optarg);
1203 break;
1204
1205 case 'z':
1206 g_compress = true;
1207 break;
1208
John Reck40b26b42016-03-30 09:44:36 -07001209 case 'o':
1210 g_outputFile = optarg;
1211 break;
1212
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001213 case 0:
1214 if (!strcmp(long_options[option_index].name, "async_start")) {
1215 async = true;
1216 traceStop = false;
1217 traceDump = false;
1218 g_traceOverwrite = true;
1219 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1220 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001221 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001222 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1223 async = true;
1224 traceStart = false;
1225 traceStop = false;
Hector Dearman11845782018-03-08 14:35:44 +00001226 } else if (!strcmp(long_options[option_index].name, "only_userspace")) {
1227 onlyUserspace = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001228 } else if (!strcmp(long_options[option_index].name, "stream")) {
1229 traceStream = true;
1230 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001231 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1232 listSupportedCategories();
1233 exit(0);
1234 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001235 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001236
1237 default:
1238 fprintf(stderr, "\n");
1239 showHelp(argv[0]);
1240 exit(-1);
1241 break;
1242 }
1243 }
1244
Hector Dearman11845782018-03-08 14:35:44 +00001245 if (onlyUserspace) {
1246 if (!async || !(traceStart || traceStop)) {
1247 fprintf(stderr, "--only_userspace can only be used with "
1248 "--async_start or --async_stop\n");
1249 exit(1);
1250 }
1251 }
1252
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001253 registerSigHandler();
1254
1255 if (g_initialSleepSecs > 0) {
1256 sleep(g_initialSleepSecs);
1257 }
1258
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001259 bool ok = true;
Hector Dearman11845782018-03-08 14:35:44 +00001260
Wei Wang5b73b742018-03-08 13:33:12 -08001261 if (traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001262 ok &= setUpUserspaceTracing();
1263 }
1264
1265 if (ok && traceStart && !onlyUserspace) {
1266 ok &= setUpKernelTracing();
Wei Wang5b73b742018-03-08 13:33:12 -08001267 ok &= startTrace();
1268 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001269
1270 if (ok && traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001271
1272 if (!traceStream && !onlyUserspace) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001273 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001274 fflush(stdout);
1275 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001276
1277 // We clear the trace after starting it because tracing gets enabled for
1278 // each CPU individually in the kernel. Having the beginning of the trace
1279 // contain entries from only one CPU can cause "begin" entries without a
1280 // matching "end" entry to show up if a task gets migrated from one CPU to
1281 // another.
Hector Dearman11845782018-03-08 14:35:44 +00001282 if (!onlyUserspace)
1283 ok = clearTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001284
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001285 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001286 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001287 // Sleep to allow the trace to be captured.
1288 struct timespec timeLeft;
1289 timeLeft.tv_sec = g_traceDurationSeconds;
1290 timeLeft.tv_nsec = 0;
1291 do {
1292 if (g_traceAborted) {
1293 break;
1294 }
1295 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1296 }
Martijn Coenend9535872015-11-26 10:00:55 +01001297
1298 if (traceStream) {
1299 streamTrace();
1300 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001301 }
1302
1303 // Stop the trace and restore the default settings.
Hector Dearman11845782018-03-08 14:35:44 +00001304 if (traceStop && !onlyUserspace)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001305 stopTrace();
1306
Hector Dearman11845782018-03-08 14:35:44 +00001307 if (ok && traceDump && !onlyUserspace) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001308 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001309 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001310 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001311 int outFd = STDOUT_FILENO;
1312 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001313 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001314 }
1315 if (outFd == -1) {
1316 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1317 } else {
1318 dprintf(outFd, "TRACE:\n");
1319 dumpTrace(outFd);
1320 if (g_outputFile) {
1321 close(outFd);
1322 }
1323 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001324 } else {
1325 printf("\ntrace aborted.\n");
1326 fflush(stdout);
1327 }
1328 clearTrace();
1329 } else if (!ok) {
1330 fprintf(stderr, "unable to start tracing\n");
1331 }
1332
1333 // Reset the trace buffer size to 1.
Hector Dearman11845782018-03-08 14:35:44 +00001334 if (traceStop) {
1335 cleanUpUserspaceTracing();
1336 if (!onlyUserspace)
1337 cleanUpKernelTracing();
1338 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001339
1340 return g_traceAborted ? 1 : 0;
1341}