blob: 2561e0acd76f8f39dd4a151c11664a56bd5adc68 [file] [log] [blame]
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Paul Lawrence2cd93cc2017-01-17 09:50:18 -080017#define LOG_TAG "atrace"
John Reck40b26b42016-03-30 09:44:36 -070018
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080019#include <errno.h>
20#include <fcntl.h>
21#include <getopt.h>
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070022#include <inttypes.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080023#include <signal.h>
24#include <stdarg.h>
25#include <stdbool.h>
26#include <stdio.h>
27#include <stdlib.h>
Elliott Hughes3da5d232015-01-25 08:35:20 -080028#include <string.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080029#include <time.h>
Martijn Coenend9535872015-11-26 10:00:55 +010030#include <unistd.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080031#include <zlib.h>
32
Carmen Jacksonea826792017-05-05 11:42:32 -070033#include <fstream>
Elliott Hughesa252f4d2016-07-21 17:12:15 -070034#include <memory>
35
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080036#include <binder/IBinder.h>
37#include <binder/IServiceManager.h>
38#include <binder/Parcel.h>
39
Martijn Coenenee9b97e2016-11-16 16:00:26 +010040#include <android/hidl/manager/1.0/IServiceManager.h>
41#include <hidl/ServiceManagement.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080042
Corey Tabakaa6c0a722017-05-31 16:37:40 -070043#include <pdx/default_transport/service_utility.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080044#include <utils/String8.h>
John Reck469a1942015-03-26 15:31:35 -070045#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +090046#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080047#include <utils/Trace.h>
Stephane Gasparinid8419c22016-03-02 13:45:15 +010048#include <android-base/file.h>
Elliott Hughes5fd6ff62017-03-28 14:55:31 -070049#include <android-base/macros.h>
50#include <android-base/properties.h>
51#include <android-base/stringprintf.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080052
53using namespace android;
Corey Tabakaa6c0a722017-05-31 16:37:40 -070054using pdx::default_transport::ServiceUtility;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080055
Martijn Coenenee9b97e2016-11-16 16:00:26 +010056using std::string;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080057
sergeyv4144eff2016-04-28 11:40:04 -070058#define MAX_SYS_FILES 10
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080059
60const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
Carmen Jackson65ecfbb2018-05-22 10:29:47 -070061const char* k_userInitiatedTraceProperty = "debug.atrace.user_initiated";
sergeyv4144eff2016-04-28 11:40:04 -070062
63const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
64const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070065const char* k_coreServiceCategory = "core_services";
Corey Tabakaa6c0a722017-05-31 16:37:40 -070066const char* k_pdxServiceCategory = "pdx";
sergeyvdb404152016-05-02 19:26:07 -070067const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080068
69typedef enum { OPT, REQ } requiredness ;
70
71struct TracingCategory {
72 // The name identifying the category.
73 const char* name;
74
75 // A longer description of the category.
76 const char* longname;
77
78 // The userland tracing tags that the category enables.
79 uint64_t tags;
80
81 // The fname==NULL terminated list of /sys/ files that the category
82 // enables.
83 struct {
84 // Whether the file must be writable in order to enable the tracing
85 // category.
86 requiredness required;
87
88 // The path to the enable file.
89 const char* path;
90 } sysfiles[MAX_SYS_FILES];
91};
92
93/* Tracing categories */
94static const TracingCategory k_categories[] = {
John Reck732a29a2017-05-24 16:09:21 -070095 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, {
96 { OPT, "events/mdss/enable" },
Wei Wangbcfb4872018-02-13 10:47:23 -080097 { OPT, "events/sde/enable" },
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" },
Wei Wangca49dfc2018-05-03 15:45:20 -0700130 { OPT, "events/sched/sched_pi_setprio/enable" },
Joel Fernandes4dfca7c2017-06-15 16:53:52 -0700131 { OPT, "events/cgroup/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800132 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700133 { "irq", "IRQ Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800134 { REQ, "events/irq/enable" },
135 { OPT, "events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700136 } },
Joel Fernandes6ccad102017-08-31 08:35:05 -0700137 { "irqoff", "IRQ-disabled code section tracing", 0, {
138 { REQ, "events/preemptirq/irq_enable/enable" },
139 { REQ, "events/preemptirq/irq_disable/enable" },
140 } },
141 { "preemptoff", "Preempt-disabled code section tracing", 0, {
142 { REQ, "events/preemptirq/preempt_enable/enable" },
143 { REQ, "events/preemptirq/preempt_disable/enable" },
144 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100145 { "i2c", "I2C Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800146 { REQ, "events/i2c/enable" },
147 { REQ, "events/i2c/i2c_read/enable" },
148 { REQ, "events/i2c/i2c_write/enable" },
149 { REQ, "events/i2c/i2c_result/enable" },
150 { REQ, "events/i2c/i2c_reply/enable" },
151 { OPT, "events/i2c/smbus_read/enable" },
152 { OPT, "events/i2c/smbus_write/enable" },
153 { OPT, "events/i2c/smbus_result/enable" },
154 { OPT, "events/i2c/smbus_reply/enable" },
Michael Wright43fb6782016-08-18 19:56:43 +0100155 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700156 { "freq", "CPU Frequency", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800157 { REQ, "events/power/cpu_frequency/enable" },
158 { OPT, "events/power/clock_set_rate/enable" },
Kevin DuBois062e0b92017-11-03 15:44:08 -0700159 { OPT, "events/power/clock_disable/enable" },
160 { OPT, "events/power/clock_enable/enable" },
Wei Wang53305dd2018-02-22 11:40:07 -0800161 { OPT, "events/clk/clk_set_rate/enable" },
162 { OPT, "events/clk/clk_disable/enable" },
163 { OPT, "events/clk/clk_enable/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800164 { OPT, "events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800165 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700166 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800167 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800168 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700169 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800170 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800171 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700172 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800173 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
174 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
175 { OPT, "events/f2fs/f2fs_write_begin/enable" },
176 { OPT, "events/f2fs/f2fs_write_end/enable" },
177 { OPT, "events/ext4/ext4_da_write_begin/enable" },
178 { OPT, "events/ext4/ext4_da_write_end/enable" },
179 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
180 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
181 { REQ, "events/block/block_rq_issue/enable" },
182 { REQ, "events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800183 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700184 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800185 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700186 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700187 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800188 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800189 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700190 { "sync", "Synchronization", 0, {
Jesse Hallae001a32018-05-15 12:02:15 -0700191 // before linux kernel 4.9
192 { OPT, "events/sync/enable" },
193 // starting in linux kernel 4.9
194 { OPT, "events/fence/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800195 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700196 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800197 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800198 } },
Colin Cross580407f2014-08-18 15:22:13 -0700199 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800200 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
201 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
202 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
203 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Marc Hittingerf1f62e32017-05-17 15:57:43 -0700204 { REQ, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700205 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800206 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800207 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800208 } },
Scott Bauerae473362015-06-08 16:32:36 -0700209 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800210 { REQ, "events/binder/binder_transaction/enable" },
211 { REQ, "events/binder/binder_transaction_received/enable" },
Martijn Coenen7f3d7a22017-05-26 09:50:55 -0700212 { OPT, "events/binder/binder_set_priority/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700213 } },
214 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800215 { OPT, "events/binder/binder_lock/enable" },
216 { OPT, "events/binder/binder_locked/enable" },
217 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700218 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200219 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800220 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200221 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800222};
223
224/* Command line options */
225static int g_traceDurationSeconds = 5;
226static bool g_traceOverwrite = false;
227static int g_traceBufferSizeKB = 2048;
228static bool g_compress = false;
229static bool g_nohup = false;
230static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900231static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700232static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700233static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700234static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800235
236/* Global state */
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700237static bool g_tracePdx = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800238static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700239static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800240static std::string g_traceFolder;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800241
242/* Sys file paths */
243static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800244 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800245
246static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800247 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800248
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700249#if 0
250// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700251static const char* k_traceCmdlineSizePath =
252 "saved_cmdlines_size";
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700253#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700254
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800255static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800256 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800257
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700258static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800259 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700260
261static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800262 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700263
264static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800265 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700266
267static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800268 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700269
270static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800271 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700272
273static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800274 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700275
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700276static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800277 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700278
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800279static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800280 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800281
282static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800283 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800284
Martijn Coenend9535872015-11-26 10:00:55 +0100285static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800286 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100287
John Reck469a1942015-03-26 15:31:35 -0700288static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800289 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700290
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800291// Check whether a file exists.
292static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800293 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800294}
295
296// Check whether a file is writable.
297static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800298 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800299}
300
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700301// Truncate a file.
302static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800303{
Jamie Gennis43122e72013-03-21 14:06:31 -0700304 // This uses creat rather than truncate because some of the debug kernel
305 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
306 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800307 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700308 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800309 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700310 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700311 return false;
312 }
313
Jamie Gennis43122e72013-03-21 14:06:31 -0700314 close(traceFD);
315
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700316 return true;
317}
318
319static bool _writeStr(const char* filename, const char* str, int flags)
320{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800321 std::string fullFilename = g_traceFolder + filename;
322 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800323 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800324 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800325 strerror(errno), errno);
326 return false;
327 }
328
329 bool ok = true;
330 ssize_t len = strlen(str);
331 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800332 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800333 strerror(errno), errno);
334 ok = false;
335 }
336
337 close(fd);
338
339 return ok;
340}
341
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700342// Write a string to a file, returning true if the write was successful.
343static bool writeStr(const char* filename, const char* str)
344{
345 return _writeStr(filename, str, O_WRONLY);
346}
347
348// Append a string to a file, returning true if the write was successful.
349static bool appendStr(const char* filename, const char* str)
350{
351 return _writeStr(filename, str, O_APPEND|O_WRONLY);
352}
353
John Reck469a1942015-03-26 15:31:35 -0700354static void writeClockSyncMarker()
355{
356 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200357 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800358 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200359 if (fd == -1) {
360 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
361 strerror(errno), errno);
362 return;
363 }
John Reck469a1942015-03-26 15:31:35 -0700364 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200365
366 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
367 if (write(fd, buffer, len) != len) {
368 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
369 }
370
371 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
372 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
373 if (write(fd, buffer, len) != len) {
374 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
375 }
376
377 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700378}
379
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800380// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
381// file.
382static bool setKernelOptionEnable(const char* filename, bool enable)
383{
384 return writeStr(filename, enable ? "1" : "0");
385}
386
387// Check whether the category is supported on the device with the current
388// rootness. A category is supported only if all its required /sys/ files are
389// writable and if enabling the category will enable one or more tracing tags
390// or /sys/ files.
391static bool isCategorySupported(const TracingCategory& category)
392{
sergeyvdb404152016-05-02 19:26:07 -0700393 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700394 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700395 }
396
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700397 if (strcmp(category.name, k_pdxServiceCategory) == 0) {
398 return true;
399 }
400
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800401 bool ok = category.tags != 0;
402 for (int i = 0; i < MAX_SYS_FILES; i++) {
403 const char* path = category.sysfiles[i].path;
404 bool req = category.sysfiles[i].required == REQ;
405 if (path != NULL) {
406 if (req) {
407 if (!fileIsWritable(path)) {
408 return false;
409 } else {
410 ok = true;
411 }
412 } else {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800413 ok = true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800414 }
415 }
416 }
417 return ok;
418}
419
420// Check whether the category would be supported on the device if the user
421// were root. This function assumes that root is able to write to any file
422// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700423// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800424static bool isCategorySupportedForRoot(const TracingCategory& category)
425{
426 bool ok = category.tags != 0;
427 for (int i = 0; i < MAX_SYS_FILES; i++) {
428 const char* path = category.sysfiles[i].path;
429 bool req = category.sysfiles[i].required == REQ;
430 if (path != NULL) {
431 if (req) {
432 if (!fileExists(path)) {
433 return false;
434 } else {
435 ok = true;
436 }
437 } else {
438 ok |= fileExists(path);
439 }
440 }
441 }
442 return ok;
443}
444
445// Enable or disable overwriting of the kernel trace buffers. Disabling this
446// will cause tracing to stop once the trace buffers have filled up.
447static bool setTraceOverwriteEnable(bool enable)
448{
449 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
450}
451
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700452// Set the user initiated trace property
453static bool setUserInitiatedTraceProperty(bool enable)
454{
455 if (!android::base::SetProperty(k_userInitiatedTraceProperty, enable ? "1" : "")) {
456 fprintf(stderr, "error setting user initiated strace system property\n");
457 return false;
458 }
459 return true;
460}
461
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800462// Enable or disable kernel tracing.
463static bool setTracingEnabled(bool enable)
464{
465 return setKernelOptionEnable(k_tracingOnPath, enable);
466}
467
468// Clear the contents of the kernel trace.
469static bool clearTrace()
470{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700471 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800472}
473
474// Set the size of the kernel's trace buffer in kilobytes.
475static bool setTraceBufferSizeKB(int size)
476{
477 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800478 if (size < 1) {
479 size = 1;
480 }
481 snprintf(str, 32, "%d", size);
482 return writeStr(k_traceBufferSizePath, str);
483}
484
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700485#if 0
486// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700487// Set the default size of cmdline hashtable
488static bool setCmdlineSize()
489{
Joel Fernandesce964f22017-06-06 12:20:29 -0700490 if (fileExists(k_traceCmdlineSizePath)) {
491 return writeStr(k_traceCmdlineSizePath, "8192");
492 }
493 return true;
Joel Fernandesed80bd02017-06-02 10:19:28 -0700494}
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700495#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700496
Carmen Jacksonea826792017-05-05 11:42:32 -0700497// Set the clock to the best available option while tracing. Use 'boot' if it's
498// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700499// Any write to the trace_clock sysfs file will reset the buffer, so only
500// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700501static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800502{
Carmen Jacksonea826792017-05-05 11:42:32 -0700503 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
504 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
505 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700506
Carmen Jacksonea826792017-05-05 11:42:32 -0700507 std::string newClock;
508 if (clockStr.find("boot") != std::string::npos) {
509 newClock = "boot";
510 } else if (clockStr.find("mono") != std::string::npos) {
511 newClock = "mono";
512 } else {
513 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700514 }
515
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700516 size_t begin = clockStr.find('[') + 1;
517 size_t end = clockStr.find(']');
Carmen Jacksonea826792017-05-05 11:42:32 -0700518 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
519 return true;
520 }
521 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800522}
523
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700524static bool setPrintTgidEnableIfPresent(bool enable)
525{
526 if (fileExists(k_printTgidPath)) {
527 return setKernelOptionEnable(k_printTgidPath, enable);
528 }
529 return true;
530}
531
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800532// Poke all the binder-enabled processes in the system to get them to re-read
533// their system properties.
534static bool pokeBinderServices()
535{
536 sp<IServiceManager> sm = defaultServiceManager();
537 Vector<String16> services = sm->listServices();
538 for (size_t i = 0; i < services.size(); i++) {
539 sp<IBinder> obj = sm->checkService(services[i]);
540 if (obj != NULL) {
541 Parcel data;
542 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
543 NULL, 0) != OK) {
544 if (false) {
545 // XXX: For some reason this fails on tablets trying to
546 // poke the "phone" service. It's not clear whether some
547 // are expected to fail.
548 String8 svc(services[i]);
549 fprintf(stderr, "error poking binder service %s\n",
550 svc.string());
551 return false;
552 }
553 }
554 }
555 }
556 return true;
557}
558
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100559// Poke all the HAL processes in the system to get them to re-read
560// their system properties.
561static void pokeHalServices()
562{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100563 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100564 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100565 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100566 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100567
568 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800569
570 if (sm == nullptr) {
571 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
572 return;
573 }
574
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800575 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100576 for (size_t i = 0; i < interfaces.size(); i++) {
577 string fqInstanceName = interfaces[i];
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700578 string::size_type n = fqInstanceName.find('/');
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100579 if (n == std::string::npos || interfaces[i].size() == n+1)
580 continue;
581 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
582 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100583 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
584 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100585 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100586 continue;
587 }
Carmen Jackson73206122017-04-18 15:37:57 -0700588
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100589 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700590 if (interface == nullptr) {
591 // ignore
592 continue;
593 }
594
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100595 auto notifyRet = interface->notifySyspropsChanged();
596 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100597 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800598 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100599 }
600 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800601 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100602 // TODO(b/34242478) fix this when we determine the correct ACL
603 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800604 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100605}
606
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800607// Set the trace tags that userland tracing uses, and poke the running
608// processes to pick up the new value.
609static bool setTagsProperty(uint64_t tags)
610{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700611 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
612 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800613 fprintf(stderr, "error setting trace tags system property\n");
614 return false;
615 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700616 return true;
617}
618
sergeyv4144eff2016-04-28 11:40:04 -0700619static void clearAppProperties()
620{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700621 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700622 fprintf(stderr, "failed to clear system property: %s",
623 k_traceAppsNumberProperty);
624 }
625}
626
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700627// Set the system property that indicates which apps should perform
628// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700629static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700630{
sergeyv4144eff2016-04-28 11:40:04 -0700631 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700632 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700633 while (start != NULL) {
sergeyv4144eff2016-04-28 11:40:04 -0700634 char* end = strchr(start, ',');
635 if (end != NULL) {
636 *end = '\0';
637 end++;
638 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700639 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
640 if (!android::base::SetProperty(key, start)) {
641 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700642 clearAppProperties();
643 return false;
644 }
645 start = end;
646 i++;
647 }
648
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700649 std::string value = android::base::StringPrintf("%d", i);
650 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
651 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700652 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700653 return false;
654 }
655 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800656}
657
658// Disable all /sys/ enable files.
659static bool disableKernelTraceEvents() {
660 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700661 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800662 const TracingCategory &c = k_categories[i];
663 for (int j = 0; j < MAX_SYS_FILES; j++) {
664 const char* path = c.sysfiles[j].path;
665 if (path != NULL && fileIsWritable(path)) {
666 ok &= setKernelOptionEnable(path, false);
667 }
668 }
669 }
670 return ok;
671}
672
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700673// Verify that the comma separated list of functions are being traced by the
674// kernel.
675static bool verifyKernelTraceFuncs(const char* funcs)
676{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100677 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800678 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100679 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700680 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100681 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700682 }
683
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100684 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700685
686 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100687 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700688 bool ok = true;
689 char* myFuncs = strdup(funcs);
690 char* func = strtok(myFuncs, ",");
691 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100692 if (!strchr(func, '*')) {
693 String8 fancyFunc = String8::format("\n%s\n", func);
694 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
695 if (!found || func[0] == '\0') {
696 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
697 "to trace.\n", func);
698 ok = false;
699 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700700 }
701 func = strtok(NULL, ",");
702 }
703 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700704 return ok;
705}
706
707// Set the comma separated list of functions that the kernel is to trace.
708static bool setKernelTraceFuncs(const char* funcs)
709{
710 bool ok = true;
711
712 if (funcs == NULL || funcs[0] == '\0') {
713 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700714 if (fileIsWritable(k_currentTracerPath)) {
715 ok &= writeStr(k_currentTracerPath, "nop");
716 }
717 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700718 ok &= truncateFile(k_ftraceFilterPath);
719 }
720 } else {
721 // Enable kernel function tracing.
722 ok &= writeStr(k_currentTracerPath, "function_graph");
723 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
724 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
725 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
726 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
727
728 // Set the requested filter functions.
729 ok &= truncateFile(k_ftraceFilterPath);
730 char* myFuncs = strdup(funcs);
731 char* func = strtok(myFuncs, ",");
732 while (func) {
733 ok &= appendStr(k_ftraceFilterPath, func);
734 func = strtok(NULL, ",");
735 }
736 free(myFuncs);
737
738 // Verify that the set functions are being traced.
739 if (ok) {
740 ok &= verifyKernelTraceFuncs(funcs);
741 }
742 }
743
744 return ok;
745}
746
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900747static bool setCategoryEnable(const char* name, bool enable)
748{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700749 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900750 const TracingCategory& c = k_categories[i];
751 if (strcmp(name, c.name) == 0) {
752 if (isCategorySupported(c)) {
753 g_categoryEnables[i] = enable;
754 return true;
755 } else {
756 if (isCategorySupportedForRoot(c)) {
757 fprintf(stderr, "error: category \"%s\" requires root "
758 "privileges.\n", name);
759 } else {
760 fprintf(stderr, "error: category \"%s\" is not supported "
761 "on this device.\n", name);
762 }
763 return false;
764 }
765 }
766 }
767 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
768 return false;
769}
770
771static bool setCategoriesEnableFromFile(const char* categories_file)
772{
773 if (!categories_file) {
774 return true;
775 }
776 Tokenizer* tokenizer = NULL;
777 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
778 return false;
779 }
780 bool ok = true;
781 while (!tokenizer->isEol()) {
782 String8 token = tokenizer->nextToken(" ");
783 if (token.isEmpty()) {
784 tokenizer->skipDelimiters(" ");
785 continue;
786 }
787 ok &= setCategoryEnable(token.string(), true);
788 }
789 delete tokenizer;
790 return ok;
791}
792
Hector Dearman11845782018-03-08 14:35:44 +0000793static bool setUpUserspaceTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800794{
795 bool ok = true;
796
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800797 // Set up the tags property.
798 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700799 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800800 if (g_categoryEnables[i]) {
801 const TracingCategory &c = k_categories[i];
802 tags |= c.tags;
803 }
804 }
805 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700806
807 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700808 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700809 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
810 coreServicesTagEnabled = g_categoryEnables[i];
811 }
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700812
813 // Set whether to poke PDX services in this session.
814 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
815 g_tracePdx = g_categoryEnables[i];
816 }
sergeyvdb404152016-05-02 19:26:07 -0700817 }
818
819 std::string packageList(g_debugAppCmdLine);
820 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700821 if (!packageList.empty()) {
822 packageList += ",";
823 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700824 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700825 }
Dan Austin09a79872016-05-31 13:27:03 -0700826 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700827 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100828 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800829
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700830 if (g_tracePdx) {
831 ok &= ServiceUtility::PokeServices();
832 }
833
Hector Dearman11845782018-03-08 14:35:44 +0000834 return ok;
835}
836
837static void cleanUpUserspaceTracing()
838{
839 setTagsProperty(0);
840 clearAppProperties();
841 pokeBinderServices();
842
843 if (g_tracePdx) {
844 ServiceUtility::PokeServices();
845 }
846}
847
848
849// Set all the kernel tracing settings to the desired state for this trace
850// capture.
851static bool setUpKernelTracing()
852{
853 bool ok = true;
854
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700855 ok &= setUserInitiatedTraceProperty(true);
856
Hector Dearman11845782018-03-08 14:35:44 +0000857 // Set up the tracing options.
858 ok &= setCategoriesEnableFromFile(g_categoriesFile);
859 ok &= setTraceOverwriteEnable(g_traceOverwrite);
860 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
861 // TODO: Re-enable after stabilization
862 //ok &= setCmdlineSize();
863 ok &= setClock();
864 ok &= setPrintTgidEnableIfPresent(true);
865 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
866
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800867 // Disable all the sysfs enables. This is done as a separate loop from
868 // the enables to allow the same enable to exist in multiple categories.
869 ok &= disableKernelTraceEvents();
870
871 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700872 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800873 if (g_categoryEnables[i]) {
874 const TracingCategory &c = k_categories[i];
875 for (int j = 0; j < MAX_SYS_FILES; j++) {
876 const char* path = c.sysfiles[j].path;
877 bool required = c.sysfiles[j].required == REQ;
878 if (path != NULL) {
879 if (fileIsWritable(path)) {
880 ok &= setKernelOptionEnable(path, true);
881 } else if (required) {
882 fprintf(stderr, "error writing file %s\n", path);
883 ok = false;
884 }
885 }
886 }
887 }
888 }
889
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800890 return ok;
891}
892
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700893// Reset all the kernel tracing settings to their default state.
Hector Dearman11845782018-03-08 14:35:44 +0000894static void cleanUpKernelTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800895{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800896 // Disable all tracing that we're able to.
897 disableKernelTraceEvents();
898
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800899 // Set the options back to their defaults.
900 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700901 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700902 setPrintTgidEnableIfPresent(false);
903 setKernelTraceFuncs(NULL);
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700904 setUserInitiatedTraceProperty(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700905}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800906
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700907// Enable tracing in the kernel.
908static bool startTrace()
909{
910 return setTracingEnabled(true);
911}
912
913// Disable tracing in the kernel.
914static void stopTrace()
915{
916 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800917}
918
Martijn Coenend9535872015-11-26 10:00:55 +0100919// Read data from the tracing pipe and forward to stdout
920static void streamTrace()
921{
922 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800923 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100924 if (traceFD == -1) {
925 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
926 strerror(errno), errno);
927 return;
928 }
929 while (!g_traceAborted) {
930 ssize_t bytes_read = read(traceFD, trace_data, 4096);
931 if (bytes_read > 0) {
932 write(STDOUT_FILENO, trace_data, bytes_read);
933 fflush(stdout);
934 } else {
935 if (!g_traceAborted) {
936 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
937 bytes_read, errno, strerror(errno));
938 }
939 break;
940 }
941 }
942}
943
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800944// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700945static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800946{
John Reck6c8ac922016-03-28 11:25:30 -0700947 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800948 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800949 if (traceFD == -1) {
950 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
951 strerror(errno), errno);
952 return;
953 }
954
955 if (g_compress) {
956 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800957 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700958
959 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800960 if (result != Z_OK) {
961 fprintf(stderr, "error initializing zlib: %d\n", result);
962 close(traceFD);
963 return;
964 }
965
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700966 constexpr size_t bufSize = 64*1024;
967 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
968 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
969 if (!in || !out) {
970 fprintf(stderr, "couldn't allocate buffers\n");
971 close(traceFD);
972 return;
973 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800974
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700975 int flush = Z_NO_FLUSH;
976
977 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800978 zs.avail_out = bufSize;
979
980 do {
981
982 if (zs.avail_in == 0) {
983 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700984 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800985 if (result < 0) {
986 fprintf(stderr, "error reading trace: %s (%d)\n",
987 strerror(errno), errno);
988 result = Z_STREAM_END;
989 break;
990 } else if (result == 0) {
991 flush = Z_FINISH;
992 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700993 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800994 zs.avail_in = result;
995 }
996 }
997
998 if (zs.avail_out == 0) {
999 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -07001000 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001001 if ((size_t)result < bufSize) {
1002 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1003 strerror(errno), errno);
1004 result = Z_STREAM_END; // skip deflate error message
1005 zs.avail_out = bufSize; // skip the final write
1006 break;
1007 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001008 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001009 zs.avail_out = bufSize;
1010 }
1011
1012 } while ((result = deflate(&zs, flush)) == Z_OK);
1013
1014 if (result != Z_STREAM_END) {
1015 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
1016 }
1017
1018 if (zs.avail_out < bufSize) {
1019 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -07001020 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001021 if ((size_t)result < bytes) {
1022 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1023 strerror(errno), errno);
1024 }
1025 }
1026
1027 result = deflateEnd(&zs);
1028 if (result != Z_OK) {
1029 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1030 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001031 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001032 char buf[4096];
1033 ssize_t rc;
1034 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1035 if (!android::base::WriteFully(outFd, buf, rc)) {
1036 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1037 break;
1038 }
1039 }
1040 if (rc == -1) {
1041 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001042 }
1043 }
1044
1045 close(traceFD);
1046}
1047
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001048static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001049{
1050 if (!g_nohup) {
1051 g_traceAborted = true;
1052 }
1053}
1054
1055static void registerSigHandler()
1056{
1057 struct sigaction sa;
1058 sigemptyset(&sa.sa_mask);
1059 sa.sa_flags = 0;
1060 sa.sa_handler = handleSignal;
1061 sigaction(SIGHUP, &sa, NULL);
1062 sigaction(SIGINT, &sa, NULL);
1063 sigaction(SIGQUIT, &sa, NULL);
1064 sigaction(SIGTERM, &sa, NULL);
1065}
1066
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001067static void listSupportedCategories()
1068{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001069 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001070 const TracingCategory& c = k_categories[i];
1071 if (isCategorySupported(c)) {
1072 printf(" %10s - %s\n", c.name, c.longname);
1073 }
1074 }
1075}
1076
1077// Print the command usage help to stderr.
1078static void showHelp(const char *cmd)
1079{
1080 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1081 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001082 " -a appname enable app-level tracing for a comma "
Daniel Colascione519a0792018-02-09 20:05:39 -08001083 "separated list of cmdlines; * is a wildcard matching any process\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001084 " -b N use a trace buffer size of N KB\n"
1085 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001086 " -f filename use the categories written in a file as space-separated\n"
1087 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001088 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001089 " -n ignore signals\n"
1090 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001091 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001092 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001093 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001094 " --async_dump dump the current contents of circular trace buffer\n"
1095 " --async_stop stop tracing and dump the current contents of circular\n"
1096 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001097 " --stream stream trace to stdout as it enters the trace buffer\n"
1098 " Note: this can take significant CPU time, and is best\n"
1099 " used for measuring things that are not affected by\n"
1100 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001101 " --list_categories\n"
1102 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001103 " -o filename write the trace to the specified file instead\n"
1104 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001105 );
1106}
1107
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001108bool findTraceFiles()
1109{
1110 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1111 static const std::string tracefs_path = "/sys/kernel/tracing/";
1112 static const std::string trace_file = "trace_marker";
1113
1114 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1115 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1116
1117 if (!tracefs && !debugfs) {
1118 fprintf(stderr, "Error: Did not find trace folder\n");
1119 return false;
1120 }
1121
1122 if (tracefs) {
1123 g_traceFolder = tracefs_path;
1124 } else {
1125 g_traceFolder = debugfs_path;
1126 }
1127
1128 return true;
1129}
1130
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001131int main(int argc, char **argv)
1132{
1133 bool async = false;
1134 bool traceStart = true;
1135 bool traceStop = true;
1136 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001137 bool traceStream = false;
Hector Dearman11845782018-03-08 14:35:44 +00001138 bool onlyUserspace = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001139
1140 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1141 showHelp(argv[0]);
1142 exit(0);
1143 }
1144
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001145 if (!findTraceFiles()) {
1146 fprintf(stderr, "No trace folder found\n");
1147 exit(-1);
1148 }
1149
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001150 for (;;) {
1151 int ret;
1152 int option_index = 0;
1153 static struct option long_options[] = {
Hector Dearman11845782018-03-08 14:35:44 +00001154 {"async_start", no_argument, 0, 0 },
1155 {"async_stop", no_argument, 0, 0 },
1156 {"async_dump", no_argument, 0, 0 },
1157 {"only_userspace", no_argument, 0, 0 },
1158 {"list_categories", no_argument, 0, 0 },
1159 {"stream", no_argument, 0, 0 },
1160 { 0, 0, 0, 0 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001161 };
1162
John Reck40b26b42016-03-30 09:44:36 -07001163 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001164 long_options, &option_index);
1165
1166 if (ret < 0) {
1167 for (int i = optind; i < argc; i++) {
1168 if (!setCategoryEnable(argv[i], true)) {
1169 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1170 exit(1);
1171 }
1172 }
1173 break;
1174 }
1175
1176 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001177 case 'a':
1178 g_debugAppCmdLine = optarg;
1179 break;
1180
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001181 case 'b':
1182 g_traceBufferSizeKB = atoi(optarg);
1183 break;
1184
1185 case 'c':
1186 g_traceOverwrite = true;
1187 break;
1188
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001189 case 'f':
1190 g_categoriesFile = optarg;
1191 break;
1192
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001193 case 'k':
1194 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001195 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001196
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001197 case 'n':
1198 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001199 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001200
1201 case 's':
1202 g_initialSleepSecs = atoi(optarg);
1203 break;
1204
1205 case 't':
1206 g_traceDurationSeconds = atoi(optarg);
1207 break;
1208
1209 case 'z':
1210 g_compress = true;
1211 break;
1212
John Reck40b26b42016-03-30 09:44:36 -07001213 case 'o':
1214 g_outputFile = optarg;
1215 break;
1216
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001217 case 0:
1218 if (!strcmp(long_options[option_index].name, "async_start")) {
1219 async = true;
1220 traceStop = false;
1221 traceDump = false;
1222 g_traceOverwrite = true;
1223 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1224 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001225 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001226 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1227 async = true;
1228 traceStart = false;
1229 traceStop = false;
Hector Dearman11845782018-03-08 14:35:44 +00001230 } else if (!strcmp(long_options[option_index].name, "only_userspace")) {
1231 onlyUserspace = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001232 } else if (!strcmp(long_options[option_index].name, "stream")) {
1233 traceStream = true;
1234 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001235 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1236 listSupportedCategories();
1237 exit(0);
1238 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001239 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001240
1241 default:
1242 fprintf(stderr, "\n");
1243 showHelp(argv[0]);
1244 exit(-1);
1245 break;
1246 }
1247 }
1248
Hector Dearman11845782018-03-08 14:35:44 +00001249 if (onlyUserspace) {
1250 if (!async || !(traceStart || traceStop)) {
1251 fprintf(stderr, "--only_userspace can only be used with "
1252 "--async_start or --async_stop\n");
1253 exit(1);
1254 }
1255 }
1256
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001257 registerSigHandler();
1258
1259 if (g_initialSleepSecs > 0) {
1260 sleep(g_initialSleepSecs);
1261 }
1262
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001263 bool ok = true;
Hector Dearman11845782018-03-08 14:35:44 +00001264
Wei Wang5b73b742018-03-08 13:33:12 -08001265 if (traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001266 ok &= setUpUserspaceTracing();
1267 }
1268
1269 if (ok && traceStart && !onlyUserspace) {
1270 ok &= setUpKernelTracing();
Wei Wang5b73b742018-03-08 13:33:12 -08001271 ok &= startTrace();
1272 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001273
1274 if (ok && traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001275
1276 if (!traceStream && !onlyUserspace) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001277 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001278 fflush(stdout);
1279 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001280
1281 // We clear the trace after starting it because tracing gets enabled for
1282 // each CPU individually in the kernel. Having the beginning of the trace
1283 // contain entries from only one CPU can cause "begin" entries without a
1284 // matching "end" entry to show up if a task gets migrated from one CPU to
1285 // another.
Hector Dearman11845782018-03-08 14:35:44 +00001286 if (!onlyUserspace)
1287 ok = clearTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001288
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001289 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001290 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001291 // Sleep to allow the trace to be captured.
1292 struct timespec timeLeft;
1293 timeLeft.tv_sec = g_traceDurationSeconds;
1294 timeLeft.tv_nsec = 0;
1295 do {
1296 if (g_traceAborted) {
1297 break;
1298 }
1299 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1300 }
Martijn Coenend9535872015-11-26 10:00:55 +01001301
1302 if (traceStream) {
1303 streamTrace();
1304 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001305 }
1306
1307 // Stop the trace and restore the default settings.
Hector Dearman11845782018-03-08 14:35:44 +00001308 if (traceStop && !onlyUserspace)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001309 stopTrace();
1310
Hector Dearman11845782018-03-08 14:35:44 +00001311 if (ok && traceDump && !onlyUserspace) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001312 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001313 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001314 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001315 int outFd = STDOUT_FILENO;
1316 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001317 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001318 }
1319 if (outFd == -1) {
1320 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1321 } else {
1322 dprintf(outFd, "TRACE:\n");
1323 dumpTrace(outFd);
1324 if (g_outputFile) {
1325 close(outFd);
1326 }
1327 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001328 } else {
1329 printf("\ntrace aborted.\n");
1330 fflush(stdout);
1331 }
1332 clearTrace();
1333 } else if (!ok) {
1334 fprintf(stderr, "unable to start tracing\n");
1335 }
1336
1337 // Reset the trace buffer size to 1.
Hector Dearman11845782018-03-08 14:35:44 +00001338 if (traceStop) {
1339 cleanUpUserspaceTracing();
1340 if (!onlyUserspace)
1341 cleanUpKernelTracing();
1342 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001343
1344 return g_traceAborted ? 1 : 0;
1345}