blob: 507a893b07f376675ceeb0db679d1c0a15772f96 [file] [log] [blame]
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Paul Lawrence2cd93cc2017-01-17 09:50:18 -080017#define LOG_TAG "atrace"
John Reck40b26b42016-03-30 09:44:36 -070018
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080019#include <errno.h>
20#include <fcntl.h>
21#include <getopt.h>
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070022#include <inttypes.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080023#include <signal.h>
24#include <stdarg.h>
25#include <stdbool.h>
26#include <stdio.h>
27#include <stdlib.h>
Elliott Hughes3da5d232015-01-25 08:35:20 -080028#include <string.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080029#include <time.h>
Martijn Coenend9535872015-11-26 10:00:55 +010030#include <unistd.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080031#include <zlib.h>
32
Carmen Jacksonea826792017-05-05 11:42:32 -070033#include <fstream>
Elliott Hughesa252f4d2016-07-21 17:12:15 -070034#include <memory>
35
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080036#include <binder/IBinder.h>
37#include <binder/IServiceManager.h>
38#include <binder/Parcel.h>
39
Martijn Coenenee9b97e2016-11-16 16:00:26 +010040#include <android/hidl/manager/1.0/IServiceManager.h>
41#include <hidl/ServiceManagement.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080042
Corey Tabakaa6c0a722017-05-31 16:37:40 -070043#include <pdx/default_transport/service_utility.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080044#include <utils/String8.h>
John Reck469a1942015-03-26 15:31:35 -070045#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +090046#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080047#include <utils/Trace.h>
Stephane Gasparinid8419c22016-03-02 13:45:15 +010048#include <android-base/file.h>
Elliott Hughes5fd6ff62017-03-28 14:55:31 -070049#include <android-base/macros.h>
50#include <android-base/properties.h>
51#include <android-base/stringprintf.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080052
53using namespace android;
Corey Tabakaa6c0a722017-05-31 16:37:40 -070054using pdx::default_transport::ServiceUtility;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080055
Martijn Coenenee9b97e2016-11-16 16:00:26 +010056using std::string;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080057
sergeyv4144eff2016-04-28 11:40:04 -070058#define MAX_SYS_FILES 10
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080059
60const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
Carmen Jacksonab1118e2018-05-22 10:29:47 -070061const char* k_userInitiatedTraceProperty = "debug.atrace.user_initiated";
sergeyv4144eff2016-04-28 11:40:04 -070062
63const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
64const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070065const char* k_coreServiceCategory = "core_services";
Corey Tabakaa6c0a722017-05-31 16:37:40 -070066const char* k_pdxServiceCategory = "pdx";
sergeyvdb404152016-05-02 19:26:07 -070067const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080068
69typedef enum { OPT, REQ } requiredness ;
70
71struct TracingCategory {
72 // The name identifying the category.
73 const char* name;
74
75 // A longer description of the category.
76 const char* longname;
77
78 // The userland tracing tags that the category enables.
79 uint64_t tags;
80
81 // The fname==NULL terminated list of /sys/ files that the category
82 // enables.
83 struct {
84 // Whether the file must be writable in order to enable the tracing
85 // category.
86 requiredness required;
87
88 // The path to the enable file.
89 const char* path;
90 } sysfiles[MAX_SYS_FILES];
91};
92
93/* Tracing categories */
94static const TracingCategory k_categories[] = {
John Reck732a29a2017-05-24 16:09:21 -070095 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, {
96 { OPT, "events/mdss/enable" },
Wei Wangbcfb4872018-02-13 10:47:23 -080097 { OPT, "events/sde/enable" },
John Reck732a29a2017-05-24 16:09:21 -070098 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070099 { "input", "Input", ATRACE_TAG_INPUT, { } },
100 { "view", "View System", ATRACE_TAG_VIEW, { } },
101 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
102 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
103 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -0500104 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700105 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
106 { "video", "Video", ATRACE_TAG_VIDEO, { } },
107 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
108 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -0700109 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -0700110 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -0700111 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -0700112 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700113 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 14:36:20 -0700114 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-07-01 01:46:25 +0900115 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Greg Hackmannbbd7d992014-12-01 14:43:34 -0800116 { "database", "Database", ATRACE_TAG_DATABASE, { } },
Felipe Leme0f97c1d2016-09-07 11:33:26 -0700117 { "network", "Network", ATRACE_TAG_NETWORK, { } },
Josh Gao468b4cb2016-11-29 10:55:21 -0800118 { "adb", "ADB", ATRACE_TAG_ADB, { } },
Martijn Coenen42f2ab42018-03-09 09:27:32 +0100119 { "vibrator", "Vibrator", ATRACE_TAG_VIBRATOR, { } },
120 { "aidl", "AIDL calls", ATRACE_TAG_AIDL, { } },
Mika Raentob363cf52018-04-23 22:09:13 +0100121 { "nnapi", "NNAPI", ATRACE_TAG_NNAPI, { } },
sergeyvdb404152016-05-02 19:26:07 -0700122 { k_coreServiceCategory, "Core services", 0, { } },
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700123 { k_pdxServiceCategory, "PDX services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700124 { "sched", "CPU Scheduling", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800125 { REQ, "events/sched/sched_switch/enable" },
126 { REQ, "events/sched/sched_wakeup/enable" },
Joel Fernandesee593e22017-06-04 13:05:59 -0700127 { OPT, "events/sched/sched_waking/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800128 { OPT, "events/sched/sched_blocked_reason/enable" },
129 { OPT, "events/sched/sched_cpu_hotplug/enable" },
Joel Fernandes4dfca7c2017-06-15 16:53:52 -0700130 { OPT, "events/cgroup/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800131 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700132 { "irq", "IRQ Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800133 { REQ, "events/irq/enable" },
134 { OPT, "events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700135 } },
Joel Fernandes6ccad102017-08-31 08:35:05 -0700136 { "irqoff", "IRQ-disabled code section tracing", 0, {
137 { REQ, "events/preemptirq/irq_enable/enable" },
138 { REQ, "events/preemptirq/irq_disable/enable" },
139 } },
140 { "preemptoff", "Preempt-disabled code section tracing", 0, {
141 { REQ, "events/preemptirq/preempt_enable/enable" },
142 { REQ, "events/preemptirq/preempt_disable/enable" },
143 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100144 { "i2c", "I2C Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800145 { REQ, "events/i2c/enable" },
146 { REQ, "events/i2c/i2c_read/enable" },
147 { REQ, "events/i2c/i2c_write/enable" },
148 { REQ, "events/i2c/i2c_result/enable" },
149 { REQ, "events/i2c/i2c_reply/enable" },
150 { OPT, "events/i2c/smbus_read/enable" },
151 { OPT, "events/i2c/smbus_write/enable" },
152 { OPT, "events/i2c/smbus_result/enable" },
153 { OPT, "events/i2c/smbus_reply/enable" },
Michael Wright43fb6782016-08-18 19:56:43 +0100154 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700155 { "freq", "CPU Frequency", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800156 { REQ, "events/power/cpu_frequency/enable" },
157 { OPT, "events/power/clock_set_rate/enable" },
Kevin DuBois062e0b92017-11-03 15:44:08 -0700158 { OPT, "events/power/clock_disable/enable" },
159 { OPT, "events/power/clock_enable/enable" },
Wei Wang53305dd2018-02-22 11:40:07 -0800160 { OPT, "events/clk/clk_set_rate/enable" },
161 { OPT, "events/clk/clk_disable/enable" },
162 { OPT, "events/clk/clk_enable/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800163 { OPT, "events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800164 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700165 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800166 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800167 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700168 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800169 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800170 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700171 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800172 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
173 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
174 { OPT, "events/f2fs/f2fs_write_begin/enable" },
175 { OPT, "events/f2fs/f2fs_write_end/enable" },
176 { OPT, "events/ext4/ext4_da_write_begin/enable" },
177 { OPT, "events/ext4/ext4_da_write_end/enable" },
178 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
179 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
180 { REQ, "events/block/block_rq_issue/enable" },
181 { REQ, "events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800182 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700183 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800184 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700185 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700186 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800187 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800188 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700189 { "sync", "Synchronization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800190 { REQ, "events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800191 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700192 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800193 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800194 } },
Colin Cross580407f2014-08-18 15:22:13 -0700195 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800196 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
197 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
198 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
199 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Marc Hittingerf1f62e32017-05-17 15:57:43 -0700200 { REQ, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700201 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800202 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800203 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800204 } },
Scott Bauerae473362015-06-08 16:32:36 -0700205 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800206 { REQ, "events/binder/binder_transaction/enable" },
207 { REQ, "events/binder/binder_transaction_received/enable" },
Mika Raento80c3e5d2018-06-25 16:47:24 +0100208 { REQ, "events/binder/binder_transaction_alloc_buf/enable" },
Martijn Coenen7f3d7a22017-05-26 09:50:55 -0700209 { OPT, "events/binder/binder_set_priority/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700210 } },
211 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800212 { OPT, "events/binder/binder_lock/enable" },
213 { OPT, "events/binder/binder_locked/enable" },
214 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700215 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200216 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800217 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200218 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800219};
220
221/* Command line options */
222static int g_traceDurationSeconds = 5;
223static bool g_traceOverwrite = false;
224static int g_traceBufferSizeKB = 2048;
225static bool g_compress = false;
226static bool g_nohup = false;
227static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900228static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700229static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700230static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700231static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800232
233/* Global state */
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700234static bool g_tracePdx = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800235static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700236static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800237static std::string g_traceFolder;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800238
239/* Sys file paths */
240static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800241 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800242
243static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800244 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800245
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700246#if 0
247// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700248static const char* k_traceCmdlineSizePath =
249 "saved_cmdlines_size";
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700250#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700251
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800252static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800253 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800254
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700255static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800256 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700257
258static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800259 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700260
John Recke757b1c2018-06-28 12:24:33 -0700261static const char* k_recordTgidPath =
262 "options/record-tgid";
263
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700264static 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 Jacksonab1118e2018-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 }
John Recke757b1c2018-06-28 12:24:33 -0700529 if (fileExists(k_recordTgidPath)) {
530 return setKernelOptionEnable(k_recordTgidPath, enable);
531 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700532 return true;
533}
534
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800535// Poke all the binder-enabled processes in the system to get them to re-read
536// their system properties.
537static bool pokeBinderServices()
538{
539 sp<IServiceManager> sm = defaultServiceManager();
540 Vector<String16> services = sm->listServices();
541 for (size_t i = 0; i < services.size(); i++) {
542 sp<IBinder> obj = sm->checkService(services[i]);
543 if (obj != NULL) {
544 Parcel data;
545 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
546 NULL, 0) != OK) {
547 if (false) {
548 // XXX: For some reason this fails on tablets trying to
549 // poke the "phone" service. It's not clear whether some
550 // are expected to fail.
551 String8 svc(services[i]);
552 fprintf(stderr, "error poking binder service %s\n",
553 svc.string());
554 return false;
555 }
556 }
557 }
558 }
559 return true;
560}
561
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100562// Poke all the HAL processes in the system to get them to re-read
563// their system properties.
564static void pokeHalServices()
565{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100566 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100567 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100568 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100569 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100570
571 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800572
573 if (sm == nullptr) {
574 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
575 return;
576 }
577
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800578 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100579 for (size_t i = 0; i < interfaces.size(); i++) {
580 string fqInstanceName = interfaces[i];
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700581 string::size_type n = fqInstanceName.find('/');
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100582 if (n == std::string::npos || interfaces[i].size() == n+1)
583 continue;
584 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
585 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100586 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
587 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100588 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100589 continue;
590 }
Carmen Jackson73206122017-04-18 15:37:57 -0700591
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100592 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700593 if (interface == nullptr) {
594 // ignore
595 continue;
596 }
597
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100598 auto notifyRet = interface->notifySyspropsChanged();
599 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100600 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800601 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100602 }
603 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800604 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100605 // TODO(b/34242478) fix this when we determine the correct ACL
606 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800607 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100608}
609
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800610// Set the trace tags that userland tracing uses, and poke the running
611// processes to pick up the new value.
612static bool setTagsProperty(uint64_t tags)
613{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700614 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
615 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800616 fprintf(stderr, "error setting trace tags system property\n");
617 return false;
618 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700619 return true;
620}
621
sergeyv4144eff2016-04-28 11:40:04 -0700622static void clearAppProperties()
623{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700624 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700625 fprintf(stderr, "failed to clear system property: %s",
626 k_traceAppsNumberProperty);
627 }
628}
629
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700630// Set the system property that indicates which apps should perform
631// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700632static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700633{
sergeyv4144eff2016-04-28 11:40:04 -0700634 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700635 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700636 while (start != NULL) {
sergeyv4144eff2016-04-28 11:40:04 -0700637 char* end = strchr(start, ',');
638 if (end != NULL) {
639 *end = '\0';
640 end++;
641 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700642 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
643 if (!android::base::SetProperty(key, start)) {
644 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700645 clearAppProperties();
646 return false;
647 }
648 start = end;
649 i++;
650 }
651
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700652 std::string value = android::base::StringPrintf("%d", i);
653 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
654 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700655 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700656 return false;
657 }
658 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800659}
660
661// Disable all /sys/ enable files.
662static bool disableKernelTraceEvents() {
663 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700664 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800665 const TracingCategory &c = k_categories[i];
666 for (int j = 0; j < MAX_SYS_FILES; j++) {
667 const char* path = c.sysfiles[j].path;
668 if (path != NULL && fileIsWritable(path)) {
669 ok &= setKernelOptionEnable(path, false);
670 }
671 }
672 }
673 return ok;
674}
675
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700676// Verify that the comma separated list of functions are being traced by the
677// kernel.
678static bool verifyKernelTraceFuncs(const char* funcs)
679{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100680 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800681 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100682 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700683 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100684 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700685 }
686
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100687 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700688
689 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100690 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700691 bool ok = true;
692 char* myFuncs = strdup(funcs);
693 char* func = strtok(myFuncs, ",");
694 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100695 if (!strchr(func, '*')) {
696 String8 fancyFunc = String8::format("\n%s\n", func);
697 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
698 if (!found || func[0] == '\0') {
699 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
700 "to trace.\n", func);
701 ok = false;
702 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700703 }
704 func = strtok(NULL, ",");
705 }
706 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700707 return ok;
708}
709
710// Set the comma separated list of functions that the kernel is to trace.
711static bool setKernelTraceFuncs(const char* funcs)
712{
713 bool ok = true;
714
715 if (funcs == NULL || funcs[0] == '\0') {
716 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700717 if (fileIsWritable(k_currentTracerPath)) {
718 ok &= writeStr(k_currentTracerPath, "nop");
719 }
720 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700721 ok &= truncateFile(k_ftraceFilterPath);
722 }
723 } else {
724 // Enable kernel function tracing.
725 ok &= writeStr(k_currentTracerPath, "function_graph");
726 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
727 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
728 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
729 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
730
731 // Set the requested filter functions.
732 ok &= truncateFile(k_ftraceFilterPath);
733 char* myFuncs = strdup(funcs);
734 char* func = strtok(myFuncs, ",");
735 while (func) {
736 ok &= appendStr(k_ftraceFilterPath, func);
737 func = strtok(NULL, ",");
738 }
739 free(myFuncs);
740
741 // Verify that the set functions are being traced.
742 if (ok) {
743 ok &= verifyKernelTraceFuncs(funcs);
744 }
745 }
746
747 return ok;
748}
749
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900750static bool setCategoryEnable(const char* name, bool enable)
751{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700752 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900753 const TracingCategory& c = k_categories[i];
754 if (strcmp(name, c.name) == 0) {
755 if (isCategorySupported(c)) {
756 g_categoryEnables[i] = enable;
757 return true;
758 } else {
759 if (isCategorySupportedForRoot(c)) {
760 fprintf(stderr, "error: category \"%s\" requires root "
761 "privileges.\n", name);
762 } else {
763 fprintf(stderr, "error: category \"%s\" is not supported "
764 "on this device.\n", name);
765 }
766 return false;
767 }
768 }
769 }
770 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
771 return false;
772}
773
774static bool setCategoriesEnableFromFile(const char* categories_file)
775{
776 if (!categories_file) {
777 return true;
778 }
779 Tokenizer* tokenizer = NULL;
780 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
781 return false;
782 }
783 bool ok = true;
784 while (!tokenizer->isEol()) {
785 String8 token = tokenizer->nextToken(" ");
786 if (token.isEmpty()) {
787 tokenizer->skipDelimiters(" ");
788 continue;
789 }
790 ok &= setCategoryEnable(token.string(), true);
791 }
792 delete tokenizer;
793 return ok;
794}
795
Hector Dearman11845782018-03-08 14:35:44 +0000796static bool setUpUserspaceTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800797{
798 bool ok = true;
799
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800800 // Set up the tags property.
801 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700802 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800803 if (g_categoryEnables[i]) {
804 const TracingCategory &c = k_categories[i];
805 tags |= c.tags;
806 }
807 }
808 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700809
810 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700811 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700812 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
813 coreServicesTagEnabled = g_categoryEnables[i];
814 }
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700815
816 // Set whether to poke PDX services in this session.
817 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
818 g_tracePdx = g_categoryEnables[i];
819 }
sergeyvdb404152016-05-02 19:26:07 -0700820 }
821
822 std::string packageList(g_debugAppCmdLine);
823 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700824 if (!packageList.empty()) {
825 packageList += ",";
826 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700827 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700828 }
Dan Austin09a79872016-05-31 13:27:03 -0700829 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700830 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100831 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800832
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700833 if (g_tracePdx) {
834 ok &= ServiceUtility::PokeServices();
835 }
836
Hector Dearman11845782018-03-08 14:35:44 +0000837 return ok;
838}
839
840static void cleanUpUserspaceTracing()
841{
842 setTagsProperty(0);
843 clearAppProperties();
844 pokeBinderServices();
845
846 if (g_tracePdx) {
847 ServiceUtility::PokeServices();
848 }
849}
850
851
852// Set all the kernel tracing settings to the desired state for this trace
853// capture.
854static bool setUpKernelTracing()
855{
856 bool ok = true;
857
Carmen Jacksonab1118e2018-05-22 10:29:47 -0700858 ok &= setUserInitiatedTraceProperty(true);
859
Hector Dearman11845782018-03-08 14:35:44 +0000860 // Set up the tracing options.
861 ok &= setCategoriesEnableFromFile(g_categoriesFile);
862 ok &= setTraceOverwriteEnable(g_traceOverwrite);
863 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
864 // TODO: Re-enable after stabilization
865 //ok &= setCmdlineSize();
866 ok &= setClock();
867 ok &= setPrintTgidEnableIfPresent(true);
868 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
869
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800870 // Disable all the sysfs enables. This is done as a separate loop from
871 // the enables to allow the same enable to exist in multiple categories.
872 ok &= disableKernelTraceEvents();
873
874 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700875 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800876 if (g_categoryEnables[i]) {
877 const TracingCategory &c = k_categories[i];
878 for (int j = 0; j < MAX_SYS_FILES; j++) {
879 const char* path = c.sysfiles[j].path;
880 bool required = c.sysfiles[j].required == REQ;
881 if (path != NULL) {
882 if (fileIsWritable(path)) {
883 ok &= setKernelOptionEnable(path, true);
884 } else if (required) {
885 fprintf(stderr, "error writing file %s\n", path);
886 ok = false;
887 }
888 }
889 }
890 }
891 }
892
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800893 return ok;
894}
895
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700896// Reset all the kernel tracing settings to their default state.
Hector Dearman11845782018-03-08 14:35:44 +0000897static void cleanUpKernelTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800898{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800899 // Disable all tracing that we're able to.
900 disableKernelTraceEvents();
901
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800902 // Set the options back to their defaults.
903 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700904 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700905 setPrintTgidEnableIfPresent(false);
906 setKernelTraceFuncs(NULL);
Carmen Jacksonab1118e2018-05-22 10:29:47 -0700907 setUserInitiatedTraceProperty(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700908}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800909
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700910// Enable tracing in the kernel.
911static bool startTrace()
912{
913 return setTracingEnabled(true);
914}
915
916// Disable tracing in the kernel.
917static void stopTrace()
918{
919 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800920}
921
Martijn Coenend9535872015-11-26 10:00:55 +0100922// Read data from the tracing pipe and forward to stdout
923static void streamTrace()
924{
925 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800926 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100927 if (traceFD == -1) {
928 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
929 strerror(errno), errno);
930 return;
931 }
932 while (!g_traceAborted) {
933 ssize_t bytes_read = read(traceFD, trace_data, 4096);
934 if (bytes_read > 0) {
935 write(STDOUT_FILENO, trace_data, bytes_read);
936 fflush(stdout);
937 } else {
938 if (!g_traceAborted) {
939 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
940 bytes_read, errno, strerror(errno));
941 }
942 break;
943 }
944 }
945}
946
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800947// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700948static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800949{
John Reck6c8ac922016-03-28 11:25:30 -0700950 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800951 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800952 if (traceFD == -1) {
953 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
954 strerror(errno), errno);
955 return;
956 }
957
958 if (g_compress) {
959 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800960 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700961
962 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800963 if (result != Z_OK) {
964 fprintf(stderr, "error initializing zlib: %d\n", result);
965 close(traceFD);
966 return;
967 }
968
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700969 constexpr size_t bufSize = 64*1024;
970 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
971 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
972 if (!in || !out) {
973 fprintf(stderr, "couldn't allocate buffers\n");
974 close(traceFD);
975 return;
976 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800977
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700978 int flush = Z_NO_FLUSH;
979
980 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800981 zs.avail_out = bufSize;
982
983 do {
984
985 if (zs.avail_in == 0) {
986 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700987 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800988 if (result < 0) {
989 fprintf(stderr, "error reading trace: %s (%d)\n",
990 strerror(errno), errno);
991 result = Z_STREAM_END;
992 break;
993 } else if (result == 0) {
994 flush = Z_FINISH;
995 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700996 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800997 zs.avail_in = result;
998 }
999 }
1000
1001 if (zs.avail_out == 0) {
1002 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -07001003 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001004 if ((size_t)result < bufSize) {
1005 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1006 strerror(errno), errno);
1007 result = Z_STREAM_END; // skip deflate error message
1008 zs.avail_out = bufSize; // skip the final write
1009 break;
1010 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001011 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001012 zs.avail_out = bufSize;
1013 }
1014
1015 } while ((result = deflate(&zs, flush)) == Z_OK);
1016
1017 if (result != Z_STREAM_END) {
1018 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
1019 }
1020
1021 if (zs.avail_out < bufSize) {
1022 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -07001023 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001024 if ((size_t)result < bytes) {
1025 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1026 strerror(errno), errno);
1027 }
1028 }
1029
1030 result = deflateEnd(&zs);
1031 if (result != Z_OK) {
1032 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1033 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001034 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001035 char buf[4096];
1036 ssize_t rc;
1037 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1038 if (!android::base::WriteFully(outFd, buf, rc)) {
1039 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1040 break;
1041 }
1042 }
1043 if (rc == -1) {
1044 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001045 }
1046 }
1047
1048 close(traceFD);
1049}
1050
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001051static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001052{
1053 if (!g_nohup) {
1054 g_traceAborted = true;
1055 }
1056}
1057
1058static void registerSigHandler()
1059{
1060 struct sigaction sa;
1061 sigemptyset(&sa.sa_mask);
1062 sa.sa_flags = 0;
1063 sa.sa_handler = handleSignal;
1064 sigaction(SIGHUP, &sa, NULL);
1065 sigaction(SIGINT, &sa, NULL);
1066 sigaction(SIGQUIT, &sa, NULL);
1067 sigaction(SIGTERM, &sa, NULL);
1068}
1069
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001070static void listSupportedCategories()
1071{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001072 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001073 const TracingCategory& c = k_categories[i];
1074 if (isCategorySupported(c)) {
1075 printf(" %10s - %s\n", c.name, c.longname);
1076 }
1077 }
1078}
1079
1080// Print the command usage help to stderr.
1081static void showHelp(const char *cmd)
1082{
1083 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1084 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001085 " -a appname enable app-level tracing for a comma "
Daniel Colascione519a0792018-02-09 20:05:39 -08001086 "separated list of cmdlines; * is a wildcard matching any process\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001087 " -b N use a trace buffer size of N KB\n"
1088 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001089 " -f filename use the categories written in a file as space-separated\n"
1090 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001091 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001092 " -n ignore signals\n"
1093 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001094 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001095 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001096 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001097 " --async_dump dump the current contents of circular trace buffer\n"
1098 " --async_stop stop tracing and dump the current contents of circular\n"
1099 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001100 " --stream stream trace to stdout as it enters the trace buffer\n"
1101 " Note: this can take significant CPU time, and is best\n"
1102 " used for measuring things that are not affected by\n"
1103 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001104 " --list_categories\n"
1105 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001106 " -o filename write the trace to the specified file instead\n"
1107 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001108 );
1109}
1110
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001111bool findTraceFiles()
1112{
1113 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1114 static const std::string tracefs_path = "/sys/kernel/tracing/";
1115 static const std::string trace_file = "trace_marker";
1116
1117 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1118 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1119
1120 if (!tracefs && !debugfs) {
1121 fprintf(stderr, "Error: Did not find trace folder\n");
1122 return false;
1123 }
1124
1125 if (tracefs) {
1126 g_traceFolder = tracefs_path;
1127 } else {
1128 g_traceFolder = debugfs_path;
1129 }
1130
1131 return true;
1132}
1133
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001134int main(int argc, char **argv)
1135{
1136 bool async = false;
1137 bool traceStart = true;
1138 bool traceStop = true;
1139 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001140 bool traceStream = false;
Hector Dearman11845782018-03-08 14:35:44 +00001141 bool onlyUserspace = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001142
1143 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1144 showHelp(argv[0]);
1145 exit(0);
1146 }
1147
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001148 if (!findTraceFiles()) {
1149 fprintf(stderr, "No trace folder found\n");
1150 exit(-1);
1151 }
1152
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001153 for (;;) {
1154 int ret;
1155 int option_index = 0;
1156 static struct option long_options[] = {
Hector Dearman11845782018-03-08 14:35:44 +00001157 {"async_start", no_argument, 0, 0 },
1158 {"async_stop", no_argument, 0, 0 },
1159 {"async_dump", no_argument, 0, 0 },
1160 {"only_userspace", no_argument, 0, 0 },
1161 {"list_categories", no_argument, 0, 0 },
1162 {"stream", no_argument, 0, 0 },
1163 { 0, 0, 0, 0 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001164 };
1165
John Reck40b26b42016-03-30 09:44:36 -07001166 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001167 long_options, &option_index);
1168
1169 if (ret < 0) {
1170 for (int i = optind; i < argc; i++) {
1171 if (!setCategoryEnable(argv[i], true)) {
1172 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1173 exit(1);
1174 }
1175 }
1176 break;
1177 }
1178
1179 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001180 case 'a':
1181 g_debugAppCmdLine = optarg;
1182 break;
1183
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001184 case 'b':
1185 g_traceBufferSizeKB = atoi(optarg);
1186 break;
1187
1188 case 'c':
1189 g_traceOverwrite = true;
1190 break;
1191
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001192 case 'f':
1193 g_categoriesFile = optarg;
1194 break;
1195
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001196 case 'k':
1197 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001198 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001199
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001200 case 'n':
1201 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001202 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001203
1204 case 's':
1205 g_initialSleepSecs = atoi(optarg);
1206 break;
1207
1208 case 't':
1209 g_traceDurationSeconds = atoi(optarg);
1210 break;
1211
1212 case 'z':
1213 g_compress = true;
1214 break;
1215
John Reck40b26b42016-03-30 09:44:36 -07001216 case 'o':
1217 g_outputFile = optarg;
1218 break;
1219
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001220 case 0:
1221 if (!strcmp(long_options[option_index].name, "async_start")) {
1222 async = true;
1223 traceStop = false;
1224 traceDump = false;
1225 g_traceOverwrite = true;
1226 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1227 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001228 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001229 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1230 async = true;
1231 traceStart = false;
1232 traceStop = false;
Hector Dearman11845782018-03-08 14:35:44 +00001233 } else if (!strcmp(long_options[option_index].name, "only_userspace")) {
1234 onlyUserspace = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001235 } else if (!strcmp(long_options[option_index].name, "stream")) {
1236 traceStream = true;
1237 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001238 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1239 listSupportedCategories();
1240 exit(0);
1241 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001242 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001243
1244 default:
1245 fprintf(stderr, "\n");
1246 showHelp(argv[0]);
1247 exit(-1);
1248 break;
1249 }
1250 }
1251
Hector Dearman11845782018-03-08 14:35:44 +00001252 if (onlyUserspace) {
1253 if (!async || !(traceStart || traceStop)) {
1254 fprintf(stderr, "--only_userspace can only be used with "
1255 "--async_start or --async_stop\n");
1256 exit(1);
1257 }
1258 }
1259
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001260 registerSigHandler();
1261
1262 if (g_initialSleepSecs > 0) {
1263 sleep(g_initialSleepSecs);
1264 }
1265
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001266 bool ok = true;
Hector Dearman11845782018-03-08 14:35:44 +00001267
Wei Wang5b73b742018-03-08 13:33:12 -08001268 if (traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001269 ok &= setUpUserspaceTracing();
1270 }
1271
1272 if (ok && traceStart && !onlyUserspace) {
1273 ok &= setUpKernelTracing();
Wei Wang5b73b742018-03-08 13:33:12 -08001274 ok &= startTrace();
1275 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001276
1277 if (ok && traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001278
1279 if (!traceStream && !onlyUserspace) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001280 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001281 fflush(stdout);
1282 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001283
1284 // We clear the trace after starting it because tracing gets enabled for
1285 // each CPU individually in the kernel. Having the beginning of the trace
1286 // contain entries from only one CPU can cause "begin" entries without a
1287 // matching "end" entry to show up if a task gets migrated from one CPU to
1288 // another.
Hector Dearman11845782018-03-08 14:35:44 +00001289 if (!onlyUserspace)
1290 ok = clearTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001291
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001292 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001293 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001294 // Sleep to allow the trace to be captured.
1295 struct timespec timeLeft;
1296 timeLeft.tv_sec = g_traceDurationSeconds;
1297 timeLeft.tv_nsec = 0;
1298 do {
1299 if (g_traceAborted) {
1300 break;
1301 }
1302 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1303 }
Martijn Coenend9535872015-11-26 10:00:55 +01001304
1305 if (traceStream) {
1306 streamTrace();
1307 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001308 }
1309
1310 // Stop the trace and restore the default settings.
Hector Dearman11845782018-03-08 14:35:44 +00001311 if (traceStop && !onlyUserspace)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001312 stopTrace();
1313
Hector Dearman11845782018-03-08 14:35:44 +00001314 if (ok && traceDump && !onlyUserspace) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001315 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001316 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001317 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001318 int outFd = STDOUT_FILENO;
1319 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001320 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001321 }
1322 if (outFd == -1) {
1323 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1324 } else {
1325 dprintf(outFd, "TRACE:\n");
1326 dumpTrace(outFd);
1327 if (g_outputFile) {
1328 close(outFd);
1329 }
1330 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001331 } else {
1332 printf("\ntrace aborted.\n");
1333 fflush(stdout);
1334 }
1335 clearTrace();
1336 } else if (!ok) {
1337 fprintf(stderr, "unable to start tracing\n");
1338 }
1339
1340 // Reset the trace buffer size to 1.
Hector Dearman11845782018-03-08 14:35:44 +00001341 if (traceStop) {
1342 cleanUpUserspaceTracing();
1343 if (!onlyUserspace)
1344 cleanUpKernelTracing();
1345 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001346
1347 return g_traceAborted ? 1 : 0;
1348}