blob: 60be26feda4ac3b5a1d21a9886fef90a0b6522e0 [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{
John Reckedbf9ec2018-06-29 11:15:17 -0700526 // Pre-4.13 this was options/print-tgid as an android-specific option.
527 // In 4.13+ this is an upstream option called options/record-tgid
528 // Both options produce the same ftrace format change
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700529 if (fileExists(k_printTgidPath)) {
530 return setKernelOptionEnable(k_printTgidPath, enable);
531 }
John Recke757b1c2018-06-28 12:24:33 -0700532 if (fileExists(k_recordTgidPath)) {
533 return setKernelOptionEnable(k_recordTgidPath, enable);
534 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700535 return true;
536}
537
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800538// Poke all the binder-enabled processes in the system to get them to re-read
539// their system properties.
540static bool pokeBinderServices()
541{
542 sp<IServiceManager> sm = defaultServiceManager();
543 Vector<String16> services = sm->listServices();
544 for (size_t i = 0; i < services.size(); i++) {
545 sp<IBinder> obj = sm->checkService(services[i]);
546 if (obj != NULL) {
547 Parcel data;
548 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
549 NULL, 0) != OK) {
550 if (false) {
551 // XXX: For some reason this fails on tablets trying to
552 // poke the "phone" service. It's not clear whether some
553 // are expected to fail.
554 String8 svc(services[i]);
555 fprintf(stderr, "error poking binder service %s\n",
556 svc.string());
557 return false;
558 }
559 }
560 }
561 }
562 return true;
563}
564
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100565// Poke all the HAL processes in the system to get them to re-read
566// their system properties.
567static void pokeHalServices()
568{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100569 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100570 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100571 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100572 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100573
574 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800575
576 if (sm == nullptr) {
577 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
578 return;
579 }
580
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800581 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100582 for (size_t i = 0; i < interfaces.size(); i++) {
583 string fqInstanceName = interfaces[i];
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700584 string::size_type n = fqInstanceName.find('/');
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100585 if (n == std::string::npos || interfaces[i].size() == n+1)
586 continue;
587 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
588 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100589 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
590 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100591 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100592 continue;
593 }
Carmen Jackson73206122017-04-18 15:37:57 -0700594
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100595 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700596 if (interface == nullptr) {
597 // ignore
598 continue;
599 }
600
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100601 auto notifyRet = interface->notifySyspropsChanged();
602 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100603 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800604 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100605 }
606 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800607 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100608 // TODO(b/34242478) fix this when we determine the correct ACL
609 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800610 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100611}
612
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800613// Set the trace tags that userland tracing uses, and poke the running
614// processes to pick up the new value.
615static bool setTagsProperty(uint64_t tags)
616{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700617 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
618 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800619 fprintf(stderr, "error setting trace tags system property\n");
620 return false;
621 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700622 return true;
623}
624
sergeyv4144eff2016-04-28 11:40:04 -0700625static void clearAppProperties()
626{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700627 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700628 fprintf(stderr, "failed to clear system property: %s",
629 k_traceAppsNumberProperty);
630 }
631}
632
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700633// Set the system property that indicates which apps should perform
634// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700635static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700636{
sergeyv4144eff2016-04-28 11:40:04 -0700637 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700638 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700639 while (start != NULL) {
sergeyv4144eff2016-04-28 11:40:04 -0700640 char* end = strchr(start, ',');
641 if (end != NULL) {
642 *end = '\0';
643 end++;
644 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700645 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
646 if (!android::base::SetProperty(key, start)) {
647 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700648 clearAppProperties();
649 return false;
650 }
651 start = end;
652 i++;
653 }
654
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700655 std::string value = android::base::StringPrintf("%d", i);
656 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
657 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700658 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700659 return false;
660 }
661 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800662}
663
664// Disable all /sys/ enable files.
665static bool disableKernelTraceEvents() {
666 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700667 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800668 const TracingCategory &c = k_categories[i];
669 for (int j = 0; j < MAX_SYS_FILES; j++) {
670 const char* path = c.sysfiles[j].path;
671 if (path != NULL && fileIsWritable(path)) {
672 ok &= setKernelOptionEnable(path, false);
673 }
674 }
675 }
676 return ok;
677}
678
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700679// Verify that the comma separated list of functions are being traced by the
680// kernel.
681static bool verifyKernelTraceFuncs(const char* funcs)
682{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100683 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800684 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100685 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700686 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100687 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700688 }
689
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100690 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700691
692 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100693 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700694 bool ok = true;
695 char* myFuncs = strdup(funcs);
696 char* func = strtok(myFuncs, ",");
697 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100698 if (!strchr(func, '*')) {
699 String8 fancyFunc = String8::format("\n%s\n", func);
700 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
701 if (!found || func[0] == '\0') {
702 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
703 "to trace.\n", func);
704 ok = false;
705 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700706 }
707 func = strtok(NULL, ",");
708 }
709 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700710 return ok;
711}
712
713// Set the comma separated list of functions that the kernel is to trace.
714static bool setKernelTraceFuncs(const char* funcs)
715{
716 bool ok = true;
717
718 if (funcs == NULL || funcs[0] == '\0') {
719 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700720 if (fileIsWritable(k_currentTracerPath)) {
721 ok &= writeStr(k_currentTracerPath, "nop");
722 }
723 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700724 ok &= truncateFile(k_ftraceFilterPath);
725 }
726 } else {
727 // Enable kernel function tracing.
728 ok &= writeStr(k_currentTracerPath, "function_graph");
729 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
730 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
731 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
732 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
733
734 // Set the requested filter functions.
735 ok &= truncateFile(k_ftraceFilterPath);
736 char* myFuncs = strdup(funcs);
737 char* func = strtok(myFuncs, ",");
738 while (func) {
739 ok &= appendStr(k_ftraceFilterPath, func);
740 func = strtok(NULL, ",");
741 }
742 free(myFuncs);
743
744 // Verify that the set functions are being traced.
745 if (ok) {
746 ok &= verifyKernelTraceFuncs(funcs);
747 }
748 }
749
750 return ok;
751}
752
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900753static bool setCategoryEnable(const char* name, bool enable)
754{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700755 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900756 const TracingCategory& c = k_categories[i];
757 if (strcmp(name, c.name) == 0) {
758 if (isCategorySupported(c)) {
759 g_categoryEnables[i] = enable;
760 return true;
761 } else {
762 if (isCategorySupportedForRoot(c)) {
763 fprintf(stderr, "error: category \"%s\" requires root "
764 "privileges.\n", name);
765 } else {
766 fprintf(stderr, "error: category \"%s\" is not supported "
767 "on this device.\n", name);
768 }
769 return false;
770 }
771 }
772 }
773 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
774 return false;
775}
776
777static bool setCategoriesEnableFromFile(const char* categories_file)
778{
779 if (!categories_file) {
780 return true;
781 }
782 Tokenizer* tokenizer = NULL;
783 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
784 return false;
785 }
786 bool ok = true;
787 while (!tokenizer->isEol()) {
788 String8 token = tokenizer->nextToken(" ");
789 if (token.isEmpty()) {
790 tokenizer->skipDelimiters(" ");
791 continue;
792 }
793 ok &= setCategoryEnable(token.string(), true);
794 }
795 delete tokenizer;
796 return ok;
797}
798
Hector Dearman11845782018-03-08 14:35:44 +0000799static bool setUpUserspaceTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800800{
801 bool ok = true;
802
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800803 // Set up the tags property.
804 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700805 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800806 if (g_categoryEnables[i]) {
807 const TracingCategory &c = k_categories[i];
808 tags |= c.tags;
809 }
810 }
811 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700812
813 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700814 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700815 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
816 coreServicesTagEnabled = g_categoryEnables[i];
817 }
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700818
819 // Set whether to poke PDX services in this session.
820 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
821 g_tracePdx = g_categoryEnables[i];
822 }
sergeyvdb404152016-05-02 19:26:07 -0700823 }
824
825 std::string packageList(g_debugAppCmdLine);
826 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700827 if (!packageList.empty()) {
828 packageList += ",";
829 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700830 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700831 }
Dan Austin09a79872016-05-31 13:27:03 -0700832 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700833 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100834 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800835
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700836 if (g_tracePdx) {
837 ok &= ServiceUtility::PokeServices();
838 }
839
Hector Dearman11845782018-03-08 14:35:44 +0000840 return ok;
841}
842
843static void cleanUpUserspaceTracing()
844{
845 setTagsProperty(0);
846 clearAppProperties();
847 pokeBinderServices();
848
849 if (g_tracePdx) {
850 ServiceUtility::PokeServices();
851 }
852}
853
854
855// Set all the kernel tracing settings to the desired state for this trace
856// capture.
857static bool setUpKernelTracing()
858{
859 bool ok = true;
860
Carmen Jacksonab1118e2018-05-22 10:29:47 -0700861 ok &= setUserInitiatedTraceProperty(true);
862
Hector Dearman11845782018-03-08 14:35:44 +0000863 // Set up the tracing options.
864 ok &= setCategoriesEnableFromFile(g_categoriesFile);
865 ok &= setTraceOverwriteEnable(g_traceOverwrite);
866 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
867 // TODO: Re-enable after stabilization
868 //ok &= setCmdlineSize();
869 ok &= setClock();
870 ok &= setPrintTgidEnableIfPresent(true);
871 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
872
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800873 // Disable all the sysfs enables. This is done as a separate loop from
874 // the enables to allow the same enable to exist in multiple categories.
875 ok &= disableKernelTraceEvents();
876
877 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700878 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800879 if (g_categoryEnables[i]) {
880 const TracingCategory &c = k_categories[i];
881 for (int j = 0; j < MAX_SYS_FILES; j++) {
882 const char* path = c.sysfiles[j].path;
883 bool required = c.sysfiles[j].required == REQ;
884 if (path != NULL) {
885 if (fileIsWritable(path)) {
886 ok &= setKernelOptionEnable(path, true);
887 } else if (required) {
888 fprintf(stderr, "error writing file %s\n", path);
889 ok = false;
890 }
891 }
892 }
893 }
894 }
895
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800896 return ok;
897}
898
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700899// Reset all the kernel tracing settings to their default state.
Hector Dearman11845782018-03-08 14:35:44 +0000900static void cleanUpKernelTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800901{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800902 // Disable all tracing that we're able to.
903 disableKernelTraceEvents();
904
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800905 // Set the options back to their defaults.
906 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700907 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700908 setPrintTgidEnableIfPresent(false);
909 setKernelTraceFuncs(NULL);
Carmen Jacksonab1118e2018-05-22 10:29:47 -0700910 setUserInitiatedTraceProperty(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700911}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800912
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700913// Enable tracing in the kernel.
914static bool startTrace()
915{
916 return setTracingEnabled(true);
917}
918
919// Disable tracing in the kernel.
920static void stopTrace()
921{
922 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800923}
924
Martijn Coenend9535872015-11-26 10:00:55 +0100925// Read data from the tracing pipe and forward to stdout
926static void streamTrace()
927{
928 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800929 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100930 if (traceFD == -1) {
931 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
932 strerror(errno), errno);
933 return;
934 }
935 while (!g_traceAborted) {
936 ssize_t bytes_read = read(traceFD, trace_data, 4096);
937 if (bytes_read > 0) {
938 write(STDOUT_FILENO, trace_data, bytes_read);
939 fflush(stdout);
940 } else {
941 if (!g_traceAborted) {
942 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
943 bytes_read, errno, strerror(errno));
944 }
945 break;
946 }
947 }
948}
949
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800950// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700951static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800952{
John Reck6c8ac922016-03-28 11:25:30 -0700953 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800954 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800955 if (traceFD == -1) {
956 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
957 strerror(errno), errno);
958 return;
959 }
960
961 if (g_compress) {
962 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800963 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700964
965 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800966 if (result != Z_OK) {
967 fprintf(stderr, "error initializing zlib: %d\n", result);
968 close(traceFD);
969 return;
970 }
971
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700972 constexpr size_t bufSize = 64*1024;
973 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
974 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
975 if (!in || !out) {
976 fprintf(stderr, "couldn't allocate buffers\n");
977 close(traceFD);
978 return;
979 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800980
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700981 int flush = Z_NO_FLUSH;
982
983 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800984 zs.avail_out = bufSize;
985
986 do {
987
988 if (zs.avail_in == 0) {
989 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700990 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800991 if (result < 0) {
992 fprintf(stderr, "error reading trace: %s (%d)\n",
993 strerror(errno), errno);
994 result = Z_STREAM_END;
995 break;
996 } else if (result == 0) {
997 flush = Z_FINISH;
998 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700999 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001000 zs.avail_in = result;
1001 }
1002 }
1003
1004 if (zs.avail_out == 0) {
1005 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -07001006 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001007 if ((size_t)result < bufSize) {
1008 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1009 strerror(errno), errno);
1010 result = Z_STREAM_END; // skip deflate error message
1011 zs.avail_out = bufSize; // skip the final write
1012 break;
1013 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001014 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001015 zs.avail_out = bufSize;
1016 }
1017
1018 } while ((result = deflate(&zs, flush)) == Z_OK);
1019
1020 if (result != Z_STREAM_END) {
1021 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
1022 }
1023
1024 if (zs.avail_out < bufSize) {
1025 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -07001026 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001027 if ((size_t)result < bytes) {
1028 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1029 strerror(errno), errno);
1030 }
1031 }
1032
1033 result = deflateEnd(&zs);
1034 if (result != Z_OK) {
1035 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1036 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001037 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001038 char buf[4096];
1039 ssize_t rc;
1040 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1041 if (!android::base::WriteFully(outFd, buf, rc)) {
1042 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1043 break;
1044 }
1045 }
1046 if (rc == -1) {
1047 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001048 }
1049 }
1050
1051 close(traceFD);
1052}
1053
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001054static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001055{
1056 if (!g_nohup) {
1057 g_traceAborted = true;
1058 }
1059}
1060
1061static void registerSigHandler()
1062{
1063 struct sigaction sa;
1064 sigemptyset(&sa.sa_mask);
1065 sa.sa_flags = 0;
1066 sa.sa_handler = handleSignal;
1067 sigaction(SIGHUP, &sa, NULL);
1068 sigaction(SIGINT, &sa, NULL);
1069 sigaction(SIGQUIT, &sa, NULL);
1070 sigaction(SIGTERM, &sa, NULL);
1071}
1072
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001073static void listSupportedCategories()
1074{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001075 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001076 const TracingCategory& c = k_categories[i];
1077 if (isCategorySupported(c)) {
1078 printf(" %10s - %s\n", c.name, c.longname);
1079 }
1080 }
1081}
1082
1083// Print the command usage help to stderr.
1084static void showHelp(const char *cmd)
1085{
1086 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1087 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001088 " -a appname enable app-level tracing for a comma "
Daniel Colascione519a0792018-02-09 20:05:39 -08001089 "separated list of cmdlines; * is a wildcard matching any process\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001090 " -b N use a trace buffer size of N KB\n"
1091 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001092 " -f filename use the categories written in a file as space-separated\n"
1093 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001094 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001095 " -n ignore signals\n"
1096 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001097 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001098 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001099 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001100 " --async_dump dump the current contents of circular trace buffer\n"
1101 " --async_stop stop tracing and dump the current contents of circular\n"
1102 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001103 " --stream stream trace to stdout as it enters the trace buffer\n"
1104 " Note: this can take significant CPU time, and is best\n"
1105 " used for measuring things that are not affected by\n"
1106 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001107 " --list_categories\n"
1108 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001109 " -o filename write the trace to the specified file instead\n"
1110 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001111 );
1112}
1113
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001114bool findTraceFiles()
1115{
1116 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1117 static const std::string tracefs_path = "/sys/kernel/tracing/";
1118 static const std::string trace_file = "trace_marker";
1119
1120 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1121 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1122
1123 if (!tracefs && !debugfs) {
1124 fprintf(stderr, "Error: Did not find trace folder\n");
1125 return false;
1126 }
1127
1128 if (tracefs) {
1129 g_traceFolder = tracefs_path;
1130 } else {
1131 g_traceFolder = debugfs_path;
1132 }
1133
1134 return true;
1135}
1136
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001137int main(int argc, char **argv)
1138{
1139 bool async = false;
1140 bool traceStart = true;
1141 bool traceStop = true;
1142 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001143 bool traceStream = false;
Hector Dearman11845782018-03-08 14:35:44 +00001144 bool onlyUserspace = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001145
1146 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1147 showHelp(argv[0]);
1148 exit(0);
1149 }
1150
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001151 if (!findTraceFiles()) {
1152 fprintf(stderr, "No trace folder found\n");
1153 exit(-1);
1154 }
1155
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001156 for (;;) {
1157 int ret;
1158 int option_index = 0;
1159 static struct option long_options[] = {
Hector Dearman11845782018-03-08 14:35:44 +00001160 {"async_start", no_argument, 0, 0 },
1161 {"async_stop", no_argument, 0, 0 },
1162 {"async_dump", no_argument, 0, 0 },
1163 {"only_userspace", no_argument, 0, 0 },
1164 {"list_categories", no_argument, 0, 0 },
1165 {"stream", no_argument, 0, 0 },
1166 { 0, 0, 0, 0 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001167 };
1168
John Reck40b26b42016-03-30 09:44:36 -07001169 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001170 long_options, &option_index);
1171
1172 if (ret < 0) {
1173 for (int i = optind; i < argc; i++) {
1174 if (!setCategoryEnable(argv[i], true)) {
1175 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1176 exit(1);
1177 }
1178 }
1179 break;
1180 }
1181
1182 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001183 case 'a':
1184 g_debugAppCmdLine = optarg;
1185 break;
1186
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001187 case 'b':
1188 g_traceBufferSizeKB = atoi(optarg);
1189 break;
1190
1191 case 'c':
1192 g_traceOverwrite = true;
1193 break;
1194
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001195 case 'f':
1196 g_categoriesFile = optarg;
1197 break;
1198
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001199 case 'k':
1200 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001201 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001202
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001203 case 'n':
1204 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001205 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001206
1207 case 's':
1208 g_initialSleepSecs = atoi(optarg);
1209 break;
1210
1211 case 't':
1212 g_traceDurationSeconds = atoi(optarg);
1213 break;
1214
1215 case 'z':
1216 g_compress = true;
1217 break;
1218
John Reck40b26b42016-03-30 09:44:36 -07001219 case 'o':
1220 g_outputFile = optarg;
1221 break;
1222
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001223 case 0:
1224 if (!strcmp(long_options[option_index].name, "async_start")) {
1225 async = true;
1226 traceStop = false;
1227 traceDump = false;
1228 g_traceOverwrite = true;
1229 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1230 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001231 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001232 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1233 async = true;
1234 traceStart = false;
1235 traceStop = false;
Hector Dearman11845782018-03-08 14:35:44 +00001236 } else if (!strcmp(long_options[option_index].name, "only_userspace")) {
1237 onlyUserspace = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001238 } else if (!strcmp(long_options[option_index].name, "stream")) {
1239 traceStream = true;
1240 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001241 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1242 listSupportedCategories();
1243 exit(0);
1244 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001245 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001246
1247 default:
1248 fprintf(stderr, "\n");
1249 showHelp(argv[0]);
1250 exit(-1);
1251 break;
1252 }
1253 }
1254
Hector Dearman11845782018-03-08 14:35:44 +00001255 if (onlyUserspace) {
1256 if (!async || !(traceStart || traceStop)) {
1257 fprintf(stderr, "--only_userspace can only be used with "
1258 "--async_start or --async_stop\n");
1259 exit(1);
1260 }
1261 }
1262
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001263 registerSigHandler();
1264
1265 if (g_initialSleepSecs > 0) {
1266 sleep(g_initialSleepSecs);
1267 }
1268
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001269 bool ok = true;
Hector Dearman11845782018-03-08 14:35:44 +00001270
Wei Wang5b73b742018-03-08 13:33:12 -08001271 if (traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001272 ok &= setUpUserspaceTracing();
1273 }
1274
1275 if (ok && traceStart && !onlyUserspace) {
1276 ok &= setUpKernelTracing();
Wei Wang5b73b742018-03-08 13:33:12 -08001277 ok &= startTrace();
1278 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001279
1280 if (ok && traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001281
1282 if (!traceStream && !onlyUserspace) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001283 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001284 fflush(stdout);
1285 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001286
1287 // We clear the trace after starting it because tracing gets enabled for
1288 // each CPU individually in the kernel. Having the beginning of the trace
1289 // contain entries from only one CPU can cause "begin" entries without a
1290 // matching "end" entry to show up if a task gets migrated from one CPU to
1291 // another.
Hector Dearman11845782018-03-08 14:35:44 +00001292 if (!onlyUserspace)
1293 ok = clearTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001294
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001295 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001296 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001297 // Sleep to allow the trace to be captured.
1298 struct timespec timeLeft;
1299 timeLeft.tv_sec = g_traceDurationSeconds;
1300 timeLeft.tv_nsec = 0;
1301 do {
1302 if (g_traceAborted) {
1303 break;
1304 }
1305 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1306 }
Martijn Coenend9535872015-11-26 10:00:55 +01001307
1308 if (traceStream) {
1309 streamTrace();
1310 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001311 }
1312
1313 // Stop the trace and restore the default settings.
Hector Dearman11845782018-03-08 14:35:44 +00001314 if (traceStop && !onlyUserspace)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001315 stopTrace();
1316
Hector Dearman11845782018-03-08 14:35:44 +00001317 if (ok && traceDump && !onlyUserspace) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001318 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001319 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001320 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001321 int outFd = STDOUT_FILENO;
1322 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001323 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001324 }
1325 if (outFd == -1) {
1326 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1327 } else {
1328 dprintf(outFd, "TRACE:\n");
1329 dumpTrace(outFd);
1330 if (g_outputFile) {
1331 close(outFd);
1332 }
1333 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001334 } else {
1335 printf("\ntrace aborted.\n");
1336 fflush(stdout);
1337 }
1338 clearTrace();
1339 } else if (!ok) {
1340 fprintf(stderr, "unable to start tracing\n");
1341 }
1342
1343 // Reset the trace buffer size to 1.
Hector Dearman11845782018-03-08 14:35:44 +00001344 if (traceStop) {
1345 cleanUpUserspaceTracing();
1346 if (!onlyUserspace)
1347 cleanUpKernelTracing();
1348 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001349
1350 return g_traceAborted ? 1 : 0;
1351}