blob: 668a701eb5a7192af4063fb1dd0fd7ef8a9a99ce [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" },
Carmen Jacksonac37b5d2018-07-02 13:14:56 -0700204 { OPT, "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
John Recke757b1c2018-06-28 12:24:33 -0700265static const char* k_recordTgidPath =
266 "options/record-tgid";
267
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700268static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800269 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700270
271static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800272 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700273
274static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800275 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700276
277static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800278 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700279
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700280static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800281 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700282
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800283static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800284 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800285
286static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800287 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800288
Martijn Coenend9535872015-11-26 10:00:55 +0100289static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800290 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100291
John Reck469a1942015-03-26 15:31:35 -0700292static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800293 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700294
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800295// Check whether a file exists.
296static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800297 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800298}
299
300// Check whether a file is writable.
301static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800302 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800303}
304
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700305// Truncate a file.
306static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800307{
Jamie Gennis43122e72013-03-21 14:06:31 -0700308 // This uses creat rather than truncate because some of the debug kernel
309 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
310 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800311 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700312 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800313 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700314 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700315 return false;
316 }
317
Jamie Gennis43122e72013-03-21 14:06:31 -0700318 close(traceFD);
319
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700320 return true;
321}
322
323static bool _writeStr(const char* filename, const char* str, int flags)
324{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800325 std::string fullFilename = g_traceFolder + filename;
326 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800327 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800328 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800329 strerror(errno), errno);
330 return false;
331 }
332
333 bool ok = true;
334 ssize_t len = strlen(str);
335 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800336 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800337 strerror(errno), errno);
338 ok = false;
339 }
340
341 close(fd);
342
343 return ok;
344}
345
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700346// Write a string to a file, returning true if the write was successful.
347static bool writeStr(const char* filename, const char* str)
348{
349 return _writeStr(filename, str, O_WRONLY);
350}
351
352// Append a string to a file, returning true if the write was successful.
353static bool appendStr(const char* filename, const char* str)
354{
355 return _writeStr(filename, str, O_APPEND|O_WRONLY);
356}
357
John Reck469a1942015-03-26 15:31:35 -0700358static void writeClockSyncMarker()
359{
360 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200361 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800362 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200363 if (fd == -1) {
364 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
365 strerror(errno), errno);
366 return;
367 }
John Reck469a1942015-03-26 15:31:35 -0700368 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200369
370 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
371 if (write(fd, buffer, len) != len) {
372 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
373 }
374
375 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
376 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
377 if (write(fd, buffer, len) != len) {
378 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
379 }
380
381 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700382}
383
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800384// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
385// file.
386static bool setKernelOptionEnable(const char* filename, bool enable)
387{
388 return writeStr(filename, enable ? "1" : "0");
389}
390
391// Check whether the category is supported on the device with the current
392// rootness. A category is supported only if all its required /sys/ files are
393// writable and if enabling the category will enable one or more tracing tags
394// or /sys/ files.
395static bool isCategorySupported(const TracingCategory& category)
396{
sergeyvdb404152016-05-02 19:26:07 -0700397 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700398 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700399 }
400
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700401 if (strcmp(category.name, k_pdxServiceCategory) == 0) {
402 return true;
403 }
404
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800405 bool ok = category.tags != 0;
406 for (int i = 0; i < MAX_SYS_FILES; i++) {
407 const char* path = category.sysfiles[i].path;
408 bool req = category.sysfiles[i].required == REQ;
409 if (path != NULL) {
410 if (req) {
411 if (!fileIsWritable(path)) {
412 return false;
413 } else {
414 ok = true;
415 }
416 } else {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800417 ok = true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800418 }
419 }
420 }
421 return ok;
422}
423
424// Check whether the category would be supported on the device if the user
425// were root. This function assumes that root is able to write to any file
426// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700427// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800428static bool isCategorySupportedForRoot(const TracingCategory& category)
429{
430 bool ok = category.tags != 0;
431 for (int i = 0; i < MAX_SYS_FILES; i++) {
432 const char* path = category.sysfiles[i].path;
433 bool req = category.sysfiles[i].required == REQ;
434 if (path != NULL) {
435 if (req) {
436 if (!fileExists(path)) {
437 return false;
438 } else {
439 ok = true;
440 }
441 } else {
442 ok |= fileExists(path);
443 }
444 }
445 }
446 return ok;
447}
448
449// Enable or disable overwriting of the kernel trace buffers. Disabling this
450// will cause tracing to stop once the trace buffers have filled up.
451static bool setTraceOverwriteEnable(bool enable)
452{
453 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
454}
455
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700456// Set the user initiated trace property
457static bool setUserInitiatedTraceProperty(bool enable)
458{
459 if (!android::base::SetProperty(k_userInitiatedTraceProperty, enable ? "1" : "")) {
460 fprintf(stderr, "error setting user initiated strace system property\n");
461 return false;
462 }
463 return true;
464}
465
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800466// Enable or disable kernel tracing.
467static bool setTracingEnabled(bool enable)
468{
469 return setKernelOptionEnable(k_tracingOnPath, enable);
470}
471
472// Clear the contents of the kernel trace.
473static bool clearTrace()
474{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700475 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800476}
477
478// Set the size of the kernel's trace buffer in kilobytes.
479static bool setTraceBufferSizeKB(int size)
480{
481 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800482 if (size < 1) {
483 size = 1;
484 }
485 snprintf(str, 32, "%d", size);
486 return writeStr(k_traceBufferSizePath, str);
487}
488
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700489#if 0
490// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700491// Set the default size of cmdline hashtable
492static bool setCmdlineSize()
493{
Joel Fernandesce964f22017-06-06 12:20:29 -0700494 if (fileExists(k_traceCmdlineSizePath)) {
495 return writeStr(k_traceCmdlineSizePath, "8192");
496 }
497 return true;
Joel Fernandesed80bd02017-06-02 10:19:28 -0700498}
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700499#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700500
Carmen Jacksonea826792017-05-05 11:42:32 -0700501// Set the clock to the best available option while tracing. Use 'boot' if it's
502// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700503// Any write to the trace_clock sysfs file will reset the buffer, so only
504// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700505static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800506{
Carmen Jacksonea826792017-05-05 11:42:32 -0700507 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
508 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
509 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700510
Carmen Jacksonea826792017-05-05 11:42:32 -0700511 std::string newClock;
512 if (clockStr.find("boot") != std::string::npos) {
513 newClock = "boot";
514 } else if (clockStr.find("mono") != std::string::npos) {
515 newClock = "mono";
516 } else {
517 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700518 }
519
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700520 size_t begin = clockStr.find('[') + 1;
521 size_t end = clockStr.find(']');
Carmen Jacksonea826792017-05-05 11:42:32 -0700522 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
523 return true;
524 }
525 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800526}
527
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700528static bool setPrintTgidEnableIfPresent(bool enable)
529{
John Reckedbf9ec2018-06-29 11:15:17 -0700530 // Pre-4.13 this was options/print-tgid as an android-specific option.
531 // In 4.13+ this is an upstream option called options/record-tgid
532 // Both options produce the same ftrace format change
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700533 if (fileExists(k_printTgidPath)) {
534 return setKernelOptionEnable(k_printTgidPath, enable);
535 }
John Recke757b1c2018-06-28 12:24:33 -0700536 if (fileExists(k_recordTgidPath)) {
537 return setKernelOptionEnable(k_recordTgidPath, enable);
538 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700539 return true;
540}
541
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800542// Poke all the binder-enabled processes in the system to get them to re-read
543// their system properties.
544static bool pokeBinderServices()
545{
546 sp<IServiceManager> sm = defaultServiceManager();
547 Vector<String16> services = sm->listServices();
548 for (size_t i = 0; i < services.size(); i++) {
549 sp<IBinder> obj = sm->checkService(services[i]);
550 if (obj != NULL) {
551 Parcel data;
552 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
553 NULL, 0) != OK) {
554 if (false) {
555 // XXX: For some reason this fails on tablets trying to
556 // poke the "phone" service. It's not clear whether some
557 // are expected to fail.
558 String8 svc(services[i]);
559 fprintf(stderr, "error poking binder service %s\n",
560 svc.string());
561 return false;
562 }
563 }
564 }
565 }
566 return true;
567}
568
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100569// Poke all the HAL processes in the system to get them to re-read
570// their system properties.
571static void pokeHalServices()
572{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100573 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100574 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100575 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100576 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100577
578 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800579
580 if (sm == nullptr) {
581 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
582 return;
583 }
584
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800585 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100586 for (size_t i = 0; i < interfaces.size(); i++) {
587 string fqInstanceName = interfaces[i];
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700588 string::size_type n = fqInstanceName.find('/');
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100589 if (n == std::string::npos || interfaces[i].size() == n+1)
590 continue;
591 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
592 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100593 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
594 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100595 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100596 continue;
597 }
Carmen Jackson73206122017-04-18 15:37:57 -0700598
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100599 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700600 if (interface == nullptr) {
601 // ignore
602 continue;
603 }
604
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100605 auto notifyRet = interface->notifySyspropsChanged();
606 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100607 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800608 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100609 }
610 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800611 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100612 // TODO(b/34242478) fix this when we determine the correct ACL
613 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800614 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100615}
616
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800617// Set the trace tags that userland tracing uses, and poke the running
618// processes to pick up the new value.
619static bool setTagsProperty(uint64_t tags)
620{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700621 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
622 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800623 fprintf(stderr, "error setting trace tags system property\n");
624 return false;
625 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700626 return true;
627}
628
sergeyv4144eff2016-04-28 11:40:04 -0700629static void clearAppProperties()
630{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700631 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700632 fprintf(stderr, "failed to clear system property: %s",
633 k_traceAppsNumberProperty);
634 }
635}
636
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700637// Set the system property that indicates which apps should perform
638// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700639static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700640{
sergeyv4144eff2016-04-28 11:40:04 -0700641 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700642 char* start = cmdline;
sergeyv4144eff2016-04-28 11:40:04 -0700643 while (start != NULL) {
sergeyv4144eff2016-04-28 11:40:04 -0700644 char* end = strchr(start, ',');
645 if (end != NULL) {
646 *end = '\0';
647 end++;
648 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700649 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
650 if (!android::base::SetProperty(key, start)) {
651 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700652 clearAppProperties();
653 return false;
654 }
655 start = end;
656 i++;
657 }
658
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700659 std::string value = android::base::StringPrintf("%d", i);
660 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
661 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700662 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700663 return false;
664 }
665 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800666}
667
668// Disable all /sys/ enable files.
669static bool disableKernelTraceEvents() {
670 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700671 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800672 const TracingCategory &c = k_categories[i];
673 for (int j = 0; j < MAX_SYS_FILES; j++) {
674 const char* path = c.sysfiles[j].path;
675 if (path != NULL && fileIsWritable(path)) {
676 ok &= setKernelOptionEnable(path, false);
677 }
678 }
679 }
680 return ok;
681}
682
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700683// Verify that the comma separated list of functions are being traced by the
684// kernel.
685static bool verifyKernelTraceFuncs(const char* funcs)
686{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100687 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800688 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100689 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700690 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100691 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700692 }
693
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100694 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700695
696 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100697 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700698 bool ok = true;
699 char* myFuncs = strdup(funcs);
700 char* func = strtok(myFuncs, ",");
701 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100702 if (!strchr(func, '*')) {
703 String8 fancyFunc = String8::format("\n%s\n", func);
704 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
705 if (!found || func[0] == '\0') {
706 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
707 "to trace.\n", func);
708 ok = false;
709 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700710 }
711 func = strtok(NULL, ",");
712 }
713 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700714 return ok;
715}
716
717// Set the comma separated list of functions that the kernel is to trace.
718static bool setKernelTraceFuncs(const char* funcs)
719{
720 bool ok = true;
721
722 if (funcs == NULL || funcs[0] == '\0') {
723 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700724 if (fileIsWritable(k_currentTracerPath)) {
725 ok &= writeStr(k_currentTracerPath, "nop");
726 }
727 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700728 ok &= truncateFile(k_ftraceFilterPath);
729 }
730 } else {
731 // Enable kernel function tracing.
732 ok &= writeStr(k_currentTracerPath, "function_graph");
733 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
734 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
735 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
736 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
737
738 // Set the requested filter functions.
739 ok &= truncateFile(k_ftraceFilterPath);
740 char* myFuncs = strdup(funcs);
741 char* func = strtok(myFuncs, ",");
742 while (func) {
743 ok &= appendStr(k_ftraceFilterPath, func);
744 func = strtok(NULL, ",");
745 }
746 free(myFuncs);
747
748 // Verify that the set functions are being traced.
749 if (ok) {
750 ok &= verifyKernelTraceFuncs(funcs);
751 }
752 }
753
754 return ok;
755}
756
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900757static bool setCategoryEnable(const char* name, bool enable)
758{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700759 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900760 const TracingCategory& c = k_categories[i];
761 if (strcmp(name, c.name) == 0) {
762 if (isCategorySupported(c)) {
763 g_categoryEnables[i] = enable;
764 return true;
765 } else {
766 if (isCategorySupportedForRoot(c)) {
767 fprintf(stderr, "error: category \"%s\" requires root "
768 "privileges.\n", name);
769 } else {
770 fprintf(stderr, "error: category \"%s\" is not supported "
771 "on this device.\n", name);
772 }
773 return false;
774 }
775 }
776 }
777 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
778 return false;
779}
780
781static bool setCategoriesEnableFromFile(const char* categories_file)
782{
783 if (!categories_file) {
784 return true;
785 }
786 Tokenizer* tokenizer = NULL;
787 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
788 return false;
789 }
790 bool ok = true;
791 while (!tokenizer->isEol()) {
792 String8 token = tokenizer->nextToken(" ");
793 if (token.isEmpty()) {
794 tokenizer->skipDelimiters(" ");
795 continue;
796 }
797 ok &= setCategoryEnable(token.string(), true);
798 }
799 delete tokenizer;
800 return ok;
801}
802
Hector Dearman11845782018-03-08 14:35:44 +0000803static bool setUpUserspaceTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800804{
805 bool ok = true;
806
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800807 // Set up the tags property.
808 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700809 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800810 if (g_categoryEnables[i]) {
811 const TracingCategory &c = k_categories[i];
812 tags |= c.tags;
813 }
814 }
815 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700816
817 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700818 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700819 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
820 coreServicesTagEnabled = g_categoryEnables[i];
821 }
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700822
823 // Set whether to poke PDX services in this session.
824 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
825 g_tracePdx = g_categoryEnables[i];
826 }
sergeyvdb404152016-05-02 19:26:07 -0700827 }
828
829 std::string packageList(g_debugAppCmdLine);
830 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700831 if (!packageList.empty()) {
832 packageList += ",";
833 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700834 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700835 }
Dan Austin09a79872016-05-31 13:27:03 -0700836 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700837 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100838 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800839
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700840 if (g_tracePdx) {
841 ok &= ServiceUtility::PokeServices();
842 }
843
Hector Dearman11845782018-03-08 14:35:44 +0000844 return ok;
845}
846
847static void cleanUpUserspaceTracing()
848{
849 setTagsProperty(0);
850 clearAppProperties();
851 pokeBinderServices();
852
853 if (g_tracePdx) {
854 ServiceUtility::PokeServices();
855 }
856}
857
858
859// Set all the kernel tracing settings to the desired state for this trace
860// capture.
861static bool setUpKernelTracing()
862{
863 bool ok = true;
864
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700865 ok &= setUserInitiatedTraceProperty(true);
866
Hector Dearman11845782018-03-08 14:35:44 +0000867 // Set up the tracing options.
868 ok &= setCategoriesEnableFromFile(g_categoriesFile);
869 ok &= setTraceOverwriteEnable(g_traceOverwrite);
870 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
871 // TODO: Re-enable after stabilization
872 //ok &= setCmdlineSize();
873 ok &= setClock();
874 ok &= setPrintTgidEnableIfPresent(true);
875 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
876
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800877 // Disable all the sysfs enables. This is done as a separate loop from
878 // the enables to allow the same enable to exist in multiple categories.
879 ok &= disableKernelTraceEvents();
880
881 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700882 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800883 if (g_categoryEnables[i]) {
884 const TracingCategory &c = k_categories[i];
885 for (int j = 0; j < MAX_SYS_FILES; j++) {
886 const char* path = c.sysfiles[j].path;
887 bool required = c.sysfiles[j].required == REQ;
888 if (path != NULL) {
889 if (fileIsWritable(path)) {
890 ok &= setKernelOptionEnable(path, true);
891 } else if (required) {
892 fprintf(stderr, "error writing file %s\n", path);
893 ok = false;
894 }
895 }
896 }
897 }
898 }
899
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800900 return ok;
901}
902
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700903// Reset all the kernel tracing settings to their default state.
Hector Dearman11845782018-03-08 14:35:44 +0000904static void cleanUpKernelTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800905{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800906 // Disable all tracing that we're able to.
907 disableKernelTraceEvents();
908
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800909 // Set the options back to their defaults.
910 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700911 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700912 setPrintTgidEnableIfPresent(false);
913 setKernelTraceFuncs(NULL);
Carmen Jackson65ecfbb2018-05-22 10:29:47 -0700914 setUserInitiatedTraceProperty(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700915}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800916
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700917// Enable tracing in the kernel.
918static bool startTrace()
919{
920 return setTracingEnabled(true);
921}
922
923// Disable tracing in the kernel.
924static void stopTrace()
925{
926 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800927}
928
Martijn Coenend9535872015-11-26 10:00:55 +0100929// Read data from the tracing pipe and forward to stdout
930static void streamTrace()
931{
932 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800933 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100934 if (traceFD == -1) {
935 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
936 strerror(errno), errno);
937 return;
938 }
939 while (!g_traceAborted) {
940 ssize_t bytes_read = read(traceFD, trace_data, 4096);
941 if (bytes_read > 0) {
942 write(STDOUT_FILENO, trace_data, bytes_read);
943 fflush(stdout);
944 } else {
945 if (!g_traceAborted) {
946 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
947 bytes_read, errno, strerror(errno));
948 }
949 break;
950 }
951 }
952}
953
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800954// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700955static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800956{
John Reck6c8ac922016-03-28 11:25:30 -0700957 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800958 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800959 if (traceFD == -1) {
960 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
961 strerror(errno), errno);
962 return;
963 }
964
965 if (g_compress) {
966 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800967 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700968
969 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800970 if (result != Z_OK) {
971 fprintf(stderr, "error initializing zlib: %d\n", result);
972 close(traceFD);
973 return;
974 }
975
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700976 constexpr size_t bufSize = 64*1024;
977 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
978 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
979 if (!in || !out) {
980 fprintf(stderr, "couldn't allocate buffers\n");
981 close(traceFD);
982 return;
983 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800984
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700985 int flush = Z_NO_FLUSH;
986
987 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800988 zs.avail_out = bufSize;
989
990 do {
991
992 if (zs.avail_in == 0) {
993 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700994 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800995 if (result < 0) {
996 fprintf(stderr, "error reading trace: %s (%d)\n",
997 strerror(errno), errno);
998 result = Z_STREAM_END;
999 break;
1000 } else if (result == 0) {
1001 flush = Z_FINISH;
1002 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001003 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001004 zs.avail_in = result;
1005 }
1006 }
1007
1008 if (zs.avail_out == 0) {
1009 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -07001010 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001011 if ((size_t)result < bufSize) {
1012 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1013 strerror(errno), errno);
1014 result = Z_STREAM_END; // skip deflate error message
1015 zs.avail_out = bufSize; // skip the final write
1016 break;
1017 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001018 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001019 zs.avail_out = bufSize;
1020 }
1021
1022 } while ((result = deflate(&zs, flush)) == Z_OK);
1023
1024 if (result != Z_STREAM_END) {
1025 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
1026 }
1027
1028 if (zs.avail_out < bufSize) {
1029 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -07001030 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001031 if ((size_t)result < bytes) {
1032 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1033 strerror(errno), errno);
1034 }
1035 }
1036
1037 result = deflateEnd(&zs);
1038 if (result != Z_OK) {
1039 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1040 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001041 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001042 char buf[4096];
1043 ssize_t rc;
1044 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1045 if (!android::base::WriteFully(outFd, buf, rc)) {
1046 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1047 break;
1048 }
1049 }
1050 if (rc == -1) {
1051 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001052 }
1053 }
1054
1055 close(traceFD);
1056}
1057
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001058static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001059{
1060 if (!g_nohup) {
1061 g_traceAborted = true;
1062 }
1063}
1064
1065static void registerSigHandler()
1066{
1067 struct sigaction sa;
1068 sigemptyset(&sa.sa_mask);
1069 sa.sa_flags = 0;
1070 sa.sa_handler = handleSignal;
1071 sigaction(SIGHUP, &sa, NULL);
1072 sigaction(SIGINT, &sa, NULL);
1073 sigaction(SIGQUIT, &sa, NULL);
1074 sigaction(SIGTERM, &sa, NULL);
1075}
1076
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001077static void listSupportedCategories()
1078{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001079 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001080 const TracingCategory& c = k_categories[i];
1081 if (isCategorySupported(c)) {
1082 printf(" %10s - %s\n", c.name, c.longname);
1083 }
1084 }
1085}
1086
1087// Print the command usage help to stderr.
1088static void showHelp(const char *cmd)
1089{
1090 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1091 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001092 " -a appname enable app-level tracing for a comma "
Daniel Colascione519a0792018-02-09 20:05:39 -08001093 "separated list of cmdlines; * is a wildcard matching any process\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001094 " -b N use a trace buffer size of N KB\n"
1095 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001096 " -f filename use the categories written in a file as space-separated\n"
1097 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001098 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001099 " -n ignore signals\n"
1100 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001101 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001102 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001103 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001104 " --async_dump dump the current contents of circular trace buffer\n"
1105 " --async_stop stop tracing and dump the current contents of circular\n"
1106 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001107 " --stream stream trace to stdout as it enters the trace buffer\n"
1108 " Note: this can take significant CPU time, and is best\n"
1109 " used for measuring things that are not affected by\n"
1110 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001111 " --list_categories\n"
1112 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001113 " -o filename write the trace to the specified file instead\n"
1114 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001115 );
1116}
1117
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001118bool findTraceFiles()
1119{
1120 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1121 static const std::string tracefs_path = "/sys/kernel/tracing/";
1122 static const std::string trace_file = "trace_marker";
1123
1124 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1125 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1126
1127 if (!tracefs && !debugfs) {
1128 fprintf(stderr, "Error: Did not find trace folder\n");
1129 return false;
1130 }
1131
1132 if (tracefs) {
1133 g_traceFolder = tracefs_path;
1134 } else {
1135 g_traceFolder = debugfs_path;
1136 }
1137
1138 return true;
1139}
1140
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001141int main(int argc, char **argv)
1142{
1143 bool async = false;
1144 bool traceStart = true;
1145 bool traceStop = true;
1146 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001147 bool traceStream = false;
Hector Dearman11845782018-03-08 14:35:44 +00001148 bool onlyUserspace = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001149
1150 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1151 showHelp(argv[0]);
1152 exit(0);
1153 }
1154
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001155 if (!findTraceFiles()) {
1156 fprintf(stderr, "No trace folder found\n");
1157 exit(-1);
1158 }
1159
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001160 for (;;) {
1161 int ret;
1162 int option_index = 0;
1163 static struct option long_options[] = {
Hector Dearman11845782018-03-08 14:35:44 +00001164 {"async_start", no_argument, 0, 0 },
1165 {"async_stop", no_argument, 0, 0 },
1166 {"async_dump", no_argument, 0, 0 },
1167 {"only_userspace", no_argument, 0, 0 },
1168 {"list_categories", no_argument, 0, 0 },
1169 {"stream", no_argument, 0, 0 },
1170 { 0, 0, 0, 0 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001171 };
1172
John Reck40b26b42016-03-30 09:44:36 -07001173 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001174 long_options, &option_index);
1175
1176 if (ret < 0) {
1177 for (int i = optind; i < argc; i++) {
1178 if (!setCategoryEnable(argv[i], true)) {
1179 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1180 exit(1);
1181 }
1182 }
1183 break;
1184 }
1185
1186 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001187 case 'a':
1188 g_debugAppCmdLine = optarg;
1189 break;
1190
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001191 case 'b':
1192 g_traceBufferSizeKB = atoi(optarg);
1193 break;
1194
1195 case 'c':
1196 g_traceOverwrite = true;
1197 break;
1198
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001199 case 'f':
1200 g_categoriesFile = optarg;
1201 break;
1202
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001203 case 'k':
1204 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001205 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001206
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001207 case 'n':
1208 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001209 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001210
1211 case 's':
1212 g_initialSleepSecs = atoi(optarg);
1213 break;
1214
1215 case 't':
1216 g_traceDurationSeconds = atoi(optarg);
1217 break;
1218
1219 case 'z':
1220 g_compress = true;
1221 break;
1222
John Reck40b26b42016-03-30 09:44:36 -07001223 case 'o':
1224 g_outputFile = optarg;
1225 break;
1226
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001227 case 0:
1228 if (!strcmp(long_options[option_index].name, "async_start")) {
1229 async = true;
1230 traceStop = false;
1231 traceDump = false;
1232 g_traceOverwrite = true;
1233 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1234 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001235 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001236 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1237 async = true;
1238 traceStart = false;
1239 traceStop = false;
Hector Dearman11845782018-03-08 14:35:44 +00001240 } else if (!strcmp(long_options[option_index].name, "only_userspace")) {
1241 onlyUserspace = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001242 } else if (!strcmp(long_options[option_index].name, "stream")) {
1243 traceStream = true;
1244 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001245 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1246 listSupportedCategories();
1247 exit(0);
1248 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001249 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001250
1251 default:
1252 fprintf(stderr, "\n");
1253 showHelp(argv[0]);
1254 exit(-1);
1255 break;
1256 }
1257 }
1258
Hector Dearman11845782018-03-08 14:35:44 +00001259 if (onlyUserspace) {
1260 if (!async || !(traceStart || traceStop)) {
1261 fprintf(stderr, "--only_userspace can only be used with "
1262 "--async_start or --async_stop\n");
1263 exit(1);
1264 }
1265 }
1266
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001267 registerSigHandler();
1268
1269 if (g_initialSleepSecs > 0) {
1270 sleep(g_initialSleepSecs);
1271 }
1272
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001273 bool ok = true;
Hector Dearman11845782018-03-08 14:35:44 +00001274
Wei Wang5b73b742018-03-08 13:33:12 -08001275 if (traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001276 ok &= setUpUserspaceTracing();
1277 }
1278
1279 if (ok && traceStart && !onlyUserspace) {
1280 ok &= setUpKernelTracing();
Wei Wang5b73b742018-03-08 13:33:12 -08001281 ok &= startTrace();
1282 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001283
1284 if (ok && traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001285
1286 if (!traceStream && !onlyUserspace) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001287 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001288 fflush(stdout);
1289 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001290
1291 // We clear the trace after starting it because tracing gets enabled for
1292 // each CPU individually in the kernel. Having the beginning of the trace
1293 // contain entries from only one CPU can cause "begin" entries without a
1294 // matching "end" entry to show up if a task gets migrated from one CPU to
1295 // another.
Hector Dearman11845782018-03-08 14:35:44 +00001296 if (!onlyUserspace)
1297 ok = clearTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001298
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001299 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001300 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001301 // Sleep to allow the trace to be captured.
1302 struct timespec timeLeft;
1303 timeLeft.tv_sec = g_traceDurationSeconds;
1304 timeLeft.tv_nsec = 0;
1305 do {
1306 if (g_traceAborted) {
1307 break;
1308 }
1309 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1310 }
Martijn Coenend9535872015-11-26 10:00:55 +01001311
1312 if (traceStream) {
1313 streamTrace();
1314 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001315 }
1316
1317 // Stop the trace and restore the default settings.
Hector Dearman11845782018-03-08 14:35:44 +00001318 if (traceStop && !onlyUserspace)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001319 stopTrace();
1320
Hector Dearman11845782018-03-08 14:35:44 +00001321 if (ok && traceDump && !onlyUserspace) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001322 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001323 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001324 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001325 int outFd = STDOUT_FILENO;
1326 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001327 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001328 }
1329 if (outFd == -1) {
1330 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1331 } else {
1332 dprintf(outFd, "TRACE:\n");
1333 dumpTrace(outFd);
1334 if (g_outputFile) {
1335 close(outFd);
1336 }
1337 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001338 } else {
1339 printf("\ntrace aborted.\n");
1340 fflush(stdout);
1341 }
1342 clearTrace();
1343 } else if (!ok) {
1344 fprintf(stderr, "unable to start tracing\n");
1345 }
1346
1347 // Reset the trace buffer size to 1.
Hector Dearman11845782018-03-08 14:35:44 +00001348 if (traceStop) {
1349 cleanUpUserspaceTracing();
1350 if (!onlyUserspace)
1351 cleanUpKernelTracing();
1352 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001353
1354 return g_traceAborted ? 1 : 0;
1355}