blob: 90609379ff6267cfbc8377ffc92f4a9c7b54d064 [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";
sergeyv4144eff2016-04-28 11:40:04 -070061
62const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
63const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070064const char* k_coreServiceCategory = "core_services";
Corey Tabakaa6c0a722017-05-31 16:37:40 -070065const char* k_pdxServiceCategory = "pdx";
sergeyvdb404152016-05-02 19:26:07 -070066const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080067
68typedef enum { OPT, REQ } requiredness ;
69
70struct TracingCategory {
71 // The name identifying the category.
72 const char* name;
73
74 // A longer description of the category.
75 const char* longname;
76
77 // The userland tracing tags that the category enables.
78 uint64_t tags;
79
80 // The fname==NULL terminated list of /sys/ files that the category
81 // enables.
82 struct {
83 // Whether the file must be writable in order to enable the tracing
84 // category.
85 requiredness required;
86
87 // The path to the enable file.
88 const char* path;
89 } sysfiles[MAX_SYS_FILES];
90};
91
92/* Tracing categories */
93static const TracingCategory k_categories[] = {
John Reck732a29a2017-05-24 16:09:21 -070094 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, {
95 { OPT, "events/mdss/enable" },
Wei Wange2c10462018-02-13 10:47:23 -080096 { OPT, "events/sde/enable" },
John Reck732a29a2017-05-24 16:09:21 -070097 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070098 { "input", "Input", ATRACE_TAG_INPUT, { } },
99 { "view", "View System", ATRACE_TAG_VIEW, { } },
100 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
101 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
102 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -0500103 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700104 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
105 { "video", "Video", ATRACE_TAG_VIDEO, { } },
106 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
107 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -0700108 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -0700109 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -0700110 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -0700111 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700112 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 14:36:20 -0700113 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-07-01 01:46:25 +0900114 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Greg Hackmannbbd7d992014-12-01 14:43:34 -0800115 { "database", "Database", ATRACE_TAG_DATABASE, { } },
Felipe Leme0f97c1d2016-09-07 11:33:26 -0700116 { "network", "Network", ATRACE_TAG_NETWORK, { } },
Josh Gao468b4cb2016-11-29 10:55:21 -0800117 { "adb", "ADB", ATRACE_TAG_ADB, { } },
Martijn Coenen47791e92018-03-09 09:27:32 +0100118 { "vibrator", "Vibrator", ATRACE_TAG_VIBRATOR, { } },
119 { "aidl", "AIDL calls", ATRACE_TAG_AIDL, { } },
sergeyvdb404152016-05-02 19:26:07 -0700120 { k_coreServiceCategory, "Core services", 0, { } },
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700121 { k_pdxServiceCategory, "PDX services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700122 { "sched", "CPU Scheduling", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800123 { REQ, "events/sched/sched_switch/enable" },
124 { REQ, "events/sched/sched_wakeup/enable" },
Joel Fernandesee593e22017-06-04 13:05:59 -0700125 { OPT, "events/sched/sched_waking/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800126 { OPT, "events/sched/sched_blocked_reason/enable" },
127 { OPT, "events/sched/sched_cpu_hotplug/enable" },
Wei Wangca49dfc2018-05-03 15:45:20 -0700128 { OPT, "events/sched/sched_pi_setprio/enable" },
Joel Fernandes4dfca7c2017-06-15 16:53:52 -0700129 { OPT, "events/cgroup/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800130 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700131 { "irq", "IRQ Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800132 { REQ, "events/irq/enable" },
133 { OPT, "events/ipi/enable" },
Dan Willemsenf440d392014-04-11 15:44:09 -0700134 } },
Joel Fernandes0ad0f302017-08-31 08:35:05 -0700135 { "irqoff", "IRQ-disabled code section tracing", 0, {
136 { REQ, "events/preemptirq/irq_enable/enable" },
137 { REQ, "events/preemptirq/irq_disable/enable" },
138 } },
139 { "preemptoff", "Preempt-disabled code section tracing", 0, {
140 { REQ, "events/preemptirq/preempt_enable/enable" },
141 { REQ, "events/preemptirq/preempt_disable/enable" },
142 } },
Michael Wright43fb6782016-08-18 19:56:43 +0100143 { "i2c", "I2C Events", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800144 { REQ, "events/i2c/enable" },
145 { REQ, "events/i2c/i2c_read/enable" },
146 { REQ, "events/i2c/i2c_write/enable" },
147 { REQ, "events/i2c/i2c_result/enable" },
148 { REQ, "events/i2c/i2c_reply/enable" },
149 { OPT, "events/i2c/smbus_read/enable" },
150 { OPT, "events/i2c/smbus_write/enable" },
151 { OPT, "events/i2c/smbus_result/enable" },
152 { OPT, "events/i2c/smbus_reply/enable" },
Michael Wright43fb6782016-08-18 19:56:43 +0100153 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700154 { "freq", "CPU Frequency", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800155 { REQ, "events/power/cpu_frequency/enable" },
156 { OPT, "events/power/clock_set_rate/enable" },
Kevin DuBoisafc2f972017-11-03 15:44:08 -0700157 { OPT, "events/power/clock_disable/enable" },
158 { OPT, "events/power/clock_enable/enable" },
Wei Wang391efc22018-02-22 11:40:07 -0800159 { OPT, "events/clk/clk_set_rate/enable" },
160 { OPT, "events/clk/clk_disable/enable" },
161 { OPT, "events/clk/clk_enable/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800162 { OPT, "events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800163 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700164 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800165 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800166 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700167 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800168 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800169 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700170 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800171 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
172 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
173 { OPT, "events/f2fs/f2fs_write_begin/enable" },
174 { OPT, "events/f2fs/f2fs_write_end/enable" },
175 { OPT, "events/ext4/ext4_da_write_begin/enable" },
176 { OPT, "events/ext4/ext4_da_write_end/enable" },
177 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
178 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
179 { REQ, "events/block/block_rq_issue/enable" },
180 { REQ, "events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800181 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700182 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800183 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700184 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700185 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800186 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800187 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700188 { "sync", "Synchronization", 0, {
Jesse Hallae001a32018-05-15 12:02:15 -0700189 // before linux kernel 4.9
190 { OPT, "events/sync/enable" },
191 // starting in linux kernel 4.9
192 { OPT, "events/fence/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800193 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700194 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800195 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800196 } },
Colin Cross580407f2014-08-18 15:22:13 -0700197 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800198 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
199 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
200 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
201 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Marc Hittingerf1f62e32017-05-17 15:57:43 -0700202 { REQ, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700203 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800204 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800205 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800206 } },
Scott Bauerae473362015-06-08 16:32:36 -0700207 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800208 { REQ, "events/binder/binder_transaction/enable" },
209 { REQ, "events/binder/binder_transaction_received/enable" },
Martijn Coenen7f3d7a22017-05-26 09:50:55 -0700210 { OPT, "events/binder/binder_set_priority/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700211 } },
212 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800213 { OPT, "events/binder/binder_lock/enable" },
214 { OPT, "events/binder/binder_locked/enable" },
215 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 16:32:36 -0700216 } },
Martijn Coenen70481612015-10-23 13:57:05 +0200217 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800218 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 13:57:05 +0200219 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800220};
221
222/* Command line options */
223static int g_traceDurationSeconds = 5;
224static bool g_traceOverwrite = false;
225static int g_traceBufferSizeKB = 2048;
226static bool g_compress = false;
227static bool g_nohup = false;
228static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900229static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700230static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700231static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 09:44:36 -0700232static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800233
234/* Global state */
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700235static bool g_tracePdx = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800236static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700237static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800238static std::string g_traceFolder;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800239
240/* Sys file paths */
241static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800242 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800243
244static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800245 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800246
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700247#if 0
248// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700249static const char* k_traceCmdlineSizePath =
250 "saved_cmdlines_size";
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700251#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700252
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800253static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800254 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800255
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700256static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800257 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700258
259static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800260 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700261
262static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800263 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700264
265static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800266 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700267
268static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800269 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700270
271static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800272 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700273
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700274static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800275 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700276
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800277static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800278 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800279
280static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800281 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800282
Martijn Coenend9535872015-11-26 10:00:55 +0100283static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800284 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100285
John Reck469a1942015-03-26 15:31:35 -0700286static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800287 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700288
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800289// Check whether a file exists.
290static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800291 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800292}
293
294// Check whether a file is writable.
295static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800296 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800297}
298
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700299// Truncate a file.
300static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800301{
Jamie Gennis43122e72013-03-21 14:06:31 -0700302 // This uses creat rather than truncate because some of the debug kernel
303 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
304 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800305 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700306 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800307 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700308 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700309 return false;
310 }
311
Jamie Gennis43122e72013-03-21 14:06:31 -0700312 close(traceFD);
313
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700314 return true;
315}
316
317static bool _writeStr(const char* filename, const char* str, int flags)
318{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800319 std::string fullFilename = g_traceFolder + filename;
320 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800321 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800322 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800323 strerror(errno), errno);
324 return false;
325 }
326
327 bool ok = true;
328 ssize_t len = strlen(str);
329 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800330 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800331 strerror(errno), errno);
332 ok = false;
333 }
334
335 close(fd);
336
337 return ok;
338}
339
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700340// Write a string to a file, returning true if the write was successful.
341static bool writeStr(const char* filename, const char* str)
342{
343 return _writeStr(filename, str, O_WRONLY);
344}
345
346// Append a string to a file, returning true if the write was successful.
347static bool appendStr(const char* filename, const char* str)
348{
349 return _writeStr(filename, str, O_APPEND|O_WRONLY);
350}
351
John Reck469a1942015-03-26 15:31:35 -0700352static void writeClockSyncMarker()
353{
354 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200355 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800356 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200357 if (fd == -1) {
358 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
359 strerror(errno), errno);
360 return;
361 }
John Reck469a1942015-03-26 15:31:35 -0700362 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200363
364 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
365 if (write(fd, buffer, len) != len) {
366 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
367 }
368
369 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
370 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
371 if (write(fd, buffer, len) != len) {
372 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
373 }
374
375 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700376}
377
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800378// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
379// file.
380static bool setKernelOptionEnable(const char* filename, bool enable)
381{
382 return writeStr(filename, enable ? "1" : "0");
383}
384
385// Check whether the category is supported on the device with the current
386// rootness. A category is supported only if all its required /sys/ files are
387// writable and if enabling the category will enable one or more tracing tags
388// or /sys/ files.
389static bool isCategorySupported(const TracingCategory& category)
390{
sergeyvdb404152016-05-02 19:26:07 -0700391 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700392 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700393 }
394
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700395 if (strcmp(category.name, k_pdxServiceCategory) == 0) {
396 return true;
397 }
398
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800399 bool ok = category.tags != 0;
400 for (int i = 0; i < MAX_SYS_FILES; i++) {
401 const char* path = category.sysfiles[i].path;
402 bool req = category.sysfiles[i].required == REQ;
403 if (path != NULL) {
404 if (req) {
405 if (!fileIsWritable(path)) {
406 return false;
407 } else {
408 ok = true;
409 }
410 } else {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800411 ok = true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800412 }
413 }
414 }
415 return ok;
416}
417
418// Check whether the category would be supported on the device if the user
419// were root. This function assumes that root is able to write to any file
420// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700421// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800422static bool isCategorySupportedForRoot(const TracingCategory& category)
423{
424 bool ok = category.tags != 0;
425 for (int i = 0; i < MAX_SYS_FILES; i++) {
426 const char* path = category.sysfiles[i].path;
427 bool req = category.sysfiles[i].required == REQ;
428 if (path != NULL) {
429 if (req) {
430 if (!fileExists(path)) {
431 return false;
432 } else {
433 ok = true;
434 }
435 } else {
436 ok |= fileExists(path);
437 }
438 }
439 }
440 return ok;
441}
442
443// Enable or disable overwriting of the kernel trace buffers. Disabling this
444// will cause tracing to stop once the trace buffers have filled up.
445static bool setTraceOverwriteEnable(bool enable)
446{
447 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
448}
449
450// Enable or disable kernel tracing.
451static bool setTracingEnabled(bool enable)
452{
453 return setKernelOptionEnable(k_tracingOnPath, enable);
454}
455
456// Clear the contents of the kernel trace.
457static bool clearTrace()
458{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700459 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800460}
461
462// Set the size of the kernel's trace buffer in kilobytes.
463static bool setTraceBufferSizeKB(int size)
464{
465 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800466 if (size < 1) {
467 size = 1;
468 }
469 snprintf(str, 32, "%d", size);
470 return writeStr(k_traceBufferSizePath, str);
471}
472
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700473#if 0
474// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700475// Set the default size of cmdline hashtable
476static bool setCmdlineSize()
477{
Joel Fernandesce964f22017-06-06 12:20:29 -0700478 if (fileExists(k_traceCmdlineSizePath)) {
479 return writeStr(k_traceCmdlineSizePath, "8192");
480 }
481 return true;
Joel Fernandesed80bd02017-06-02 10:19:28 -0700482}
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700483#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700484
Carmen Jacksonea826792017-05-05 11:42:32 -0700485// Set the clock to the best available option while tracing. Use 'boot' if it's
486// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700487// Any write to the trace_clock sysfs file will reset the buffer, so only
488// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700489static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800490{
Carmen Jacksonea826792017-05-05 11:42:32 -0700491 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
492 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
493 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700494
Carmen Jacksonea826792017-05-05 11:42:32 -0700495 std::string newClock;
496 if (clockStr.find("boot") != std::string::npos) {
497 newClock = "boot";
498 } else if (clockStr.find("mono") != std::string::npos) {
499 newClock = "mono";
500 } else {
501 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700502 }
503
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700504 size_t begin = clockStr.find('[') + 1;
505 size_t end = clockStr.find(']');
Carmen Jacksonea826792017-05-05 11:42:32 -0700506 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
507 return true;
508 }
509 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800510}
511
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700512static bool setPrintTgidEnableIfPresent(bool enable)
513{
514 if (fileExists(k_printTgidPath)) {
515 return setKernelOptionEnable(k_printTgidPath, enable);
516 }
517 return true;
518}
519
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800520// Poke all the binder-enabled processes in the system to get them to re-read
521// their system properties.
522static bool pokeBinderServices()
523{
524 sp<IServiceManager> sm = defaultServiceManager();
525 Vector<String16> services = sm->listServices();
526 for (size_t i = 0; i < services.size(); i++) {
527 sp<IBinder> obj = sm->checkService(services[i]);
528 if (obj != NULL) {
529 Parcel data;
530 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
531 NULL, 0) != OK) {
532 if (false) {
533 // XXX: For some reason this fails on tablets trying to
534 // poke the "phone" service. It's not clear whether some
535 // are expected to fail.
536 String8 svc(services[i]);
537 fprintf(stderr, "error poking binder service %s\n",
538 svc.string());
539 return false;
540 }
541 }
542 }
543 }
544 return true;
545}
546
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100547// Poke all the HAL processes in the system to get them to re-read
548// their system properties.
549static void pokeHalServices()
550{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100551 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100552 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100553 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100554 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100555
556 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800557
558 if (sm == nullptr) {
559 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
560 return;
561 }
562
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800563 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100564 for (size_t i = 0; i < interfaces.size(); i++) {
565 string fqInstanceName = interfaces[i];
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700566 string::size_type n = fqInstanceName.find('/');
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100567 if (n == std::string::npos || interfaces[i].size() == n+1)
568 continue;
569 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
570 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100571 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
572 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100573 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100574 continue;
575 }
Carmen Jackson73206122017-04-18 15:37:57 -0700576
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100577 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700578 if (interface == nullptr) {
579 // ignore
580 continue;
581 }
582
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100583 auto notifyRet = interface->notifySyspropsChanged();
584 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100585 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800586 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100587 }
588 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800589 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100590 // TODO(b/34242478) fix this when we determine the correct ACL
591 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800592 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100593}
594
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800595// Set the trace tags that userland tracing uses, and poke the running
596// processes to pick up the new value.
597static bool setTagsProperty(uint64_t tags)
598{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700599 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
600 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800601 fprintf(stderr, "error setting trace tags system property\n");
602 return false;
603 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700604 return true;
605}
606
sergeyv4144eff2016-04-28 11:40:04 -0700607static void clearAppProperties()
608{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700609 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700610 fprintf(stderr, "failed to clear system property: %s",
611 k_traceAppsNumberProperty);
612 }
613}
614
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700615// Set the system property that indicates which apps should perform
616// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700617static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700618{
sergeyv4144eff2016-04-28 11:40:04 -0700619 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700620 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700621 while (start != NULL) {
sergeyv4144eff2016-04-28 11:40:04 -0700622 char* end = strchr(start, ',');
623 if (end != NULL) {
624 *end = '\0';
625 end++;
626 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700627 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
628 if (!android::base::SetProperty(key, start)) {
629 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700630 clearAppProperties();
631 return false;
632 }
633 start = end;
634 i++;
635 }
636
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700637 std::string value = android::base::StringPrintf("%d", i);
638 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
639 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700640 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700641 return false;
642 }
643 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800644}
645
646// Disable all /sys/ enable files.
647static bool disableKernelTraceEvents() {
648 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700649 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800650 const TracingCategory &c = k_categories[i];
651 for (int j = 0; j < MAX_SYS_FILES; j++) {
652 const char* path = c.sysfiles[j].path;
653 if (path != NULL && fileIsWritable(path)) {
654 ok &= setKernelOptionEnable(path, false);
655 }
656 }
657 }
658 return ok;
659}
660
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700661// Verify that the comma separated list of functions are being traced by the
662// kernel.
663static bool verifyKernelTraceFuncs(const char* funcs)
664{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100665 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800666 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100667 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700668 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100669 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700670 }
671
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100672 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700673
674 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100675 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700676 bool ok = true;
677 char* myFuncs = strdup(funcs);
678 char* func = strtok(myFuncs, ",");
679 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100680 if (!strchr(func, '*')) {
681 String8 fancyFunc = String8::format("\n%s\n", func);
682 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
683 if (!found || func[0] == '\0') {
684 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
685 "to trace.\n", func);
686 ok = false;
687 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700688 }
689 func = strtok(NULL, ",");
690 }
691 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700692 return ok;
693}
694
695// Set the comma separated list of functions that the kernel is to trace.
696static bool setKernelTraceFuncs(const char* funcs)
697{
698 bool ok = true;
699
700 if (funcs == NULL || funcs[0] == '\0') {
701 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700702 if (fileIsWritable(k_currentTracerPath)) {
703 ok &= writeStr(k_currentTracerPath, "nop");
704 }
705 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700706 ok &= truncateFile(k_ftraceFilterPath);
707 }
708 } else {
709 // Enable kernel function tracing.
710 ok &= writeStr(k_currentTracerPath, "function_graph");
711 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
712 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
713 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
714 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
715
716 // Set the requested filter functions.
717 ok &= truncateFile(k_ftraceFilterPath);
718 char* myFuncs = strdup(funcs);
719 char* func = strtok(myFuncs, ",");
720 while (func) {
721 ok &= appendStr(k_ftraceFilterPath, func);
722 func = strtok(NULL, ",");
723 }
724 free(myFuncs);
725
726 // Verify that the set functions are being traced.
727 if (ok) {
728 ok &= verifyKernelTraceFuncs(funcs);
729 }
730 }
731
732 return ok;
733}
734
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900735static bool setCategoryEnable(const char* name, bool enable)
736{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700737 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900738 const TracingCategory& c = k_categories[i];
739 if (strcmp(name, c.name) == 0) {
740 if (isCategorySupported(c)) {
741 g_categoryEnables[i] = enable;
742 return true;
743 } else {
744 if (isCategorySupportedForRoot(c)) {
745 fprintf(stderr, "error: category \"%s\" requires root "
746 "privileges.\n", name);
747 } else {
748 fprintf(stderr, "error: category \"%s\" is not supported "
749 "on this device.\n", name);
750 }
751 return false;
752 }
753 }
754 }
755 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
756 return false;
757}
758
759static bool setCategoriesEnableFromFile(const char* categories_file)
760{
761 if (!categories_file) {
762 return true;
763 }
764 Tokenizer* tokenizer = NULL;
765 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
766 return false;
767 }
768 bool ok = true;
769 while (!tokenizer->isEol()) {
770 String8 token = tokenizer->nextToken(" ");
771 if (token.isEmpty()) {
772 tokenizer->skipDelimiters(" ");
773 continue;
774 }
775 ok &= setCategoryEnable(token.string(), true);
776 }
777 delete tokenizer;
778 return ok;
779}
780
Hector Dearman550b18c2018-03-08 14:35:44 +0000781static bool setUpUserspaceTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800782{
783 bool ok = true;
784
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800785 // Set up the tags property.
786 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700787 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800788 if (g_categoryEnables[i]) {
789 const TracingCategory &c = k_categories[i];
790 tags |= c.tags;
791 }
792 }
793 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700794
795 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700796 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700797 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
798 coreServicesTagEnabled = g_categoryEnables[i];
799 }
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700800
801 // Set whether to poke PDX services in this session.
802 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
803 g_tracePdx = g_categoryEnables[i];
804 }
sergeyvdb404152016-05-02 19:26:07 -0700805 }
806
807 std::string packageList(g_debugAppCmdLine);
808 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700809 if (!packageList.empty()) {
810 packageList += ",";
811 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700812 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700813 }
Dan Austin09a79872016-05-31 13:27:03 -0700814 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700815 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100816 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800817
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700818 if (g_tracePdx) {
819 ok &= ServiceUtility::PokeServices();
820 }
821
Hector Dearman550b18c2018-03-08 14:35:44 +0000822 return ok;
823}
824
825static void cleanUpUserspaceTracing()
826{
827 setTagsProperty(0);
828 clearAppProperties();
829 pokeBinderServices();
830
831 if (g_tracePdx) {
832 ServiceUtility::PokeServices();
833 }
834}
835
836
837// Set all the kernel tracing settings to the desired state for this trace
838// capture.
839static bool setUpKernelTracing()
840{
841 bool ok = true;
842
843 // Set up the tracing options.
844 ok &= setCategoriesEnableFromFile(g_categoriesFile);
845 ok &= setTraceOverwriteEnable(g_traceOverwrite);
846 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
847 // TODO: Re-enable after stabilization
848 //ok &= setCmdlineSize();
849 ok &= setClock();
850 ok &= setPrintTgidEnableIfPresent(true);
851 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
852
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800853 // Disable all the sysfs enables. This is done as a separate loop from
854 // the enables to allow the same enable to exist in multiple categories.
855 ok &= disableKernelTraceEvents();
856
857 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700858 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800859 if (g_categoryEnables[i]) {
860 const TracingCategory &c = k_categories[i];
861 for (int j = 0; j < MAX_SYS_FILES; j++) {
862 const char* path = c.sysfiles[j].path;
863 bool required = c.sysfiles[j].required == REQ;
864 if (path != NULL) {
865 if (fileIsWritable(path)) {
866 ok &= setKernelOptionEnable(path, true);
867 } else if (required) {
868 fprintf(stderr, "error writing file %s\n", path);
869 ok = false;
870 }
871 }
872 }
873 }
874 }
875
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800876 return ok;
877}
878
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700879// Reset all the kernel tracing settings to their default state.
Hector Dearman550b18c2018-03-08 14:35:44 +0000880static void cleanUpKernelTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800881{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800882 // Disable all tracing that we're able to.
883 disableKernelTraceEvents();
884
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800885 // Set the options back to their defaults.
886 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700887 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700888 setPrintTgidEnableIfPresent(false);
889 setKernelTraceFuncs(NULL);
890}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800891
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700892// Enable tracing in the kernel.
893static bool startTrace()
894{
895 return setTracingEnabled(true);
896}
897
898// Disable tracing in the kernel.
899static void stopTrace()
900{
901 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800902}
903
Martijn Coenend9535872015-11-26 10:00:55 +0100904// Read data from the tracing pipe and forward to stdout
905static void streamTrace()
906{
907 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800908 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100909 if (traceFD == -1) {
910 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
911 strerror(errno), errno);
912 return;
913 }
914 while (!g_traceAborted) {
915 ssize_t bytes_read = read(traceFD, trace_data, 4096);
916 if (bytes_read > 0) {
917 write(STDOUT_FILENO, trace_data, bytes_read);
918 fflush(stdout);
919 } else {
920 if (!g_traceAborted) {
921 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
922 bytes_read, errno, strerror(errno));
923 }
924 break;
925 }
926 }
927}
928
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800929// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700930static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800931{
John Reck6c8ac922016-03-28 11:25:30 -0700932 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800933 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800934 if (traceFD == -1) {
935 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
936 strerror(errno), errno);
937 return;
938 }
939
940 if (g_compress) {
941 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800942 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700943
944 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800945 if (result != Z_OK) {
946 fprintf(stderr, "error initializing zlib: %d\n", result);
947 close(traceFD);
948 return;
949 }
950
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700951 constexpr size_t bufSize = 64*1024;
952 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
953 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
954 if (!in || !out) {
955 fprintf(stderr, "couldn't allocate buffers\n");
956 close(traceFD);
957 return;
958 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800959
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700960 int flush = Z_NO_FLUSH;
961
962 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800963 zs.avail_out = bufSize;
964
965 do {
966
967 if (zs.avail_in == 0) {
968 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700969 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800970 if (result < 0) {
971 fprintf(stderr, "error reading trace: %s (%d)\n",
972 strerror(errno), errno);
973 result = Z_STREAM_END;
974 break;
975 } else if (result == 0) {
976 flush = Z_FINISH;
977 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700978 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800979 zs.avail_in = result;
980 }
981 }
982
983 if (zs.avail_out == 0) {
984 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -0700985 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800986 if ((size_t)result < bufSize) {
987 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
988 strerror(errno), errno);
989 result = Z_STREAM_END; // skip deflate error message
990 zs.avail_out = bufSize; // skip the final write
991 break;
992 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700993 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800994 zs.avail_out = bufSize;
995 }
996
997 } while ((result = deflate(&zs, flush)) == Z_OK);
998
999 if (result != Z_STREAM_END) {
1000 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
1001 }
1002
1003 if (zs.avail_out < bufSize) {
1004 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -07001005 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001006 if ((size_t)result < bytes) {
1007 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1008 strerror(errno), errno);
1009 }
1010 }
1011
1012 result = deflateEnd(&zs);
1013 if (result != Z_OK) {
1014 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1015 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001016 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001017 char buf[4096];
1018 ssize_t rc;
1019 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1020 if (!android::base::WriteFully(outFd, buf, rc)) {
1021 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1022 break;
1023 }
1024 }
1025 if (rc == -1) {
1026 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001027 }
1028 }
1029
1030 close(traceFD);
1031}
1032
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001033static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001034{
1035 if (!g_nohup) {
1036 g_traceAborted = true;
1037 }
1038}
1039
1040static void registerSigHandler()
1041{
1042 struct sigaction sa;
1043 sigemptyset(&sa.sa_mask);
1044 sa.sa_flags = 0;
1045 sa.sa_handler = handleSignal;
1046 sigaction(SIGHUP, &sa, NULL);
1047 sigaction(SIGINT, &sa, NULL);
1048 sigaction(SIGQUIT, &sa, NULL);
1049 sigaction(SIGTERM, &sa, NULL);
1050}
1051
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001052static void listSupportedCategories()
1053{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001054 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001055 const TracingCategory& c = k_categories[i];
1056 if (isCategorySupported(c)) {
1057 printf(" %10s - %s\n", c.name, c.longname);
1058 }
1059 }
1060}
1061
1062// Print the command usage help to stderr.
1063static void showHelp(const char *cmd)
1064{
1065 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1066 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001067 " -a appname enable app-level tracing for a comma "
Daniel Colascione519a0792018-02-09 20:05:39 -08001068 "separated list of cmdlines; * is a wildcard matching any process\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001069 " -b N use a trace buffer size of N KB\n"
1070 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001071 " -f filename use the categories written in a file as space-separated\n"
1072 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001073 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001074 " -n ignore signals\n"
1075 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001076 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001077 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001078 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001079 " --async_dump dump the current contents of circular trace buffer\n"
1080 " --async_stop stop tracing and dump the current contents of circular\n"
1081 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001082 " --stream stream trace to stdout as it enters the trace buffer\n"
1083 " Note: this can take significant CPU time, and is best\n"
1084 " used for measuring things that are not affected by\n"
1085 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001086 " --list_categories\n"
1087 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001088 " -o filename write the trace to the specified file instead\n"
1089 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001090 );
1091}
1092
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001093bool findTraceFiles()
1094{
1095 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1096 static const std::string tracefs_path = "/sys/kernel/tracing/";
1097 static const std::string trace_file = "trace_marker";
1098
1099 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1100 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1101
1102 if (!tracefs && !debugfs) {
1103 fprintf(stderr, "Error: Did not find trace folder\n");
1104 return false;
1105 }
1106
1107 if (tracefs) {
1108 g_traceFolder = tracefs_path;
1109 } else {
1110 g_traceFolder = debugfs_path;
1111 }
1112
1113 return true;
1114}
1115
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001116int main(int argc, char **argv)
1117{
1118 bool async = false;
1119 bool traceStart = true;
1120 bool traceStop = true;
1121 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001122 bool traceStream = false;
Hector Dearman550b18c2018-03-08 14:35:44 +00001123 bool onlyUserspace = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001124
1125 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1126 showHelp(argv[0]);
1127 exit(0);
1128 }
1129
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001130 if (!findTraceFiles()) {
1131 fprintf(stderr, "No trace folder found\n");
1132 exit(-1);
1133 }
1134
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001135 for (;;) {
1136 int ret;
1137 int option_index = 0;
1138 static struct option long_options[] = {
Hector Dearman550b18c2018-03-08 14:35:44 +00001139 {"async_start", no_argument, 0, 0 },
1140 {"async_stop", no_argument, 0, 0 },
1141 {"async_dump", no_argument, 0, 0 },
1142 {"only_userspace", no_argument, 0, 0 },
1143 {"list_categories", no_argument, 0, 0 },
1144 {"stream", no_argument, 0, 0 },
1145 { 0, 0, 0, 0 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001146 };
1147
John Reck40b26b42016-03-30 09:44:36 -07001148 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001149 long_options, &option_index);
1150
1151 if (ret < 0) {
1152 for (int i = optind; i < argc; i++) {
1153 if (!setCategoryEnable(argv[i], true)) {
1154 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1155 exit(1);
1156 }
1157 }
1158 break;
1159 }
1160
1161 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001162 case 'a':
1163 g_debugAppCmdLine = optarg;
1164 break;
1165
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001166 case 'b':
1167 g_traceBufferSizeKB = atoi(optarg);
1168 break;
1169
1170 case 'c':
1171 g_traceOverwrite = true;
1172 break;
1173
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001174 case 'f':
1175 g_categoriesFile = optarg;
1176 break;
1177
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001178 case 'k':
1179 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001180 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001181
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001182 case 'n':
1183 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001184 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001185
1186 case 's':
1187 g_initialSleepSecs = atoi(optarg);
1188 break;
1189
1190 case 't':
1191 g_traceDurationSeconds = atoi(optarg);
1192 break;
1193
1194 case 'z':
1195 g_compress = true;
1196 break;
1197
John Reck40b26b42016-03-30 09:44:36 -07001198 case 'o':
1199 g_outputFile = optarg;
1200 break;
1201
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001202 case 0:
1203 if (!strcmp(long_options[option_index].name, "async_start")) {
1204 async = true;
1205 traceStop = false;
1206 traceDump = false;
1207 g_traceOverwrite = true;
1208 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1209 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001210 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001211 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1212 async = true;
1213 traceStart = false;
1214 traceStop = false;
Hector Dearman550b18c2018-03-08 14:35:44 +00001215 } else if (!strcmp(long_options[option_index].name, "only_userspace")) {
1216 onlyUserspace = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001217 } else if (!strcmp(long_options[option_index].name, "stream")) {
1218 traceStream = true;
1219 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001220 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1221 listSupportedCategories();
1222 exit(0);
1223 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001224 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001225
1226 default:
1227 fprintf(stderr, "\n");
1228 showHelp(argv[0]);
1229 exit(-1);
1230 break;
1231 }
1232 }
1233
Hector Dearman550b18c2018-03-08 14:35:44 +00001234 if (onlyUserspace) {
1235 if (!async || !(traceStart || traceStop)) {
1236 fprintf(stderr, "--only_userspace can only be used with "
1237 "--async_start or --async_stop\n");
1238 exit(1);
1239 }
1240 }
1241
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001242 registerSigHandler();
1243
1244 if (g_initialSleepSecs > 0) {
1245 sleep(g_initialSleepSecs);
1246 }
1247
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001248 bool ok = true;
Hector Dearman550b18c2018-03-08 14:35:44 +00001249
Wei Wang190cb7d2018-03-08 13:33:12 -08001250 if (traceStart) {
Hector Dearman550b18c2018-03-08 14:35:44 +00001251 ok &= setUpUserspaceTracing();
1252 }
1253
1254 if (ok && traceStart && !onlyUserspace) {
1255 ok &= setUpKernelTracing();
Wei Wang190cb7d2018-03-08 13:33:12 -08001256 ok &= startTrace();
1257 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001258
1259 if (ok && traceStart) {
Hector Dearman550b18c2018-03-08 14:35:44 +00001260
1261 if (!traceStream && !onlyUserspace) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001262 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001263 fflush(stdout);
1264 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001265
1266 // We clear the trace after starting it because tracing gets enabled for
1267 // each CPU individually in the kernel. Having the beginning of the trace
1268 // contain entries from only one CPU can cause "begin" entries without a
1269 // matching "end" entry to show up if a task gets migrated from one CPU to
1270 // another.
Hector Dearman550b18c2018-03-08 14:35:44 +00001271 if (!onlyUserspace)
1272 ok = clearTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001273
Hector Dearman550b18c2018-03-08 14:35:44 +00001274 if (!onlyUserspace)
1275 writeClockSyncMarker();
1276
Martijn Coenend9535872015-11-26 10:00:55 +01001277 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001278 // Sleep to allow the trace to be captured.
1279 struct timespec timeLeft;
1280 timeLeft.tv_sec = g_traceDurationSeconds;
1281 timeLeft.tv_nsec = 0;
1282 do {
1283 if (g_traceAborted) {
1284 break;
1285 }
1286 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1287 }
Martijn Coenend9535872015-11-26 10:00:55 +01001288
1289 if (traceStream) {
1290 streamTrace();
1291 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001292 }
1293
1294 // Stop the trace and restore the default settings.
Hector Dearman550b18c2018-03-08 14:35:44 +00001295 if (traceStop && !onlyUserspace)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001296 stopTrace();
1297
Hector Dearman550b18c2018-03-08 14:35:44 +00001298 if (ok && traceDump && !onlyUserspace) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001299 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001300 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001301 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001302 int outFd = STDOUT_FILENO;
1303 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001304 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001305 }
1306 if (outFd == -1) {
1307 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1308 } else {
1309 dprintf(outFd, "TRACE:\n");
1310 dumpTrace(outFd);
1311 if (g_outputFile) {
1312 close(outFd);
1313 }
1314 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001315 } else {
1316 printf("\ntrace aborted.\n");
1317 fflush(stdout);
1318 }
1319 clearTrace();
1320 } else if (!ok) {
1321 fprintf(stderr, "unable to start tracing\n");
1322 }
1323
1324 // Reset the trace buffer size to 1.
Hector Dearman550b18c2018-03-08 14:35:44 +00001325 if (traceStop) {
1326 cleanUpUserspaceTracing();
1327 if (!onlyUserspace)
1328 cleanUpKernelTracing();
1329 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001330
1331 return g_traceAborted ? 1 : 0;
1332}