blob: fe9dd568fce3ec0bfed505888a9775893b3174f8 [file] [log] [blame]
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Paul Lawrence2cd93cc2017-01-17 09:50:18 -080017#define LOG_TAG "atrace"
John Reck40b26b42016-03-30 09:44:36 -070018
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080019#include <errno.h>
20#include <fcntl.h>
21#include <getopt.h>
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070022#include <inttypes.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080023#include <signal.h>
24#include <stdarg.h>
25#include <stdbool.h>
26#include <stdio.h>
27#include <stdlib.h>
Elliott Hughes3da5d232015-01-25 08:35:20 -080028#include <string.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080029#include <time.h>
Martijn Coenend9535872015-11-26 10:00:55 +010030#include <unistd.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080031#include <zlib.h>
32
Carmen Jacksonea826792017-05-05 11:42:32 -070033#include <fstream>
Elliott Hughesa252f4d2016-07-21 17:12:15 -070034#include <memory>
35
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080036#include <binder/IBinder.h>
37#include <binder/IServiceManager.h>
38#include <binder/Parcel.h>
39
Martijn Coenenee9b97e2016-11-16 16:00:26 +010040#include <android/hidl/manager/1.0/IServiceManager.h>
41#include <hidl/ServiceManagement.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080042
Corey Tabakaa6c0a722017-05-31 16:37:40 -070043#include <pdx/default_transport/service_utility.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080044#include <utils/String8.h>
John Reck469a1942015-03-26 15:31:35 -070045#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +090046#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080047#include <utils/Trace.h>
Stephane Gasparinid8419c22016-03-02 13:45:15 +010048#include <android-base/file.h>
Elliott Hughes5fd6ff62017-03-28 14:55:31 -070049#include <android-base/macros.h>
50#include <android-base/properties.h>
51#include <android-base/stringprintf.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080052
53using namespace android;
Corey Tabakaa6c0a722017-05-31 16:37:40 -070054using pdx::default_transport::ServiceUtility;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080055
Martijn Coenenee9b97e2016-11-16 16:00:26 +010056using std::string;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080057
sergeyv4144eff2016-04-28 11:40:04 -070058#define MAX_SYS_FILES 10
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080059
60const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
Carmen Jackson65ecfbb2018-05-22 10:29:47 -070061const char* k_userInitiatedTraceProperty = "debug.atrace.user_initiated";
sergeyv4144eff2016-04-28 11:40:04 -070062
63const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
64const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070065const char* k_coreServiceCategory = "core_services";
Corey Tabakaa6c0a722017-05-31 16:37:40 -070066const char* k_pdxServiceCategory = "pdx";
sergeyvdb404152016-05-02 19:26:07 -070067const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080068
69typedef enum { OPT, REQ } requiredness ;
70
71struct TracingCategory {
72 // The name identifying the category.
73 const char* name;
74
75 // A longer description of the category.
76 const char* longname;
77
78 // The userland tracing tags that the category enables.
79 uint64_t tags;
80
81 // The fname==NULL terminated list of /sys/ files that the category
82 // enables.
83 struct {
84 // Whether the file must be writable in order to enable the tracing
85 // category.
86 requiredness required;
87
88 // The path to the enable file.
89 const char* path;
90 } sysfiles[MAX_SYS_FILES];
91};
92
93/* Tracing categories */
94static const TracingCategory k_categories[] = {
John Reck732a29a2017-05-24 16:09:21 -070095 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, {
96 { OPT, "events/mdss/enable" },
Wei Wange2c10462018-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 Coenen47791e92018-03-09 09:27:32 +0100119 { "vibrator", "Vibrator", ATRACE_TAG_VIBRATOR, { } },
120 { "aidl", "AIDL calls", ATRACE_TAG_AIDL, { } },
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 Fernandes0ad0f302017-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 DuBoisafc2f972017-11-03 15:44:08 -0700158 { OPT, "events/power/clock_disable/enable" },
159 { OPT, "events/power/clock_enable/enable" },
Wei Wang391efc22018-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
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700451// Set the user initiated trace property
452static bool setUserInitiatedTraceProperty(bool enable)
453{
454 if (!android::base::SetProperty(k_userInitiatedTraceProperty, enable ? "1" : "")) {
455 fprintf(stderr, "error setting user initiated strace system property\n");
456 return false;
457 }
458 return true;
459}
460
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800461// Enable or disable kernel tracing.
462static bool setTracingEnabled(bool enable)
463{
464 return setKernelOptionEnable(k_tracingOnPath, enable);
465}
466
467// Clear the contents of the kernel trace.
468static bool clearTrace()
469{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700470 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800471}
472
473// Set the size of the kernel's trace buffer in kilobytes.
474static bool setTraceBufferSizeKB(int size)
475{
476 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800477 if (size < 1) {
478 size = 1;
479 }
480 snprintf(str, 32, "%d", size);
481 return writeStr(k_traceBufferSizePath, str);
482}
483
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700484#if 0
485// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700486// Set the default size of cmdline hashtable
487static bool setCmdlineSize()
488{
Joel Fernandesce964f22017-06-06 12:20:29 -0700489 if (fileExists(k_traceCmdlineSizePath)) {
490 return writeStr(k_traceCmdlineSizePath, "8192");
491 }
492 return true;
Joel Fernandesed80bd02017-06-02 10:19:28 -0700493}
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700494#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700495
Carmen Jacksonea826792017-05-05 11:42:32 -0700496// Set the clock to the best available option while tracing. Use 'boot' if it's
497// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700498// Any write to the trace_clock sysfs file will reset the buffer, so only
499// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700500static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800501{
Carmen Jacksonea826792017-05-05 11:42:32 -0700502 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
503 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
504 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700505
Carmen Jacksonea826792017-05-05 11:42:32 -0700506 std::string newClock;
507 if (clockStr.find("boot") != std::string::npos) {
508 newClock = "boot";
509 } else if (clockStr.find("mono") != std::string::npos) {
510 newClock = "mono";
511 } else {
512 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700513 }
514
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700515 size_t begin = clockStr.find('[') + 1;
516 size_t end = clockStr.find(']');
Carmen Jacksonea826792017-05-05 11:42:32 -0700517 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
518 return true;
519 }
520 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800521}
522
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700523static bool setPrintTgidEnableIfPresent(bool enable)
524{
525 if (fileExists(k_printTgidPath)) {
526 return setKernelOptionEnable(k_printTgidPath, enable);
527 }
528 return true;
529}
530
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800531// Poke all the binder-enabled processes in the system to get them to re-read
532// their system properties.
533static bool pokeBinderServices()
534{
535 sp<IServiceManager> sm = defaultServiceManager();
536 Vector<String16> services = sm->listServices();
537 for (size_t i = 0; i < services.size(); i++) {
538 sp<IBinder> obj = sm->checkService(services[i]);
539 if (obj != NULL) {
540 Parcel data;
541 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
542 NULL, 0) != OK) {
543 if (false) {
544 // XXX: For some reason this fails on tablets trying to
545 // poke the "phone" service. It's not clear whether some
546 // are expected to fail.
547 String8 svc(services[i]);
548 fprintf(stderr, "error poking binder service %s\n",
549 svc.string());
550 return false;
551 }
552 }
553 }
554 }
555 return true;
556}
557
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100558// Poke all the HAL processes in the system to get them to re-read
559// their system properties.
560static void pokeHalServices()
561{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100562 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100563 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100564 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100565 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100566
567 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800568
569 if (sm == nullptr) {
570 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
571 return;
572 }
573
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800574 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100575 for (size_t i = 0; i < interfaces.size(); i++) {
576 string fqInstanceName = interfaces[i];
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700577 string::size_type n = fqInstanceName.find('/');
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100578 if (n == std::string::npos || interfaces[i].size() == n+1)
579 continue;
580 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
581 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100582 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
583 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100584 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100585 continue;
586 }
Carmen Jackson73206122017-04-18 15:37:57 -0700587
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100588 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700589 if (interface == nullptr) {
590 // ignore
591 continue;
592 }
593
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100594 auto notifyRet = interface->notifySyspropsChanged();
595 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100596 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800597 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100598 }
599 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800600 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100601 // TODO(b/34242478) fix this when we determine the correct ACL
602 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800603 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100604}
605
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800606// Set the trace tags that userland tracing uses, and poke the running
607// processes to pick up the new value.
608static bool setTagsProperty(uint64_t tags)
609{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700610 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
611 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800612 fprintf(stderr, "error setting trace tags system property\n");
613 return false;
614 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700615 return true;
616}
617
sergeyv4144eff2016-04-28 11:40:04 -0700618static void clearAppProperties()
619{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700620 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700621 fprintf(stderr, "failed to clear system property: %s",
622 k_traceAppsNumberProperty);
623 }
624}
625
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700626// Set the system property that indicates which apps should perform
627// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700628static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700629{
sergeyv4144eff2016-04-28 11:40:04 -0700630 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700631 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700632 while (start != NULL) {
sergeyv4144eff2016-04-28 11:40:04 -0700633 char* end = strchr(start, ',');
634 if (end != NULL) {
635 *end = '\0';
636 end++;
637 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700638 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
639 if (!android::base::SetProperty(key, start)) {
640 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700641 clearAppProperties();
642 return false;
643 }
644 start = end;
645 i++;
646 }
647
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700648 std::string value = android::base::StringPrintf("%d", i);
649 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
650 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700651 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700652 return false;
653 }
654 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800655}
656
657// Disable all /sys/ enable files.
658static bool disableKernelTraceEvents() {
659 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700660 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800661 const TracingCategory &c = k_categories[i];
662 for (int j = 0; j < MAX_SYS_FILES; j++) {
663 const char* path = c.sysfiles[j].path;
664 if (path != NULL && fileIsWritable(path)) {
665 ok &= setKernelOptionEnable(path, false);
666 }
667 }
668 }
669 return ok;
670}
671
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700672// Verify that the comma separated list of functions are being traced by the
673// kernel.
674static bool verifyKernelTraceFuncs(const char* funcs)
675{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100676 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800677 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100678 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700679 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100680 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700681 }
682
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100683 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700684
685 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100686 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700687 bool ok = true;
688 char* myFuncs = strdup(funcs);
689 char* func = strtok(myFuncs, ",");
690 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100691 if (!strchr(func, '*')) {
692 String8 fancyFunc = String8::format("\n%s\n", func);
693 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
694 if (!found || func[0] == '\0') {
695 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
696 "to trace.\n", func);
697 ok = false;
698 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700699 }
700 func = strtok(NULL, ",");
701 }
702 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700703 return ok;
704}
705
706// Set the comma separated list of functions that the kernel is to trace.
707static bool setKernelTraceFuncs(const char* funcs)
708{
709 bool ok = true;
710
711 if (funcs == NULL || funcs[0] == '\0') {
712 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700713 if (fileIsWritable(k_currentTracerPath)) {
714 ok &= writeStr(k_currentTracerPath, "nop");
715 }
716 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700717 ok &= truncateFile(k_ftraceFilterPath);
718 }
719 } else {
720 // Enable kernel function tracing.
721 ok &= writeStr(k_currentTracerPath, "function_graph");
722 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
723 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
724 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
725 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
726
727 // Set the requested filter functions.
728 ok &= truncateFile(k_ftraceFilterPath);
729 char* myFuncs = strdup(funcs);
730 char* func = strtok(myFuncs, ",");
731 while (func) {
732 ok &= appendStr(k_ftraceFilterPath, func);
733 func = strtok(NULL, ",");
734 }
735 free(myFuncs);
736
737 // Verify that the set functions are being traced.
738 if (ok) {
739 ok &= verifyKernelTraceFuncs(funcs);
740 }
741 }
742
743 return ok;
744}
745
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900746static bool setCategoryEnable(const char* name, bool enable)
747{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700748 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900749 const TracingCategory& c = k_categories[i];
750 if (strcmp(name, c.name) == 0) {
751 if (isCategorySupported(c)) {
752 g_categoryEnables[i] = enable;
753 return true;
754 } else {
755 if (isCategorySupportedForRoot(c)) {
756 fprintf(stderr, "error: category \"%s\" requires root "
757 "privileges.\n", name);
758 } else {
759 fprintf(stderr, "error: category \"%s\" is not supported "
760 "on this device.\n", name);
761 }
762 return false;
763 }
764 }
765 }
766 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
767 return false;
768}
769
770static bool setCategoriesEnableFromFile(const char* categories_file)
771{
772 if (!categories_file) {
773 return true;
774 }
775 Tokenizer* tokenizer = NULL;
776 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
777 return false;
778 }
779 bool ok = true;
780 while (!tokenizer->isEol()) {
781 String8 token = tokenizer->nextToken(" ");
782 if (token.isEmpty()) {
783 tokenizer->skipDelimiters(" ");
784 continue;
785 }
786 ok &= setCategoryEnable(token.string(), true);
787 }
788 delete tokenizer;
789 return ok;
790}
791
Hector Dearman550b18c2018-03-08 14:35:44 +0000792static bool setUpUserspaceTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800793{
794 bool ok = true;
795
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800796 // Set up the tags property.
797 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700798 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800799 if (g_categoryEnables[i]) {
800 const TracingCategory &c = k_categories[i];
801 tags |= c.tags;
802 }
803 }
804 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700805
806 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700807 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700808 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
809 coreServicesTagEnabled = g_categoryEnables[i];
810 }
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700811
812 // Set whether to poke PDX services in this session.
813 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
814 g_tracePdx = g_categoryEnables[i];
815 }
sergeyvdb404152016-05-02 19:26:07 -0700816 }
817
818 std::string packageList(g_debugAppCmdLine);
819 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700820 if (!packageList.empty()) {
821 packageList += ",";
822 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700823 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700824 }
Dan Austin09a79872016-05-31 13:27:03 -0700825 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700826 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100827 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800828
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700829 if (g_tracePdx) {
830 ok &= ServiceUtility::PokeServices();
831 }
832
Hector Dearman550b18c2018-03-08 14:35:44 +0000833 return ok;
834}
835
836static void cleanUpUserspaceTracing()
837{
838 setTagsProperty(0);
839 clearAppProperties();
840 pokeBinderServices();
841
842 if (g_tracePdx) {
843 ServiceUtility::PokeServices();
844 }
845}
846
847
848// Set all the kernel tracing settings to the desired state for this trace
849// capture.
850static bool setUpKernelTracing()
851{
852 bool ok = true;
853
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700854 ok &= setUserInitiatedTraceProperty(true);
855
Hector Dearman550b18c2018-03-08 14:35:44 +0000856 // Set up the tracing options.
857 ok &= setCategoriesEnableFromFile(g_categoriesFile);
858 ok &= setTraceOverwriteEnable(g_traceOverwrite);
859 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
860 // TODO: Re-enable after stabilization
861 //ok &= setCmdlineSize();
862 ok &= setClock();
863 ok &= setPrintTgidEnableIfPresent(true);
864 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
865
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800866 // Disable all the sysfs enables. This is done as a separate loop from
867 // the enables to allow the same enable to exist in multiple categories.
868 ok &= disableKernelTraceEvents();
869
870 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700871 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800872 if (g_categoryEnables[i]) {
873 const TracingCategory &c = k_categories[i];
874 for (int j = 0; j < MAX_SYS_FILES; j++) {
875 const char* path = c.sysfiles[j].path;
876 bool required = c.sysfiles[j].required == REQ;
877 if (path != NULL) {
878 if (fileIsWritable(path)) {
879 ok &= setKernelOptionEnable(path, true);
880 } else if (required) {
881 fprintf(stderr, "error writing file %s\n", path);
882 ok = false;
883 }
884 }
885 }
886 }
887 }
888
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800889 return ok;
890}
891
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700892// Reset all the kernel tracing settings to their default state.
Hector Dearman550b18c2018-03-08 14:35:44 +0000893static void cleanUpKernelTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800894{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800895 // Disable all tracing that we're able to.
896 disableKernelTraceEvents();
897
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800898 // Set the options back to their defaults.
899 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700900 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700901 setPrintTgidEnableIfPresent(false);
902 setKernelTraceFuncs(NULL);
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700903 setUserInitiatedTraceProperty(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700904}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800905
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700906// Enable tracing in the kernel.
907static bool startTrace()
908{
909 return setTracingEnabled(true);
910}
911
912// Disable tracing in the kernel.
913static void stopTrace()
914{
915 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800916}
917
Martijn Coenend9535872015-11-26 10:00:55 +0100918// Read data from the tracing pipe and forward to stdout
919static void streamTrace()
920{
921 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800922 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100923 if (traceFD == -1) {
924 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
925 strerror(errno), errno);
926 return;
927 }
928 while (!g_traceAborted) {
929 ssize_t bytes_read = read(traceFD, trace_data, 4096);
930 if (bytes_read > 0) {
931 write(STDOUT_FILENO, trace_data, bytes_read);
932 fflush(stdout);
933 } else {
934 if (!g_traceAborted) {
935 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
936 bytes_read, errno, strerror(errno));
937 }
938 break;
939 }
940 }
941}
942
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800943// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700944static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800945{
John Reck6c8ac922016-03-28 11:25:30 -0700946 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800947 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800948 if (traceFD == -1) {
949 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
950 strerror(errno), errno);
951 return;
952 }
953
954 if (g_compress) {
955 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800956 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700957
958 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800959 if (result != Z_OK) {
960 fprintf(stderr, "error initializing zlib: %d\n", result);
961 close(traceFD);
962 return;
963 }
964
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700965 constexpr size_t bufSize = 64*1024;
966 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
967 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
968 if (!in || !out) {
969 fprintf(stderr, "couldn't allocate buffers\n");
970 close(traceFD);
971 return;
972 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800973
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700974 int flush = Z_NO_FLUSH;
975
976 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800977 zs.avail_out = bufSize;
978
979 do {
980
981 if (zs.avail_in == 0) {
982 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700983 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800984 if (result < 0) {
985 fprintf(stderr, "error reading trace: %s (%d)\n",
986 strerror(errno), errno);
987 result = Z_STREAM_END;
988 break;
989 } else if (result == 0) {
990 flush = Z_FINISH;
991 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700992 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800993 zs.avail_in = result;
994 }
995 }
996
997 if (zs.avail_out == 0) {
998 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700999 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001000 if ((size_t)result < bufSize) {
1001 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1002 strerror(errno), errno);
1003 result = Z_STREAM_END; // skip deflate error message
1004 zs.avail_out = bufSize; // skip the final write
1005 break;
1006 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001007 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001008 zs.avail_out = bufSize;
1009 }
1010
1011 } while ((result = deflate(&zs, flush)) == Z_OK);
1012
1013 if (result != Z_STREAM_END) {
1014 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
1015 }
1016
1017 if (zs.avail_out < bufSize) {
1018 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -07001019 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001020 if ((size_t)result < bytes) {
1021 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1022 strerror(errno), errno);
1023 }
1024 }
1025
1026 result = deflateEnd(&zs);
1027 if (result != Z_OK) {
1028 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1029 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001030 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001031 char buf[4096];
1032 ssize_t rc;
1033 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1034 if (!android::base::WriteFully(outFd, buf, rc)) {
1035 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1036 break;
1037 }
1038 }
1039 if (rc == -1) {
1040 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001041 }
1042 }
1043
1044 close(traceFD);
1045}
1046
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001047static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001048{
1049 if (!g_nohup) {
1050 g_traceAborted = true;
1051 }
1052}
1053
1054static void registerSigHandler()
1055{
1056 struct sigaction sa;
1057 sigemptyset(&sa.sa_mask);
1058 sa.sa_flags = 0;
1059 sa.sa_handler = handleSignal;
1060 sigaction(SIGHUP, &sa, NULL);
1061 sigaction(SIGINT, &sa, NULL);
1062 sigaction(SIGQUIT, &sa, NULL);
1063 sigaction(SIGTERM, &sa, NULL);
1064}
1065
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001066static void listSupportedCategories()
1067{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001068 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001069 const TracingCategory& c = k_categories[i];
1070 if (isCategorySupported(c)) {
1071 printf(" %10s - %s\n", c.name, c.longname);
1072 }
1073 }
1074}
1075
1076// Print the command usage help to stderr.
1077static void showHelp(const char *cmd)
1078{
1079 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1080 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001081 " -a appname enable app-level tracing for a comma "
Daniel Colascione519a0792018-02-09 20:05:39 -08001082 "separated list of cmdlines; * is a wildcard matching any process\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001083 " -b N use a trace buffer size of N KB\n"
1084 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001085 " -f filename use the categories written in a file as space-separated\n"
1086 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001087 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001088 " -n ignore signals\n"
1089 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001090 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001091 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001092 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001093 " --async_dump dump the current contents of circular trace buffer\n"
1094 " --async_stop stop tracing and dump the current contents of circular\n"
1095 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001096 " --stream stream trace to stdout as it enters the trace buffer\n"
1097 " Note: this can take significant CPU time, and is best\n"
1098 " used for measuring things that are not affected by\n"
1099 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001100 " --list_categories\n"
1101 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001102 " -o filename write the trace to the specified file instead\n"
1103 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001104 );
1105}
1106
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001107bool findTraceFiles()
1108{
1109 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1110 static const std::string tracefs_path = "/sys/kernel/tracing/";
1111 static const std::string trace_file = "trace_marker";
1112
1113 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1114 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1115
1116 if (!tracefs && !debugfs) {
1117 fprintf(stderr, "Error: Did not find trace folder\n");
1118 return false;
1119 }
1120
1121 if (tracefs) {
1122 g_traceFolder = tracefs_path;
1123 } else {
1124 g_traceFolder = debugfs_path;
1125 }
1126
1127 return true;
1128}
1129
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001130int main(int argc, char **argv)
1131{
1132 bool async = false;
1133 bool traceStart = true;
1134 bool traceStop = true;
1135 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001136 bool traceStream = false;
Hector Dearman550b18c2018-03-08 14:35:44 +00001137 bool onlyUserspace = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001138
1139 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1140 showHelp(argv[0]);
1141 exit(0);
1142 }
1143
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001144 if (!findTraceFiles()) {
1145 fprintf(stderr, "No trace folder found\n");
1146 exit(-1);
1147 }
1148
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001149 for (;;) {
1150 int ret;
1151 int option_index = 0;
1152 static struct option long_options[] = {
Hector Dearman550b18c2018-03-08 14:35:44 +00001153 {"async_start", no_argument, 0, 0 },
1154 {"async_stop", no_argument, 0, 0 },
1155 {"async_dump", no_argument, 0, 0 },
1156 {"only_userspace", no_argument, 0, 0 },
1157 {"list_categories", no_argument, 0, 0 },
1158 {"stream", no_argument, 0, 0 },
1159 { 0, 0, 0, 0 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001160 };
1161
John Reck40b26b42016-03-30 09:44:36 -07001162 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001163 long_options, &option_index);
1164
1165 if (ret < 0) {
1166 for (int i = optind; i < argc; i++) {
1167 if (!setCategoryEnable(argv[i], true)) {
1168 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1169 exit(1);
1170 }
1171 }
1172 break;
1173 }
1174
1175 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001176 case 'a':
1177 g_debugAppCmdLine = optarg;
1178 break;
1179
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001180 case 'b':
1181 g_traceBufferSizeKB = atoi(optarg);
1182 break;
1183
1184 case 'c':
1185 g_traceOverwrite = true;
1186 break;
1187
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001188 case 'f':
1189 g_categoriesFile = optarg;
1190 break;
1191
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001192 case 'k':
1193 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001194 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001195
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001196 case 'n':
1197 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001198 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001199
1200 case 's':
1201 g_initialSleepSecs = atoi(optarg);
1202 break;
1203
1204 case 't':
1205 g_traceDurationSeconds = atoi(optarg);
1206 break;
1207
1208 case 'z':
1209 g_compress = true;
1210 break;
1211
John Reck40b26b42016-03-30 09:44:36 -07001212 case 'o':
1213 g_outputFile = optarg;
1214 break;
1215
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001216 case 0:
1217 if (!strcmp(long_options[option_index].name, "async_start")) {
1218 async = true;
1219 traceStop = false;
1220 traceDump = false;
1221 g_traceOverwrite = true;
1222 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1223 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001224 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001225 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1226 async = true;
1227 traceStart = false;
1228 traceStop = false;
Hector Dearman550b18c2018-03-08 14:35:44 +00001229 } else if (!strcmp(long_options[option_index].name, "only_userspace")) {
1230 onlyUserspace = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001231 } else if (!strcmp(long_options[option_index].name, "stream")) {
1232 traceStream = true;
1233 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001234 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1235 listSupportedCategories();
1236 exit(0);
1237 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001238 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001239
1240 default:
1241 fprintf(stderr, "\n");
1242 showHelp(argv[0]);
1243 exit(-1);
1244 break;
1245 }
1246 }
1247
Hector Dearman550b18c2018-03-08 14:35:44 +00001248 if (onlyUserspace) {
1249 if (!async || !(traceStart || traceStop)) {
1250 fprintf(stderr, "--only_userspace can only be used with "
1251 "--async_start or --async_stop\n");
1252 exit(1);
1253 }
1254 }
1255
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001256 registerSigHandler();
1257
1258 if (g_initialSleepSecs > 0) {
1259 sleep(g_initialSleepSecs);
1260 }
1261
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001262 bool ok = true;
Hector Dearman550b18c2018-03-08 14:35:44 +00001263
Wei Wang190cb7d2018-03-08 13:33:12 -08001264 if (traceStart) {
Hector Dearman550b18c2018-03-08 14:35:44 +00001265 ok &= setUpUserspaceTracing();
1266 }
1267
1268 if (ok && traceStart && !onlyUserspace) {
1269 ok &= setUpKernelTracing();
Wei Wang190cb7d2018-03-08 13:33:12 -08001270 ok &= startTrace();
1271 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001272
1273 if (ok && traceStart) {
Hector Dearman550b18c2018-03-08 14:35:44 +00001274
1275 if (!traceStream && !onlyUserspace) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001276 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001277 fflush(stdout);
1278 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001279
1280 // We clear the trace after starting it because tracing gets enabled for
1281 // each CPU individually in the kernel. Having the beginning of the trace
1282 // contain entries from only one CPU can cause "begin" entries without a
1283 // matching "end" entry to show up if a task gets migrated from one CPU to
1284 // another.
Hector Dearman550b18c2018-03-08 14:35:44 +00001285 if (!onlyUserspace)
1286 ok = clearTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001287
Hector Dearman550b18c2018-03-08 14:35:44 +00001288 if (!onlyUserspace)
1289 writeClockSyncMarker();
1290
Martijn Coenend9535872015-11-26 10:00:55 +01001291 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001292 // Sleep to allow the trace to be captured.
1293 struct timespec timeLeft;
1294 timeLeft.tv_sec = g_traceDurationSeconds;
1295 timeLeft.tv_nsec = 0;
1296 do {
1297 if (g_traceAborted) {
1298 break;
1299 }
1300 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1301 }
Martijn Coenend9535872015-11-26 10:00:55 +01001302
1303 if (traceStream) {
1304 streamTrace();
1305 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001306 }
1307
1308 // Stop the trace and restore the default settings.
Hector Dearman550b18c2018-03-08 14:35:44 +00001309 if (traceStop && !onlyUserspace)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001310 stopTrace();
1311
Hector Dearman550b18c2018-03-08 14:35:44 +00001312 if (ok && traceDump && !onlyUserspace) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001313 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001314 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001315 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001316 int outFd = STDOUT_FILENO;
1317 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001318 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001319 }
1320 if (outFd == -1) {
1321 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1322 } else {
1323 dprintf(outFd, "TRACE:\n");
1324 dumpTrace(outFd);
1325 if (g_outputFile) {
1326 close(outFd);
1327 }
1328 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001329 } else {
1330 printf("\ntrace aborted.\n");
1331 fflush(stdout);
1332 }
1333 clearTrace();
1334 } else if (!ok) {
1335 fprintf(stderr, "unable to start tracing\n");
1336 }
1337
1338 // Reset the trace buffer size to 1.
Hector Dearman550b18c2018-03-08 14:35:44 +00001339 if (traceStop) {
1340 cleanUpUserspaceTracing();
1341 if (!onlyUserspace)
1342 cleanUpKernelTracing();
1343 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001344
1345 return g_traceAborted ? 1 : 0;
1346}