blob: 94eaf059a236fc14ddda53a32fdad21751068dca [file] [log] [blame]
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Paul Lawrence2cd93cc2017-01-17 09:50:18 -080017#define LOG_TAG "atrace"
John Reck40b26b42016-03-30 09:44:36 -070018
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080019#include <errno.h>
20#include <fcntl.h>
21#include <getopt.h>
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070022#include <inttypes.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080023#include <signal.h>
24#include <stdarg.h>
25#include <stdbool.h>
26#include <stdio.h>
27#include <stdlib.h>
Elliott Hughes3da5d232015-01-25 08:35:20 -080028#include <string.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080029#include <time.h>
Martijn Coenend9535872015-11-26 10:00:55 +010030#include <unistd.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080031#include <zlib.h>
32
Carmen Jacksonea826792017-05-05 11:42:32 -070033#include <fstream>
Elliott Hughesa252f4d2016-07-21 17:12:15 -070034#include <memory>
35
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080036#include <binder/IBinder.h>
37#include <binder/IServiceManager.h>
38#include <binder/Parcel.h>
39
Martijn Coenenee9b97e2016-11-16 16:00:26 +010040#include <android/hidl/manager/1.0/IServiceManager.h>
41#include <hidl/ServiceManagement.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080042
Corey Tabakaa6c0a722017-05-31 16:37:40 -070043#include <pdx/default_transport/service_utility.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080044#include <utils/String8.h>
John Reck469a1942015-03-26 15:31:35 -070045#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +090046#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080047#include <utils/Trace.h>
Stephane Gasparinid8419c22016-03-02 13:45:15 +010048#include <android-base/file.h>
Elliott Hughes5fd6ff62017-03-28 14:55:31 -070049#include <android-base/macros.h>
50#include <android-base/properties.h>
51#include <android-base/stringprintf.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080052
53using namespace android;
Corey Tabakaa6c0a722017-05-31 16:37:40 -070054using pdx::default_transport::ServiceUtility;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080055
Martijn Coenenee9b97e2016-11-16 16:00:26 +010056using std::string;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080057
sergeyv4144eff2016-04-28 11:40:04 -070058#define MAX_SYS_FILES 10
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080059
60const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
Carmen Jackson65ecfbb2018-05-22 10:29:47 -070061const char* k_userInitiatedTraceProperty = "debug.atrace.user_initiated";
sergeyv4144eff2016-04-28 11:40:04 -070062
63const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
64const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070065const char* k_coreServiceCategory = "core_services";
Corey Tabakaa6c0a722017-05-31 16:37:40 -070066const char* k_pdxServiceCategory = "pdx";
sergeyvdb404152016-05-02 19:26:07 -070067const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080068
69typedef enum { OPT, REQ } requiredness ;
70
71struct TracingCategory {
72 // The name identifying the category.
73 const char* name;
74
75 // A longer description of the category.
76 const char* longname;
77
78 // The userland tracing tags that the category enables.
79 uint64_t tags;
80
81 // The fname==NULL terminated list of /sys/ files that the category
82 // enables.
83 struct {
84 // Whether the file must be writable in order to enable the tracing
85 // category.
86 requiredness required;
87
88 // The path to the enable file.
89 const char* path;
90 } sysfiles[MAX_SYS_FILES];
91};
92
93/* Tracing categories */
94static const TracingCategory k_categories[] = {
John Reck732a29a2017-05-24 16:09:21 -070095 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, {
96 { OPT, "events/mdss/enable" },
Wei Wangbcfb4872018-02-13 10:47:23 -080097 { OPT, "events/sde/enable" },
John Reck732a29a2017-05-24 16:09:21 -070098 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070099 { "input", "Input", ATRACE_TAG_INPUT, { } },
100 { "view", "View System", ATRACE_TAG_VIEW, { } },
101 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
102 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
103 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -0500104 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700105 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
106 { "video", "Video", ATRACE_TAG_VIDEO, { } },
107 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
108 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -0700109 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -0700110 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -0700111 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -0700112 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700113 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 14:36:20 -0700114 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-07-01 01:46:25 +0900115 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Greg Hackmannbbd7d992014-12-01 14:43:34 -0800116 { "database", "Database", ATRACE_TAG_DATABASE, { } },
Felipe Leme0f97c1d2016-09-07 11:33:26 -0700117 { "network", "Network", ATRACE_TAG_NETWORK, { } },
Josh Gao468b4cb2016-11-29 10:55:21 -0800118 { "adb", "ADB", ATRACE_TAG_ADB, { } },
Martijn Coenen42f2ab42018-03-09 09:27:32 +0100119 { "vibrator", "Vibrator", ATRACE_TAG_VIBRATOR, { } },
120 { "aidl", "AIDL calls", ATRACE_TAG_AIDL, { } },
Mika Raentob363cf52018-04-23 22:09:13 +0100121 { "nnapi", "NNAPI", ATRACE_TAG_NNAPI, { } },
sergeyvdb404152016-05-02 19:26:07 -0700122 { k_coreServiceCategory, "Core services", 0, { } },
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700123 { k_pdxServiceCategory, "PDX services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700124 { "sched", "CPU Scheduling", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800125 { REQ, "events/sched/sched_switch/enable" },
126 { REQ, "events/sched/sched_wakeup/enable" },
Joel Fernandesee593e22017-06-04 13:05:59 -0700127 { OPT, "events/sched/sched_waking/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800128 { OPT, "events/sched/sched_blocked_reason/enable" },
129 { OPT, "events/sched/sched_cpu_hotplug/enable" },
Wei Wangca49dfc2018-05-03 15:45:20 -0700130 { OPT, "events/sched/sched_pi_setprio/enable" },
Joel Fernandes4dfca7c2017-06-15 16:53:52 -0700131 { OPT, "events/cgroup/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800132 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700133 { "irq", "IRQ Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800134 { REQ, "events/irq/enable" },
135 { OPT, "events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700136 } },
Joel Fernandes6ccad102017-08-31 08:35:05 -0700137 { "irqoff", "IRQ-disabled code section tracing", 0, {
138 { REQ, "events/preemptirq/irq_enable/enable" },
139 { REQ, "events/preemptirq/irq_disable/enable" },
140 } },
141 { "preemptoff", "Preempt-disabled code section tracing", 0, {
142 { REQ, "events/preemptirq/preempt_enable/enable" },
143 { REQ, "events/preemptirq/preempt_disable/enable" },
144 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100145 { "i2c", "I2C Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800146 { REQ, "events/i2c/enable" },
147 { REQ, "events/i2c/i2c_read/enable" },
148 { REQ, "events/i2c/i2c_write/enable" },
149 { REQ, "events/i2c/i2c_result/enable" },
150 { REQ, "events/i2c/i2c_reply/enable" },
151 { OPT, "events/i2c/smbus_read/enable" },
152 { OPT, "events/i2c/smbus_write/enable" },
153 { OPT, "events/i2c/smbus_result/enable" },
154 { OPT, "events/i2c/smbus_reply/enable" },
Michael Wright43fb6782016-08-18 19:56:43 +0100155 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700156 { "freq", "CPU Frequency", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800157 { REQ, "events/power/cpu_frequency/enable" },
158 { OPT, "events/power/clock_set_rate/enable" },
Kevin DuBois062e0b92017-11-03 15:44:08 -0700159 { OPT, "events/power/clock_disable/enable" },
160 { OPT, "events/power/clock_enable/enable" },
Wei Wang53305dd2018-02-22 11:40:07 -0800161 { OPT, "events/clk/clk_set_rate/enable" },
162 { OPT, "events/clk/clk_disable/enable" },
163 { OPT, "events/clk/clk_enable/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800164 { OPT, "events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800165 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700166 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800167 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800168 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700169 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800170 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800171 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700172 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800173 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
174 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
175 { OPT, "events/f2fs/f2fs_write_begin/enable" },
176 { OPT, "events/f2fs/f2fs_write_end/enable" },
177 { OPT, "events/ext4/ext4_da_write_begin/enable" },
178 { OPT, "events/ext4/ext4_da_write_end/enable" },
179 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
180 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
181 { REQ, "events/block/block_rq_issue/enable" },
182 { REQ, "events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800183 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700184 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800185 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700186 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700187 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800188 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800189 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700190 { "sync", "Synchronization", 0, {
Jesse Hallae001a32018-05-15 12:02:15 -0700191 // before linux kernel 4.9
192 { OPT, "events/sync/enable" },
193 // starting in linux kernel 4.9
194 { OPT, "events/fence/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800195 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700196 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800197 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800198 } },
Colin Cross580407f2014-08-18 15:22:13 -0700199 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800200 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
201 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
202 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
203 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Marc Hittingerf1f62e32017-05-17 15:57:43 -0700204 { REQ, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700205 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800206 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800207 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800208 } },
Scott Bauerae473362015-06-08 16:32:36 -0700209 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800210 { REQ, "events/binder/binder_transaction/enable" },
211 { REQ, "events/binder/binder_transaction_received/enable" },
Mika Raento80c3e5d2018-06-25 16:47:24 +0100212 { REQ, "events/binder/binder_transaction_alloc_buf/enable" },
Martijn Coenen7f3d7a22017-05-26 09:50:55 -0700213 { OPT, "events/binder/binder_set_priority/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700214 } },
215 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800216 { OPT, "events/binder/binder_lock/enable" },
217 { OPT, "events/binder/binder_locked/enable" },
218 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700219 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200220 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800221 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200222 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800223};
224
225/* Command line options */
226static int g_traceDurationSeconds = 5;
227static bool g_traceOverwrite = false;
228static int g_traceBufferSizeKB = 2048;
229static bool g_compress = false;
230static bool g_nohup = false;
231static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900232static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700233static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700234static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700235static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800236
237/* Global state */
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700238static bool g_tracePdx = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800239static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700240static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800241static std::string g_traceFolder;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800242
243/* Sys file paths */
244static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800245 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800246
247static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800248 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800249
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700250#if 0
251// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700252static const char* k_traceCmdlineSizePath =
253 "saved_cmdlines_size";
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700254#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700255
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800256static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800257 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800258
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700259static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800260 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700261
262static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800263 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700264
265static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800266 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700267
268static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800269 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700270
271static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800272 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700273
274static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800275 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700276
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700277static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800278 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700279
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800280static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800281 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800282
283static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800284 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800285
Martijn Coenend9535872015-11-26 10:00:55 +0100286static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800287 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100288
John Reck469a1942015-03-26 15:31:35 -0700289static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800290 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700291
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800292// Check whether a file exists.
293static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800294 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800295}
296
297// Check whether a file is writable.
298static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800299 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800300}
301
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700302// Truncate a file.
303static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800304{
Jamie Gennis43122e72013-03-21 14:06:31 -0700305 // This uses creat rather than truncate because some of the debug kernel
306 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
307 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800308 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700309 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800310 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700311 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700312 return false;
313 }
314
Jamie Gennis43122e72013-03-21 14:06:31 -0700315 close(traceFD);
316
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700317 return true;
318}
319
320static bool _writeStr(const char* filename, const char* str, int flags)
321{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800322 std::string fullFilename = g_traceFolder + filename;
323 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800324 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800325 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800326 strerror(errno), errno);
327 return false;
328 }
329
330 bool ok = true;
331 ssize_t len = strlen(str);
332 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800333 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800334 strerror(errno), errno);
335 ok = false;
336 }
337
338 close(fd);
339
340 return ok;
341}
342
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700343// Write a string to a file, returning true if the write was successful.
344static bool writeStr(const char* filename, const char* str)
345{
346 return _writeStr(filename, str, O_WRONLY);
347}
348
349// Append a string to a file, returning true if the write was successful.
350static bool appendStr(const char* filename, const char* str)
351{
352 return _writeStr(filename, str, O_APPEND|O_WRONLY);
353}
354
John Reck469a1942015-03-26 15:31:35 -0700355static void writeClockSyncMarker()
356{
357 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200358 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800359 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200360 if (fd == -1) {
361 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
362 strerror(errno), errno);
363 return;
364 }
John Reck469a1942015-03-26 15:31:35 -0700365 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200366
367 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
368 if (write(fd, buffer, len) != len) {
369 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
370 }
371
372 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
373 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
374 if (write(fd, buffer, len) != len) {
375 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
376 }
377
378 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700379}
380
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800381// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
382// file.
383static bool setKernelOptionEnable(const char* filename, bool enable)
384{
385 return writeStr(filename, enable ? "1" : "0");
386}
387
388// Check whether the category is supported on the device with the current
389// rootness. A category is supported only if all its required /sys/ files are
390// writable and if enabling the category will enable one or more tracing tags
391// or /sys/ files.
392static bool isCategorySupported(const TracingCategory& category)
393{
sergeyvdb404152016-05-02 19:26:07 -0700394 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700395 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700396 }
397
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700398 if (strcmp(category.name, k_pdxServiceCategory) == 0) {
399 return true;
400 }
401
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800402 bool ok = category.tags != 0;
403 for (int i = 0; i < MAX_SYS_FILES; i++) {
404 const char* path = category.sysfiles[i].path;
405 bool req = category.sysfiles[i].required == REQ;
406 if (path != NULL) {
407 if (req) {
408 if (!fileIsWritable(path)) {
409 return false;
410 } else {
411 ok = true;
412 }
413 } else {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800414 ok = true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800415 }
416 }
417 }
418 return ok;
419}
420
421// Check whether the category would be supported on the device if the user
422// were root. This function assumes that root is able to write to any file
423// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700424// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800425static bool isCategorySupportedForRoot(const TracingCategory& category)
426{
427 bool ok = category.tags != 0;
428 for (int i = 0; i < MAX_SYS_FILES; i++) {
429 const char* path = category.sysfiles[i].path;
430 bool req = category.sysfiles[i].required == REQ;
431 if (path != NULL) {
432 if (req) {
433 if (!fileExists(path)) {
434 return false;
435 } else {
436 ok = true;
437 }
438 } else {
439 ok |= fileExists(path);
440 }
441 }
442 }
443 return ok;
444}
445
446// Enable or disable overwriting of the kernel trace buffers. Disabling this
447// will cause tracing to stop once the trace buffers have filled up.
448static bool setTraceOverwriteEnable(bool enable)
449{
450 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
451}
452
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700453// Set the user initiated trace property
454static bool setUserInitiatedTraceProperty(bool enable)
455{
456 if (!android::base::SetProperty(k_userInitiatedTraceProperty, enable ? "1" : "")) {
457 fprintf(stderr, "error setting user initiated strace system property\n");
458 return false;
459 }
460 return true;
461}
462
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800463// Enable or disable kernel tracing.
464static bool setTracingEnabled(bool enable)
465{
466 return setKernelOptionEnable(k_tracingOnPath, enable);
467}
468
469// Clear the contents of the kernel trace.
470static bool clearTrace()
471{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700472 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800473}
474
475// Set the size of the kernel's trace buffer in kilobytes.
476static bool setTraceBufferSizeKB(int size)
477{
478 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800479 if (size < 1) {
480 size = 1;
481 }
482 snprintf(str, 32, "%d", size);
483 return writeStr(k_traceBufferSizePath, str);
484}
485
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700486#if 0
487// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700488// Set the default size of cmdline hashtable
489static bool setCmdlineSize()
490{
Joel Fernandesce964f22017-06-06 12:20:29 -0700491 if (fileExists(k_traceCmdlineSizePath)) {
492 return writeStr(k_traceCmdlineSizePath, "8192");
493 }
494 return true;
Joel Fernandesed80bd02017-06-02 10:19:28 -0700495}
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700496#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700497
Carmen Jacksonea826792017-05-05 11:42:32 -0700498// Set the clock to the best available option while tracing. Use 'boot' if it's
499// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700500// Any write to the trace_clock sysfs file will reset the buffer, so only
501// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700502static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800503{
Carmen Jacksonea826792017-05-05 11:42:32 -0700504 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
505 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
506 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700507
Carmen Jacksonea826792017-05-05 11:42:32 -0700508 std::string newClock;
509 if (clockStr.find("boot") != std::string::npos) {
510 newClock = "boot";
511 } else if (clockStr.find("mono") != std::string::npos) {
512 newClock = "mono";
513 } else {
514 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700515 }
516
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700517 size_t begin = clockStr.find('[') + 1;
518 size_t end = clockStr.find(']');
Carmen Jacksonea826792017-05-05 11:42:32 -0700519 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
520 return true;
521 }
522 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800523}
524
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700525static bool setPrintTgidEnableIfPresent(bool enable)
526{
527 if (fileExists(k_printTgidPath)) {
528 return setKernelOptionEnable(k_printTgidPath, enable);
529 }
530 return true;
531}
532
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800533// Poke all the binder-enabled processes in the system to get them to re-read
534// their system properties.
535static bool pokeBinderServices()
536{
537 sp<IServiceManager> sm = defaultServiceManager();
538 Vector<String16> services = sm->listServices();
539 for (size_t i = 0; i < services.size(); i++) {
540 sp<IBinder> obj = sm->checkService(services[i]);
541 if (obj != NULL) {
542 Parcel data;
543 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
544 NULL, 0) != OK) {
545 if (false) {
546 // XXX: For some reason this fails on tablets trying to
547 // poke the "phone" service. It's not clear whether some
548 // are expected to fail.
549 String8 svc(services[i]);
550 fprintf(stderr, "error poking binder service %s\n",
551 svc.string());
552 return false;
553 }
554 }
555 }
556 }
557 return true;
558}
559
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100560// Poke all the HAL processes in the system to get them to re-read
561// their system properties.
562static void pokeHalServices()
563{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100564 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100565 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100566 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100567 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100568
569 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800570
571 if (sm == nullptr) {
572 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
573 return;
574 }
575
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800576 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100577 for (size_t i = 0; i < interfaces.size(); i++) {
578 string fqInstanceName = interfaces[i];
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700579 string::size_type n = fqInstanceName.find('/');
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100580 if (n == std::string::npos || interfaces[i].size() == n+1)
581 continue;
582 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
583 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100584 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
585 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100586 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100587 continue;
588 }
Carmen Jackson73206122017-04-18 15:37:57 -0700589
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100590 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700591 if (interface == nullptr) {
592 // ignore
593 continue;
594 }
595
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100596 auto notifyRet = interface->notifySyspropsChanged();
597 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100598 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800599 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100600 }
601 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800602 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100603 // TODO(b/34242478) fix this when we determine the correct ACL
604 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800605 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100606}
607
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800608// Set the trace tags that userland tracing uses, and poke the running
609// processes to pick up the new value.
610static bool setTagsProperty(uint64_t tags)
611{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700612 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
613 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800614 fprintf(stderr, "error setting trace tags system property\n");
615 return false;
616 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700617 return true;
618}
619
sergeyv4144eff2016-04-28 11:40:04 -0700620static void clearAppProperties()
621{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700622 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700623 fprintf(stderr, "failed to clear system property: %s",
624 k_traceAppsNumberProperty);
625 }
626}
627
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700628// Set the system property that indicates which apps should perform
629// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700630static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700631{
sergeyv4144eff2016-04-28 11:40:04 -0700632 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700633 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700634 while (start != NULL) {
sergeyv4144eff2016-04-28 11:40:04 -0700635 char* end = strchr(start, ',');
636 if (end != NULL) {
637 *end = '\0';
638 end++;
639 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700640 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
641 if (!android::base::SetProperty(key, start)) {
642 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700643 clearAppProperties();
644 return false;
645 }
646 start = end;
647 i++;
648 }
649
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700650 std::string value = android::base::StringPrintf("%d", i);
651 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
652 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700653 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700654 return false;
655 }
656 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800657}
658
659// Disable all /sys/ enable files.
660static bool disableKernelTraceEvents() {
661 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700662 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800663 const TracingCategory &c = k_categories[i];
664 for (int j = 0; j < MAX_SYS_FILES; j++) {
665 const char* path = c.sysfiles[j].path;
666 if (path != NULL && fileIsWritable(path)) {
667 ok &= setKernelOptionEnable(path, false);
668 }
669 }
670 }
671 return ok;
672}
673
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700674// Verify that the comma separated list of functions are being traced by the
675// kernel.
676static bool verifyKernelTraceFuncs(const char* funcs)
677{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100678 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800679 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100680 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700681 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100682 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700683 }
684
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100685 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700686
687 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100688 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700689 bool ok = true;
690 char* myFuncs = strdup(funcs);
691 char* func = strtok(myFuncs, ",");
692 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100693 if (!strchr(func, '*')) {
694 String8 fancyFunc = String8::format("\n%s\n", func);
695 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
696 if (!found || func[0] == '\0') {
697 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
698 "to trace.\n", func);
699 ok = false;
700 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700701 }
702 func = strtok(NULL, ",");
703 }
704 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700705 return ok;
706}
707
708// Set the comma separated list of functions that the kernel is to trace.
709static bool setKernelTraceFuncs(const char* funcs)
710{
711 bool ok = true;
712
713 if (funcs == NULL || funcs[0] == '\0') {
714 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700715 if (fileIsWritable(k_currentTracerPath)) {
716 ok &= writeStr(k_currentTracerPath, "nop");
717 }
718 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700719 ok &= truncateFile(k_ftraceFilterPath);
720 }
721 } else {
722 // Enable kernel function tracing.
723 ok &= writeStr(k_currentTracerPath, "function_graph");
724 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
725 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
726 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
727 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
728
729 // Set the requested filter functions.
730 ok &= truncateFile(k_ftraceFilterPath);
731 char* myFuncs = strdup(funcs);
732 char* func = strtok(myFuncs, ",");
733 while (func) {
734 ok &= appendStr(k_ftraceFilterPath, func);
735 func = strtok(NULL, ",");
736 }
737 free(myFuncs);
738
739 // Verify that the set functions are being traced.
740 if (ok) {
741 ok &= verifyKernelTraceFuncs(funcs);
742 }
743 }
744
745 return ok;
746}
747
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900748static bool setCategoryEnable(const char* name, bool enable)
749{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700750 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900751 const TracingCategory& c = k_categories[i];
752 if (strcmp(name, c.name) == 0) {
753 if (isCategorySupported(c)) {
754 g_categoryEnables[i] = enable;
755 return true;
756 } else {
757 if (isCategorySupportedForRoot(c)) {
758 fprintf(stderr, "error: category \"%s\" requires root "
759 "privileges.\n", name);
760 } else {
761 fprintf(stderr, "error: category \"%s\" is not supported "
762 "on this device.\n", name);
763 }
764 return false;
765 }
766 }
767 }
768 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
769 return false;
770}
771
772static bool setCategoriesEnableFromFile(const char* categories_file)
773{
774 if (!categories_file) {
775 return true;
776 }
777 Tokenizer* tokenizer = NULL;
778 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
779 return false;
780 }
781 bool ok = true;
782 while (!tokenizer->isEol()) {
783 String8 token = tokenizer->nextToken(" ");
784 if (token.isEmpty()) {
785 tokenizer->skipDelimiters(" ");
786 continue;
787 }
788 ok &= setCategoryEnable(token.string(), true);
789 }
790 delete tokenizer;
791 return ok;
792}
793
Hector Dearman11845782018-03-08 14:35:44 +0000794static bool setUpUserspaceTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800795{
796 bool ok = true;
797
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800798 // Set up the tags property.
799 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700800 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800801 if (g_categoryEnables[i]) {
802 const TracingCategory &c = k_categories[i];
803 tags |= c.tags;
804 }
805 }
806 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700807
808 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700809 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700810 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
811 coreServicesTagEnabled = g_categoryEnables[i];
812 }
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700813
814 // Set whether to poke PDX services in this session.
815 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
816 g_tracePdx = g_categoryEnables[i];
817 }
sergeyvdb404152016-05-02 19:26:07 -0700818 }
819
820 std::string packageList(g_debugAppCmdLine);
821 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700822 if (!packageList.empty()) {
823 packageList += ",";
824 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700825 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700826 }
Dan Austin09a79872016-05-31 13:27:03 -0700827 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700828 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100829 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800830
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700831 if (g_tracePdx) {
832 ok &= ServiceUtility::PokeServices();
833 }
834
Hector Dearman11845782018-03-08 14:35:44 +0000835 return ok;
836}
837
838static void cleanUpUserspaceTracing()
839{
840 setTagsProperty(0);
841 clearAppProperties();
842 pokeBinderServices();
843
844 if (g_tracePdx) {
845 ServiceUtility::PokeServices();
846 }
847}
848
849
850// Set all the kernel tracing settings to the desired state for this trace
851// capture.
852static bool setUpKernelTracing()
853{
854 bool ok = true;
855
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700856 ok &= setUserInitiatedTraceProperty(true);
857
Hector Dearman11845782018-03-08 14:35:44 +0000858 // Set up the tracing options.
859 ok &= setCategoriesEnableFromFile(g_categoriesFile);
860 ok &= setTraceOverwriteEnable(g_traceOverwrite);
861 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
862 // TODO: Re-enable after stabilization
863 //ok &= setCmdlineSize();
864 ok &= setClock();
865 ok &= setPrintTgidEnableIfPresent(true);
866 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
867
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800868 // Disable all the sysfs enables. This is done as a separate loop from
869 // the enables to allow the same enable to exist in multiple categories.
870 ok &= disableKernelTraceEvents();
871
872 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700873 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800874 if (g_categoryEnables[i]) {
875 const TracingCategory &c = k_categories[i];
876 for (int j = 0; j < MAX_SYS_FILES; j++) {
877 const char* path = c.sysfiles[j].path;
878 bool required = c.sysfiles[j].required == REQ;
879 if (path != NULL) {
880 if (fileIsWritable(path)) {
881 ok &= setKernelOptionEnable(path, true);
882 } else if (required) {
883 fprintf(stderr, "error writing file %s\n", path);
884 ok = false;
885 }
886 }
887 }
888 }
889 }
890
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800891 return ok;
892}
893
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700894// Reset all the kernel tracing settings to their default state.
Hector Dearman11845782018-03-08 14:35:44 +0000895static void cleanUpKernelTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800896{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800897 // Disable all tracing that we're able to.
898 disableKernelTraceEvents();
899
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800900 // Set the options back to their defaults.
901 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700902 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700903 setPrintTgidEnableIfPresent(false);
904 setKernelTraceFuncs(NULL);
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700905 setUserInitiatedTraceProperty(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700906}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800907
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700908// Enable tracing in the kernel.
909static bool startTrace()
910{
911 return setTracingEnabled(true);
912}
913
914// Disable tracing in the kernel.
915static void stopTrace()
916{
917 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800918}
919
Martijn Coenend9535872015-11-26 10:00:55 +0100920// Read data from the tracing pipe and forward to stdout
921static void streamTrace()
922{
923 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800924 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100925 if (traceFD == -1) {
926 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
927 strerror(errno), errno);
928 return;
929 }
930 while (!g_traceAborted) {
931 ssize_t bytes_read = read(traceFD, trace_data, 4096);
932 if (bytes_read > 0) {
933 write(STDOUT_FILENO, trace_data, bytes_read);
934 fflush(stdout);
935 } else {
936 if (!g_traceAborted) {
937 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
938 bytes_read, errno, strerror(errno));
939 }
940 break;
941 }
942 }
943}
944
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800945// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700946static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800947{
John Reck6c8ac922016-03-28 11:25:30 -0700948 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800949 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800950 if (traceFD == -1) {
951 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
952 strerror(errno), errno);
953 return;
954 }
955
956 if (g_compress) {
957 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800958 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700959
960 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800961 if (result != Z_OK) {
962 fprintf(stderr, "error initializing zlib: %d\n", result);
963 close(traceFD);
964 return;
965 }
966
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700967 constexpr size_t bufSize = 64*1024;
968 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
969 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
970 if (!in || !out) {
971 fprintf(stderr, "couldn't allocate buffers\n");
972 close(traceFD);
973 return;
974 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800975
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700976 int flush = Z_NO_FLUSH;
977
978 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800979 zs.avail_out = bufSize;
980
981 do {
982
983 if (zs.avail_in == 0) {
984 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700985 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800986 if (result < 0) {
987 fprintf(stderr, "error reading trace: %s (%d)\n",
988 strerror(errno), errno);
989 result = Z_STREAM_END;
990 break;
991 } else if (result == 0) {
992 flush = Z_FINISH;
993 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700994 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800995 zs.avail_in = result;
996 }
997 }
998
999 if (zs.avail_out == 0) {
1000 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -07001001 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001002 if ((size_t)result < bufSize) {
1003 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1004 strerror(errno), errno);
1005 result = Z_STREAM_END; // skip deflate error message
1006 zs.avail_out = bufSize; // skip the final write
1007 break;
1008 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001009 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001010 zs.avail_out = bufSize;
1011 }
1012
1013 } while ((result = deflate(&zs, flush)) == Z_OK);
1014
1015 if (result != Z_STREAM_END) {
1016 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
1017 }
1018
1019 if (zs.avail_out < bufSize) {
1020 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -07001021 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001022 if ((size_t)result < bytes) {
1023 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1024 strerror(errno), errno);
1025 }
1026 }
1027
1028 result = deflateEnd(&zs);
1029 if (result != Z_OK) {
1030 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1031 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001032 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001033 char buf[4096];
1034 ssize_t rc;
1035 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1036 if (!android::base::WriteFully(outFd, buf, rc)) {
1037 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1038 break;
1039 }
1040 }
1041 if (rc == -1) {
1042 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001043 }
1044 }
1045
1046 close(traceFD);
1047}
1048
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001049static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001050{
1051 if (!g_nohup) {
1052 g_traceAborted = true;
1053 }
1054}
1055
1056static void registerSigHandler()
1057{
1058 struct sigaction sa;
1059 sigemptyset(&sa.sa_mask);
1060 sa.sa_flags = 0;
1061 sa.sa_handler = handleSignal;
1062 sigaction(SIGHUP, &sa, NULL);
1063 sigaction(SIGINT, &sa, NULL);
1064 sigaction(SIGQUIT, &sa, NULL);
1065 sigaction(SIGTERM, &sa, NULL);
1066}
1067
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001068static void listSupportedCategories()
1069{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001070 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001071 const TracingCategory& c = k_categories[i];
1072 if (isCategorySupported(c)) {
1073 printf(" %10s - %s\n", c.name, c.longname);
1074 }
1075 }
1076}
1077
1078// Print the command usage help to stderr.
1079static void showHelp(const char *cmd)
1080{
1081 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1082 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001083 " -a appname enable app-level tracing for a comma "
Daniel Colascione519a0792018-02-09 20:05:39 -08001084 "separated list of cmdlines; * is a wildcard matching any process\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001085 " -b N use a trace buffer size of N KB\n"
1086 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001087 " -f filename use the categories written in a file as space-separated\n"
1088 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001089 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001090 " -n ignore signals\n"
1091 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001092 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001093 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001094 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001095 " --async_dump dump the current contents of circular trace buffer\n"
1096 " --async_stop stop tracing and dump the current contents of circular\n"
1097 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001098 " --stream stream trace to stdout as it enters the trace buffer\n"
1099 " Note: this can take significant CPU time, and is best\n"
1100 " used for measuring things that are not affected by\n"
1101 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001102 " --list_categories\n"
1103 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001104 " -o filename write the trace to the specified file instead\n"
1105 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001106 );
1107}
1108
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001109bool findTraceFiles()
1110{
1111 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1112 static const std::string tracefs_path = "/sys/kernel/tracing/";
1113 static const std::string trace_file = "trace_marker";
1114
1115 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1116 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1117
1118 if (!tracefs && !debugfs) {
1119 fprintf(stderr, "Error: Did not find trace folder\n");
1120 return false;
1121 }
1122
1123 if (tracefs) {
1124 g_traceFolder = tracefs_path;
1125 } else {
1126 g_traceFolder = debugfs_path;
1127 }
1128
1129 return true;
1130}
1131
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001132int main(int argc, char **argv)
1133{
1134 bool async = false;
1135 bool traceStart = true;
1136 bool traceStop = true;
1137 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001138 bool traceStream = false;
Hector Dearman11845782018-03-08 14:35:44 +00001139 bool onlyUserspace = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001140
1141 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1142 showHelp(argv[0]);
1143 exit(0);
1144 }
1145
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001146 if (!findTraceFiles()) {
1147 fprintf(stderr, "No trace folder found\n");
1148 exit(-1);
1149 }
1150
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001151 for (;;) {
1152 int ret;
1153 int option_index = 0;
1154 static struct option long_options[] = {
Hector Dearman11845782018-03-08 14:35:44 +00001155 {"async_start", no_argument, 0, 0 },
1156 {"async_stop", no_argument, 0, 0 },
1157 {"async_dump", no_argument, 0, 0 },
1158 {"only_userspace", no_argument, 0, 0 },
1159 {"list_categories", no_argument, 0, 0 },
1160 {"stream", no_argument, 0, 0 },
1161 { 0, 0, 0, 0 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001162 };
1163
John Reck40b26b42016-03-30 09:44:36 -07001164 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001165 long_options, &option_index);
1166
1167 if (ret < 0) {
1168 for (int i = optind; i < argc; i++) {
1169 if (!setCategoryEnable(argv[i], true)) {
1170 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1171 exit(1);
1172 }
1173 }
1174 break;
1175 }
1176
1177 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001178 case 'a':
1179 g_debugAppCmdLine = optarg;
1180 break;
1181
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001182 case 'b':
1183 g_traceBufferSizeKB = atoi(optarg);
1184 break;
1185
1186 case 'c':
1187 g_traceOverwrite = true;
1188 break;
1189
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001190 case 'f':
1191 g_categoriesFile = optarg;
1192 break;
1193
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001194 case 'k':
1195 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001196 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001197
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001198 case 'n':
1199 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001200 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001201
1202 case 's':
1203 g_initialSleepSecs = atoi(optarg);
1204 break;
1205
1206 case 't':
1207 g_traceDurationSeconds = atoi(optarg);
1208 break;
1209
1210 case 'z':
1211 g_compress = true;
1212 break;
1213
John Reck40b26b42016-03-30 09:44:36 -07001214 case 'o':
1215 g_outputFile = optarg;
1216 break;
1217
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001218 case 0:
1219 if (!strcmp(long_options[option_index].name, "async_start")) {
1220 async = true;
1221 traceStop = false;
1222 traceDump = false;
1223 g_traceOverwrite = true;
1224 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1225 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001226 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001227 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1228 async = true;
1229 traceStart = false;
1230 traceStop = false;
Hector Dearman11845782018-03-08 14:35:44 +00001231 } else if (!strcmp(long_options[option_index].name, "only_userspace")) {
1232 onlyUserspace = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001233 } else if (!strcmp(long_options[option_index].name, "stream")) {
1234 traceStream = true;
1235 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001236 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1237 listSupportedCategories();
1238 exit(0);
1239 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001240 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001241
1242 default:
1243 fprintf(stderr, "\n");
1244 showHelp(argv[0]);
1245 exit(-1);
1246 break;
1247 }
1248 }
1249
Hector Dearman11845782018-03-08 14:35:44 +00001250 if (onlyUserspace) {
1251 if (!async || !(traceStart || traceStop)) {
1252 fprintf(stderr, "--only_userspace can only be used with "
1253 "--async_start or --async_stop\n");
1254 exit(1);
1255 }
1256 }
1257
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001258 registerSigHandler();
1259
1260 if (g_initialSleepSecs > 0) {
1261 sleep(g_initialSleepSecs);
1262 }
1263
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001264 bool ok = true;
Hector Dearman11845782018-03-08 14:35:44 +00001265
Wei Wang5b73b742018-03-08 13:33:12 -08001266 if (traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001267 ok &= setUpUserspaceTracing();
1268 }
1269
1270 if (ok && traceStart && !onlyUserspace) {
1271 ok &= setUpKernelTracing();
Wei Wang5b73b742018-03-08 13:33:12 -08001272 ok &= startTrace();
1273 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001274
1275 if (ok && traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001276
1277 if (!traceStream && !onlyUserspace) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001278 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001279 fflush(stdout);
1280 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001281
1282 // We clear the trace after starting it because tracing gets enabled for
1283 // each CPU individually in the kernel. Having the beginning of the trace
1284 // contain entries from only one CPU can cause "begin" entries without a
1285 // matching "end" entry to show up if a task gets migrated from one CPU to
1286 // another.
Hector Dearman11845782018-03-08 14:35:44 +00001287 if (!onlyUserspace)
1288 ok = clearTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001289
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001290 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001291 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001292 // Sleep to allow the trace to be captured.
1293 struct timespec timeLeft;
1294 timeLeft.tv_sec = g_traceDurationSeconds;
1295 timeLeft.tv_nsec = 0;
1296 do {
1297 if (g_traceAborted) {
1298 break;
1299 }
1300 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1301 }
Martijn Coenend9535872015-11-26 10:00:55 +01001302
1303 if (traceStream) {
1304 streamTrace();
1305 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001306 }
1307
1308 // Stop the trace and restore the default settings.
Hector Dearman11845782018-03-08 14:35:44 +00001309 if (traceStop && !onlyUserspace)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001310 stopTrace();
1311
Hector Dearman11845782018-03-08 14:35:44 +00001312 if (ok && traceDump && !onlyUserspace) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001313 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001314 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001315 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001316 int outFd = STDOUT_FILENO;
1317 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001318 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001319 }
1320 if (outFd == -1) {
1321 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1322 } else {
1323 dprintf(outFd, "TRACE:\n");
1324 dumpTrace(outFd);
1325 if (g_outputFile) {
1326 close(outFd);
1327 }
1328 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001329 } else {
1330 printf("\ntrace aborted.\n");
1331 fflush(stdout);
1332 }
1333 clearTrace();
1334 } else if (!ok) {
1335 fprintf(stderr, "unable to start tracing\n");
1336 }
1337
1338 // Reset the trace buffer size to 1.
Hector Dearman11845782018-03-08 14:35:44 +00001339 if (traceStop) {
1340 cleanUpUserspaceTracing();
1341 if (!onlyUserspace)
1342 cleanUpKernelTracing();
1343 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001344
1345 return g_traceAborted ? 1 : 0;
1346}