blob: 2e41eb5f1ace00c395b67bb1ce356d9fdea2509e [file] [log] [blame]
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Paul Lawrence2cd93cc2017-01-17 09:50:18 -080017#define LOG_TAG "atrace"
John Reck40b26b42016-03-30 09:44:36 -070018
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080019#include <errno.h>
20#include <fcntl.h>
21#include <getopt.h>
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070022#include <inttypes.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080023#include <signal.h>
24#include <stdarg.h>
25#include <stdbool.h>
26#include <stdio.h>
27#include <stdlib.h>
Elliott Hughes3da5d232015-01-25 08:35:20 -080028#include <string.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080029#include <time.h>
Martijn Coenend9535872015-11-26 10:00:55 +010030#include <unistd.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080031#include <zlib.h>
32
Carmen Jacksonea826792017-05-05 11:42:32 -070033#include <fstream>
Elliott Hughesa252f4d2016-07-21 17:12:15 -070034#include <memory>
35
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080036#include <binder/IBinder.h>
37#include <binder/IServiceManager.h>
38#include <binder/Parcel.h>
39
Martijn Coenenee9b97e2016-11-16 16:00:26 +010040#include <android/hidl/manager/1.0/IServiceManager.h>
41#include <hidl/ServiceManagement.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080042
Corey Tabakaa6c0a722017-05-31 16:37:40 -070043#include <pdx/default_transport/service_utility.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080044#include <utils/String8.h>
John Reck469a1942015-03-26 15:31:35 -070045#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +090046#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080047#include <utils/Trace.h>
Stephane Gasparinid8419c22016-03-02 13:45:15 +010048#include <android-base/file.h>
Elliott Hughes5fd6ff62017-03-28 14:55:31 -070049#include <android-base/macros.h>
50#include <android-base/properties.h>
51#include <android-base/stringprintf.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080052
53using namespace android;
Corey Tabakaa6c0a722017-05-31 16:37:40 -070054using pdx::default_transport::ServiceUtility;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080055
Martijn Coenenee9b97e2016-11-16 16:00:26 +010056using std::string;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080057
sergeyv4144eff2016-04-28 11:40:04 -070058#define MAX_SYS_FILES 10
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080059
60const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
Carmen Jacksonab1118e2018-05-22 10:29:47 -070061const char* k_userInitiatedTraceProperty = "debug.atrace.user_initiated";
sergeyv4144eff2016-04-28 11:40:04 -070062
63const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
64const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-02 19:26:07 -070065const char* k_coreServiceCategory = "core_services";
Corey Tabakaa6c0a722017-05-31 16:37:40 -070066const char* k_pdxServiceCategory = "pdx";
sergeyvdb404152016-05-02 19:26:07 -070067const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080068
69typedef enum { OPT, REQ } requiredness ;
70
71struct TracingCategory {
72 // The name identifying the category.
73 const char* name;
74
75 // A longer description of the category.
76 const char* longname;
77
78 // The userland tracing tags that the category enables.
79 uint64_t tags;
80
81 // The fname==NULL terminated list of /sys/ files that the category
82 // enables.
83 struct {
84 // Whether the file must be writable in order to enable the tracing
85 // category.
86 requiredness required;
87
88 // The path to the enable file.
89 const char* path;
90 } sysfiles[MAX_SYS_FILES];
91};
92
93/* Tracing categories */
94static const TracingCategory k_categories[] = {
John Reck732a29a2017-05-24 16:09:21 -070095 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, {
96 { OPT, "events/mdss/enable" },
Wei Wangbcfb4872018-02-13 10:47:23 -080097 { OPT, "events/sde/enable" },
Jesse Hall5731aaa2018-07-27 12:01:08 -070098 { OPT, "events/mali_systrace/enable" },
John Reck732a29a2017-05-24 16:09:21 -070099 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700100 { "input", "Input", ATRACE_TAG_INPUT, { } },
101 { "view", "View System", ATRACE_TAG_VIEW, { } },
102 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
103 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
104 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -0500105 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700106 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
107 { "video", "Video", ATRACE_TAG_VIDEO, { } },
108 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
109 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -0700110 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -0700111 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -0700112 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -0700113 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -0700114 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 14:36:20 -0700115 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-07-01 01:46:25 +0900116 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Greg Hackmannbbd7d992014-12-01 14:43:34 -0800117 { "database", "Database", ATRACE_TAG_DATABASE, { } },
Felipe Leme0f97c1d2016-09-07 11:33:26 -0700118 { "network", "Network", ATRACE_TAG_NETWORK, { } },
Josh Gao468b4cb2016-11-29 10:55:21 -0800119 { "adb", "ADB", ATRACE_TAG_ADB, { } },
Martijn Coenen42f2ab42018-03-09 09:27:32 +0100120 { "vibrator", "Vibrator", ATRACE_TAG_VIBRATOR, { } },
121 { "aidl", "AIDL calls", ATRACE_TAG_AIDL, { } },
Mika Raentob363cf52018-04-23 22:09:13 +0100122 { "nnapi", "NNAPI", ATRACE_TAG_NNAPI, { } },
sergeyvdb404152016-05-02 19:26:07 -0700123 { k_coreServiceCategory, "Core services", 0, { } },
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700124 { k_pdxServiceCategory, "PDX services", 0, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700125 { "sched", "CPU Scheduling", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800126 { REQ, "events/sched/sched_switch/enable" },
127 { REQ, "events/sched/sched_wakeup/enable" },
Joel Fernandesee593e22017-06-04 13:05:59 -0700128 { OPT, "events/sched/sched_waking/enable" },
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800129 { OPT, "events/sched/sched_blocked_reason/enable" },
130 { OPT, "events/sched/sched_cpu_hotplug/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, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800191 { REQ, "events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800192 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700193 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800194 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800195 } },
Colin Cross580407f2014-08-18 15:22:13 -0700196 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800197 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
198 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
199 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
200 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Carmen Jackson7a23eb72018-07-02 13:14:56 -0700201 { OPT, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 15:22:13 -0700202 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800203 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800204 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800205 } },
Scott Bauerae473362015-06-08 16:32:36 -0700206 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800207 { REQ, "events/binder/binder_transaction/enable" },
208 { REQ, "events/binder/binder_transaction_received/enable" },
Mika Raento80c3e5d2018-06-25 16:47:24 +0100209 { REQ, "events/binder/binder_transaction_alloc_buf/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;
Yi Kong19d5c002018-07-20 13:39:55 -0700229static const char* g_categoriesFile = nullptr;
230static const char* g_kernelTraceFuncs = nullptr;
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
John Recke757b1c2018-06-28 12:24:33 -0700262static const char* k_recordTgidPath =
263 "options/record-tgid";
264
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700265static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800266 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700267
268static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800269 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700270
271static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800272 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700273
274static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800275 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700276
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700277static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800278 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700279
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800280static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800281 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800282
283static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800284 "trace";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800285
Martijn Coenend9535872015-11-26 10:00:55 +0100286static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800287 "trace_pipe";
Martijn Coenend9535872015-11-26 10:00:55 +0100288
John Reck469a1942015-03-26 15:31:35 -0700289static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800290 "trace_marker";
John Reck469a1942015-03-26 15:31:35 -0700291
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800292// Check whether a file exists.
293static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800294 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800295}
296
297// Check whether a file is writable.
298static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800299 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800300}
301
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700302// Truncate a file.
303static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800304{
Jamie Gennis43122e72013-03-21 14:06:31 -0700305 // This uses creat rather than truncate because some of the debug kernel
306 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
307 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800308 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 14:06:31 -0700309 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800310 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 14:06:31 -0700311 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700312 return false;
313 }
314
Jamie Gennis43122e72013-03-21 14:06:31 -0700315 close(traceFD);
316
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700317 return true;
318}
319
320static bool _writeStr(const char* filename, const char* str, int flags)
321{
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800322 std::string fullFilename = g_traceFolder + filename;
323 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800324 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800325 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800326 strerror(errno), errno);
327 return false;
328 }
329
330 bool ok = true;
331 ssize_t len = strlen(str);
332 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800333 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800334 strerror(errno), errno);
335 ok = false;
336 }
337
338 close(fd);
339
340 return ok;
341}
342
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700343// Write a string to a file, returning true if the write was successful.
344static bool writeStr(const char* filename, const char* str)
345{
346 return _writeStr(filename, str, O_WRONLY);
347}
348
349// Append a string to a file, returning true if the write was successful.
350static bool appendStr(const char* filename, const char* str)
351{
352 return _writeStr(filename, str, O_APPEND|O_WRONLY);
353}
354
John Reck469a1942015-03-26 15:31:35 -0700355static void writeClockSyncMarker()
356{
357 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200358 int len = 0;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800359 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200360 if (fd == -1) {
361 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
362 strerror(errno), errno);
363 return;
364 }
John Reck469a1942015-03-26 15:31:35 -0700365 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 14:25:23 +0200366
367 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
368 if (write(fd, buffer, len) != len) {
369 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
370 }
371
372 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
373 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
374 if (write(fd, buffer, len) != len) {
375 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
376 }
377
378 close(fd);
John Reck469a1942015-03-26 15:31:35 -0700379}
380
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800381// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
382// file.
383static bool setKernelOptionEnable(const char* filename, bool enable)
384{
385 return writeStr(filename, enable ? "1" : "0");
386}
387
388// Check whether the category is supported on the device with the current
389// rootness. A category is supported only if all its required /sys/ files are
390// writable and if enabling the category will enable one or more tracing tags
391// or /sys/ files.
392static bool isCategorySupported(const TracingCategory& category)
393{
sergeyvdb404152016-05-02 19:26:07 -0700394 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700395 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-02 19:26:07 -0700396 }
397
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700398 if (strcmp(category.name, k_pdxServiceCategory) == 0) {
399 return true;
400 }
401
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800402 bool ok = category.tags != 0;
403 for (int i = 0; i < MAX_SYS_FILES; i++) {
404 const char* path = category.sysfiles[i].path;
405 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700406 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800407 if (req) {
408 if (!fileIsWritable(path)) {
409 return false;
410 } else {
411 ok = true;
412 }
413 } else {
Howard Cheneb8acbf2017-05-10 16:32:11 +0800414 ok = true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800415 }
416 }
417 }
418 return ok;
419}
420
421// Check whether the category would be supported on the device if the user
422// were root. This function assumes that root is able to write to any file
423// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 11:40:12 -0700424// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800425static bool isCategorySupportedForRoot(const TracingCategory& category)
426{
427 bool ok = category.tags != 0;
428 for (int i = 0; i < MAX_SYS_FILES; i++) {
429 const char* path = category.sysfiles[i].path;
430 bool req = category.sysfiles[i].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700431 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800432 if (req) {
433 if (!fileExists(path)) {
434 return false;
435 } else {
436 ok = true;
437 }
438 } else {
439 ok |= fileExists(path);
440 }
441 }
442 }
443 return ok;
444}
445
446// Enable or disable overwriting of the kernel trace buffers. Disabling this
447// will cause tracing to stop once the trace buffers have filled up.
448static bool setTraceOverwriteEnable(bool enable)
449{
450 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
451}
452
Carmen Jacksonab1118e2018-05-22 10:29:47 -0700453// Set the user initiated trace property
454static bool setUserInitiatedTraceProperty(bool enable)
455{
456 if (!android::base::SetProperty(k_userInitiatedTraceProperty, enable ? "1" : "")) {
457 fprintf(stderr, "error setting user initiated strace system property\n");
458 return false;
459 }
460 return true;
461}
462
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800463// Enable or disable kernel tracing.
464static bool setTracingEnabled(bool enable)
465{
466 return setKernelOptionEnable(k_tracingOnPath, enable);
467}
468
469// Clear the contents of the kernel trace.
470static bool clearTrace()
471{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700472 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800473}
474
475// Set the size of the kernel's trace buffer in kilobytes.
476static bool setTraceBufferSizeKB(int size)
477{
478 char str[32] = "1";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800479 if (size < 1) {
480 size = 1;
481 }
482 snprintf(str, 32, "%d", size);
483 return writeStr(k_traceBufferSizePath, str);
484}
485
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700486#if 0
487// TODO: Re-enable after stabilization
Joel Fernandesed80bd02017-06-02 10:19:28 -0700488// Set the default size of cmdline hashtable
489static bool setCmdlineSize()
490{
Joel Fernandesce964f22017-06-06 12:20:29 -0700491 if (fileExists(k_traceCmdlineSizePath)) {
492 return writeStr(k_traceCmdlineSizePath, "8192");
493 }
494 return true;
Joel Fernandesed80bd02017-06-02 10:19:28 -0700495}
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -0700496#endif
Joel Fernandesed80bd02017-06-02 10:19:28 -0700497
Carmen Jacksonea826792017-05-05 11:42:32 -0700498// Set the clock to the best available option while tracing. Use 'boot' if it's
499// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700500// Any write to the trace_clock sysfs file will reset the buffer, so only
501// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 11:42:32 -0700502static bool setClock()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800503{
Carmen Jacksonea826792017-05-05 11:42:32 -0700504 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
505 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
506 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 14:28:47 -0700507
Carmen Jacksonea826792017-05-05 11:42:32 -0700508 std::string newClock;
509 if (clockStr.find("boot") != std::string::npos) {
510 newClock = "boot";
511 } else if (clockStr.find("mono") != std::string::npos) {
512 newClock = "mono";
513 } else {
514 newClock = "global";
Colin Crossb1ce49b2014-08-20 14:28:47 -0700515 }
516
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700517 size_t begin = clockStr.find('[') + 1;
518 size_t end = clockStr.find(']');
Carmen Jacksonea826792017-05-05 11:42:32 -0700519 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
520 return true;
521 }
522 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800523}
524
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700525static bool setPrintTgidEnableIfPresent(bool enable)
526{
John Reckedbf9ec2018-06-29 11:15:17 -0700527 // Pre-4.13 this was options/print-tgid as an android-specific option.
528 // In 4.13+ this is an upstream option called options/record-tgid
529 // Both options produce the same ftrace format change
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700530 if (fileExists(k_printTgidPath)) {
531 return setKernelOptionEnable(k_printTgidPath, enable);
532 }
John Recke757b1c2018-06-28 12:24:33 -0700533 if (fileExists(k_recordTgidPath)) {
534 return setKernelOptionEnable(k_recordTgidPath, enable);
535 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700536 return true;
537}
538
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800539// Poke all the binder-enabled processes in the system to get them to re-read
540// their system properties.
541static bool pokeBinderServices()
542{
543 sp<IServiceManager> sm = defaultServiceManager();
544 Vector<String16> services = sm->listServices();
545 for (size_t i = 0; i < services.size(); i++) {
546 sp<IBinder> obj = sm->checkService(services[i]);
Yi Kong19d5c002018-07-20 13:39:55 -0700547 if (obj != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800548 Parcel data;
549 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
Yi Kong19d5c002018-07-20 13:39:55 -0700550 nullptr, 0) != OK) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800551 if (false) {
552 // XXX: For some reason this fails on tablets trying to
553 // poke the "phone" service. It's not clear whether some
554 // are expected to fail.
555 String8 svc(services[i]);
556 fprintf(stderr, "error poking binder service %s\n",
557 svc.string());
558 return false;
559 }
560 }
561 }
562 }
563 return true;
564}
565
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100566// Poke all the HAL processes in the system to get them to re-read
567// their system properties.
568static void pokeHalServices()
569{
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100570 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100571 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100572 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100573 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100574
575 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 15:18:06 -0800576
577 if (sm == nullptr) {
578 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
579 return;
580 }
581
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800582 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100583 for (size_t i = 0; i < interfaces.size(); i++) {
584 string fqInstanceName = interfaces[i];
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700585 string::size_type n = fqInstanceName.find('/');
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100586 if (n == std::string::npos || interfaces[i].size() == n+1)
587 continue;
588 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
589 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100590 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
591 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100592 // ignore
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100593 continue;
594 }
Carmen Jackson73206122017-04-18 15:37:57 -0700595
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100596 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 15:37:57 -0700597 if (interface == nullptr) {
598 // ignore
599 continue;
600 }
601
Martijn Coenenf6ac8482017-01-02 15:17:11 +0100602 auto notifyRet = interface->notifySyspropsChanged();
603 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 14:57:38 +0100604 // ignore
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800605 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100606 }
607 });
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800608 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 17:16:31 +0100609 // TODO(b/34242478) fix this when we determine the correct ACL
610 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-11-30 17:28:58 -0800611 }
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100612}
613
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800614// Set the trace tags that userland tracing uses, and poke the running
615// processes to pick up the new value.
616static bool setTagsProperty(uint64_t tags)
617{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700618 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
619 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800620 fprintf(stderr, "error setting trace tags system property\n");
621 return false;
622 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700623 return true;
624}
625
sergeyv4144eff2016-04-28 11:40:04 -0700626static void clearAppProperties()
627{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700628 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 11:40:04 -0700629 fprintf(stderr, "failed to clear system property: %s",
630 k_traceAppsNumberProperty);
631 }
632}
633
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700634// Set the system property that indicates which apps should perform
635// application-level tracing.
Dan Austin09a79872016-05-31 13:27:03 -0700636static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700637{
sergeyv4144eff2016-04-28 11:40:04 -0700638 int i = 0;
Dan Austin09a79872016-05-31 13:27:03 -0700639 char* start = cmdline;
Yi Kong19d5c002018-07-20 13:39:55 -0700640 while (start != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700641 char* end = strchr(start, ',');
Yi Kong19d5c002018-07-20 13:39:55 -0700642 if (end != nullptr) {
sergeyv4144eff2016-04-28 11:40:04 -0700643 *end = '\0';
644 end++;
645 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700646 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
647 if (!android::base::SetProperty(key, start)) {
648 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700649 clearAppProperties();
650 return false;
651 }
652 start = end;
653 i++;
654 }
655
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700656 std::string value = android::base::StringPrintf("%d", i);
657 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
658 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 11:40:04 -0700659 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700660 return false;
661 }
662 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800663}
664
665// Disable all /sys/ enable files.
666static bool disableKernelTraceEvents() {
667 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700668 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800669 const TracingCategory &c = k_categories[i];
670 for (int j = 0; j < MAX_SYS_FILES; j++) {
671 const char* path = c.sysfiles[j].path;
Yi Kong19d5c002018-07-20 13:39:55 -0700672 if (path != nullptr && fileIsWritable(path)) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800673 ok &= setKernelOptionEnable(path, false);
674 }
675 }
676 }
677 return ok;
678}
679
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700680// Verify that the comma separated list of functions are being traced by the
681// kernel.
682static bool verifyKernelTraceFuncs(const char* funcs)
683{
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100684 std::string buf;
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800685 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100686 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700687 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100688 return false;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700689 }
690
Stephane Gasparinid8419c22016-03-02 13:45:15 +0100691 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700692
693 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 09:44:31 +0100694 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700695 bool ok = true;
696 char* myFuncs = strdup(funcs);
697 char* func = strtok(myFuncs, ",");
698 while (func) {
Thomas Buhota2c22872016-01-27 09:44:31 +0100699 if (!strchr(func, '*')) {
700 String8 fancyFunc = String8::format("\n%s\n", func);
701 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
702 if (!found || func[0] == '\0') {
703 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
704 "to trace.\n", func);
705 ok = false;
706 }
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700707 }
Yi Kong19d5c002018-07-20 13:39:55 -0700708 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700709 }
710 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700711 return ok;
712}
713
714// Set the comma separated list of functions that the kernel is to trace.
715static bool setKernelTraceFuncs(const char* funcs)
716{
717 bool ok = true;
718
Yi Kong19d5c002018-07-20 13:39:55 -0700719 if (funcs == nullptr || funcs[0] == '\0') {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700720 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700721 if (fileIsWritable(k_currentTracerPath)) {
722 ok &= writeStr(k_currentTracerPath, "nop");
723 }
724 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700725 ok &= truncateFile(k_ftraceFilterPath);
726 }
727 } else {
728 // Enable kernel function tracing.
729 ok &= writeStr(k_currentTracerPath, "function_graph");
730 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
731 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
732 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
733 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
734
735 // Set the requested filter functions.
736 ok &= truncateFile(k_ftraceFilterPath);
737 char* myFuncs = strdup(funcs);
738 char* func = strtok(myFuncs, ",");
739 while (func) {
740 ok &= appendStr(k_ftraceFilterPath, func);
Yi Kong19d5c002018-07-20 13:39:55 -0700741 func = strtok(nullptr, ",");
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700742 }
743 free(myFuncs);
744
745 // Verify that the set functions are being traced.
746 if (ok) {
747 ok &= verifyKernelTraceFuncs(funcs);
748 }
749 }
750
751 return ok;
752}
753
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900754static bool setCategoryEnable(const char* name, bool enable)
755{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700756 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900757 const TracingCategory& c = k_categories[i];
758 if (strcmp(name, c.name) == 0) {
759 if (isCategorySupported(c)) {
760 g_categoryEnables[i] = enable;
761 return true;
762 } else {
763 if (isCategorySupportedForRoot(c)) {
764 fprintf(stderr, "error: category \"%s\" requires root "
765 "privileges.\n", name);
766 } else {
767 fprintf(stderr, "error: category \"%s\" is not supported "
768 "on this device.\n", name);
769 }
770 return false;
771 }
772 }
773 }
774 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
775 return false;
776}
777
778static bool setCategoriesEnableFromFile(const char* categories_file)
779{
780 if (!categories_file) {
781 return true;
782 }
Yi Kong19d5c002018-07-20 13:39:55 -0700783 Tokenizer* tokenizer = nullptr;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900784 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
785 return false;
786 }
787 bool ok = true;
788 while (!tokenizer->isEol()) {
789 String8 token = tokenizer->nextToken(" ");
790 if (token.isEmpty()) {
791 tokenizer->skipDelimiters(" ");
792 continue;
793 }
794 ok &= setCategoryEnable(token.string(), true);
795 }
796 delete tokenizer;
797 return ok;
798}
799
Hector Dearman11845782018-03-08 14:35:44 +0000800static bool setUpUserspaceTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800801{
802 bool ok = true;
803
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800804 // Set up the tags property.
805 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700806 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800807 if (g_categoryEnables[i]) {
808 const TracingCategory &c = k_categories[i];
809 tags |= c.tags;
810 }
811 }
812 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-02 19:26:07 -0700813
814 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700815 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-02 19:26:07 -0700816 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
817 coreServicesTagEnabled = g_categoryEnables[i];
818 }
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700819
820 // Set whether to poke PDX services in this session.
821 if (strcmp(k_categories[i].name, k_pdxServiceCategory) == 0) {
822 g_tracePdx = g_categoryEnables[i];
823 }
sergeyvdb404152016-05-02 19:26:07 -0700824 }
825
826 std::string packageList(g_debugAppCmdLine);
827 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-02 19:26:07 -0700828 if (!packageList.empty()) {
829 packageList += ",";
830 }
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700831 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-02 19:26:07 -0700832 }
Dan Austin09a79872016-05-31 13:27:03 -0700833 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700834 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 16:00:26 +0100835 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800836
Corey Tabakaa6c0a722017-05-31 16:37:40 -0700837 if (g_tracePdx) {
838 ok &= ServiceUtility::PokeServices();
839 }
840
Hector Dearman11845782018-03-08 14:35:44 +0000841 return ok;
842}
843
844static void cleanUpUserspaceTracing()
845{
846 setTagsProperty(0);
847 clearAppProperties();
848 pokeBinderServices();
849
850 if (g_tracePdx) {
851 ServiceUtility::PokeServices();
852 }
853}
854
855
856// Set all the kernel tracing settings to the desired state for this trace
857// capture.
858static bool setUpKernelTracing()
859{
860 bool ok = true;
861
Carmen Jacksonab1118e2018-05-22 10:29:47 -0700862 ok &= setUserInitiatedTraceProperty(true);
863
Hector Dearman11845782018-03-08 14:35:44 +0000864 // Set up the tracing options.
865 ok &= setCategoriesEnableFromFile(g_categoriesFile);
866 ok &= setTraceOverwriteEnable(g_traceOverwrite);
867 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
868 // TODO: Re-enable after stabilization
869 //ok &= setCmdlineSize();
870 ok &= setClock();
871 ok &= setPrintTgidEnableIfPresent(true);
872 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
873
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800874 // Disable all the sysfs enables. This is done as a separate loop from
875 // the enables to allow the same enable to exist in multiple categories.
876 ok &= disableKernelTraceEvents();
877
878 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 14:55:31 -0700879 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800880 if (g_categoryEnables[i]) {
881 const TracingCategory &c = k_categories[i];
882 for (int j = 0; j < MAX_SYS_FILES; j++) {
883 const char* path = c.sysfiles[j].path;
884 bool required = c.sysfiles[j].required == REQ;
Yi Kong19d5c002018-07-20 13:39:55 -0700885 if (path != nullptr) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800886 if (fileIsWritable(path)) {
887 ok &= setKernelOptionEnable(path, true);
888 } else if (required) {
889 fprintf(stderr, "error writing file %s\n", path);
890 ok = false;
891 }
892 }
893 }
894 }
895 }
896
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800897 return ok;
898}
899
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700900// Reset all the kernel tracing settings to their default state.
Hector Dearman11845782018-03-08 14:35:44 +0000901static void cleanUpKernelTracing()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800902{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800903 // Disable all tracing that we're able to.
904 disableKernelTraceEvents();
905
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800906 // Set the options back to their defaults.
907 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700908 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700909 setPrintTgidEnableIfPresent(false);
Yi Kong19d5c002018-07-20 13:39:55 -0700910 setKernelTraceFuncs(nullptr);
Carmen Jacksonab1118e2018-05-22 10:29:47 -0700911 setUserInitiatedTraceProperty(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700912}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800913
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700914// Enable tracing in the kernel.
915static bool startTrace()
916{
917 return setTracingEnabled(true);
918}
919
920// Disable tracing in the kernel.
921static void stopTrace()
922{
923 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800924}
925
Martijn Coenend9535872015-11-26 10:00:55 +0100926// Read data from the tracing pipe and forward to stdout
927static void streamTrace()
928{
929 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800930 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 10:00:55 +0100931 if (traceFD == -1) {
932 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
933 strerror(errno), errno);
934 return;
935 }
936 while (!g_traceAborted) {
937 ssize_t bytes_read = read(traceFD, trace_data, 4096);
938 if (bytes_read > 0) {
939 write(STDOUT_FILENO, trace_data, bytes_read);
940 fflush(stdout);
941 } else {
942 if (!g_traceAborted) {
943 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
944 bytes_read, errno, strerror(errno));
945 }
946 break;
947 }
948 }
949}
950
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800951// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 09:44:36 -0700952static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800953{
John Reck6c8ac922016-03-28 11:25:30 -0700954 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 09:50:18 -0800955 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800956 if (traceFD == -1) {
957 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
958 strerror(errno), errno);
959 return;
960 }
961
962 if (g_compress) {
963 z_stream zs;
Elliott Hughes3da5d232015-01-25 08:35:20 -0800964 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700965
966 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800967 if (result != Z_OK) {
968 fprintf(stderr, "error initializing zlib: %d\n", result);
969 close(traceFD);
970 return;
971 }
972
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700973 constexpr size_t bufSize = 64*1024;
974 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
975 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
976 if (!in || !out) {
977 fprintf(stderr, "couldn't allocate buffers\n");
978 close(traceFD);
979 return;
980 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800981
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700982 int flush = Z_NO_FLUSH;
983
984 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800985 zs.avail_out = bufSize;
986
987 do {
988
989 if (zs.avail_in == 0) {
990 // More input is needed.
Elliott Hughesa252f4d2016-07-21 17:12:15 -0700991 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800992 if (result < 0) {
993 fprintf(stderr, "error reading trace: %s (%d)\n",
994 strerror(errno), errno);
995 result = Z_STREAM_END;
996 break;
997 } else if (result == 0) {
998 flush = Z_FINISH;
999 } else {
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001000 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001001 zs.avail_in = result;
1002 }
1003 }
1004
1005 if (zs.avail_out == 0) {
1006 // Need to write the output.
Elliott Hughesb59e2962016-07-22 09:00:59 -07001007 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001008 if ((size_t)result < bufSize) {
1009 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1010 strerror(errno), errno);
1011 result = Z_STREAM_END; // skip deflate error message
1012 zs.avail_out = bufSize; // skip the final write
1013 break;
1014 }
Elliott Hughesa252f4d2016-07-21 17:12:15 -07001015 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001016 zs.avail_out = bufSize;
1017 }
1018
1019 } while ((result = deflate(&zs, flush)) == Z_OK);
1020
1021 if (result != Z_STREAM_END) {
1022 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
1023 }
1024
1025 if (zs.avail_out < bufSize) {
1026 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 09:00:59 -07001027 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001028 if ((size_t)result < bytes) {
1029 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
1030 strerror(errno), errno);
1031 }
1032 }
1033
1034 result = deflateEnd(&zs);
1035 if (result != Z_OK) {
1036 fprintf(stderr, "error cleaning up zlib: %d\n", result);
1037 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001038 } else {
Josh Gaod3d36e72017-04-11 15:21:13 -07001039 char buf[4096];
1040 ssize_t rc;
1041 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
1042 if (!android::base::WriteFully(outFd, buf, rc)) {
1043 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
1044 break;
1045 }
1046 }
1047 if (rc == -1) {
1048 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001049 }
1050 }
1051
1052 close(traceFD);
1053}
1054
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001055static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001056{
1057 if (!g_nohup) {
1058 g_traceAborted = true;
1059 }
1060}
1061
1062static void registerSigHandler()
1063{
1064 struct sigaction sa;
1065 sigemptyset(&sa.sa_mask);
1066 sa.sa_flags = 0;
1067 sa.sa_handler = handleSignal;
Yi Kong19d5c002018-07-20 13:39:55 -07001068 sigaction(SIGHUP, &sa, nullptr);
1069 sigaction(SIGINT, &sa, nullptr);
1070 sigaction(SIGQUIT, &sa, nullptr);
1071 sigaction(SIGTERM, &sa, nullptr);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001072}
1073
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001074static void listSupportedCategories()
1075{
Elliott Hughes5fd6ff62017-03-28 14:55:31 -07001076 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001077 const TracingCategory& c = k_categories[i];
1078 if (isCategorySupported(c)) {
1079 printf(" %10s - %s\n", c.name, c.longname);
1080 }
1081 }
1082}
1083
1084// Print the command usage help to stderr.
1085static void showHelp(const char *cmd)
1086{
1087 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1088 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001089 " -a appname enable app-level tracing for a comma "
Daniel Colascione519a0792018-02-09 20:05:39 -08001090 "separated list of cmdlines; * is a wildcard matching any process\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001091 " -b N use a trace buffer size of N KB\n"
1092 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001093 " -f filename use the categories written in a file as space-separated\n"
1094 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001095 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001096 " -n ignore signals\n"
1097 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001098 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001099 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 11:40:12 -07001100 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001101 " --async_dump dump the current contents of circular trace buffer\n"
1102 " --async_stop stop tracing and dump the current contents of circular\n"
1103 " trace buffer\n"
Martijn Coenend9535872015-11-26 10:00:55 +01001104 " --stream stream trace to stdout as it enters the trace buffer\n"
1105 " Note: this can take significant CPU time, and is best\n"
1106 " used for measuring things that are not affected by\n"
1107 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-07 16:29:03 -08001108 " --list_categories\n"
1109 " list the available tracing categories\n"
John Reck40b26b42016-03-30 09:44:36 -07001110 " -o filename write the trace to the specified file instead\n"
1111 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001112 );
1113}
1114
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001115bool findTraceFiles()
1116{
1117 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1118 static const std::string tracefs_path = "/sys/kernel/tracing/";
1119 static const std::string trace_file = "trace_marker";
1120
1121 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1122 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1123
1124 if (!tracefs && !debugfs) {
1125 fprintf(stderr, "Error: Did not find trace folder\n");
1126 return false;
1127 }
1128
1129 if (tracefs) {
1130 g_traceFolder = tracefs_path;
1131 } else {
1132 g_traceFolder = debugfs_path;
1133 }
1134
1135 return true;
1136}
1137
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001138int main(int argc, char **argv)
1139{
1140 bool async = false;
1141 bool traceStart = true;
1142 bool traceStop = true;
1143 bool traceDump = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001144 bool traceStream = false;
Hector Dearman11845782018-03-08 14:35:44 +00001145 bool onlyUserspace = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001146
1147 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1148 showHelp(argv[0]);
1149 exit(0);
1150 }
1151
Paul Lawrence2cd93cc2017-01-17 09:50:18 -08001152 if (!findTraceFiles()) {
1153 fprintf(stderr, "No trace folder found\n");
1154 exit(-1);
1155 }
1156
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001157 for (;;) {
1158 int ret;
1159 int option_index = 0;
1160 static struct option long_options[] = {
Yi Kong19d5c002018-07-20 13:39:55 -07001161 {"async_start", no_argument, nullptr, 0 },
1162 {"async_stop", no_argument, nullptr, 0 },
1163 {"async_dump", no_argument, nullptr, 0 },
1164 {"only_userspace", no_argument, nullptr, 0 },
1165 {"list_categories", no_argument, nullptr, 0 },
1166 {"stream", no_argument, nullptr, 0 },
1167 {nullptr, 0, nullptr, 0 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001168 };
1169
John Reck40b26b42016-03-30 09:44:36 -07001170 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001171 long_options, &option_index);
1172
1173 if (ret < 0) {
1174 for (int i = optind; i < argc; i++) {
1175 if (!setCategoryEnable(argv[i], true)) {
1176 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1177 exit(1);
1178 }
1179 }
1180 break;
1181 }
1182
1183 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -07001184 case 'a':
1185 g_debugAppCmdLine = optarg;
1186 break;
1187
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001188 case 'b':
1189 g_traceBufferSizeKB = atoi(optarg);
1190 break;
1191
1192 case 'c':
1193 g_traceOverwrite = true;
1194 break;
1195
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +09001196 case 'f':
1197 g_categoriesFile = optarg;
1198 break;
1199
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001200 case 'k':
1201 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001202 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001203
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001204 case 'n':
1205 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001206 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001207
1208 case 's':
1209 g_initialSleepSecs = atoi(optarg);
1210 break;
1211
1212 case 't':
1213 g_traceDurationSeconds = atoi(optarg);
1214 break;
1215
1216 case 'z':
1217 g_compress = true;
1218 break;
1219
John Reck40b26b42016-03-30 09:44:36 -07001220 case 'o':
1221 g_outputFile = optarg;
1222 break;
1223
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001224 case 0:
1225 if (!strcmp(long_options[option_index].name, "async_start")) {
1226 async = true;
1227 traceStop = false;
1228 traceDump = false;
1229 g_traceOverwrite = true;
1230 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1231 async = true;
John Reck4ba2b632015-05-15 10:00:34 -07001232 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001233 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1234 async = true;
1235 traceStart = false;
1236 traceStop = false;
Hector Dearman11845782018-03-08 14:35:44 +00001237 } else if (!strcmp(long_options[option_index].name, "only_userspace")) {
1238 onlyUserspace = true;
Martijn Coenend9535872015-11-26 10:00:55 +01001239 } else if (!strcmp(long_options[option_index].name, "stream")) {
1240 traceStream = true;
1241 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001242 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1243 listSupportedCategories();
1244 exit(0);
1245 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -07001246 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001247
1248 default:
1249 fprintf(stderr, "\n");
1250 showHelp(argv[0]);
1251 exit(-1);
1252 break;
1253 }
1254 }
1255
Hector Dearman11845782018-03-08 14:35:44 +00001256 if (onlyUserspace) {
1257 if (!async || !(traceStart || traceStop)) {
1258 fprintf(stderr, "--only_userspace can only be used with "
1259 "--async_start or --async_stop\n");
1260 exit(1);
1261 }
1262 }
1263
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001264 registerSigHandler();
1265
1266 if (g_initialSleepSecs > 0) {
1267 sleep(g_initialSleepSecs);
1268 }
1269
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001270 bool ok = true;
Hector Dearman11845782018-03-08 14:35:44 +00001271
Wei Wang5b73b742018-03-08 13:33:12 -08001272 if (traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001273 ok &= setUpUserspaceTracing();
1274 }
1275
1276 if (ok && traceStart && !onlyUserspace) {
1277 ok &= setUpKernelTracing();
Wei Wang5b73b742018-03-08 13:33:12 -08001278 ok &= startTrace();
1279 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001280
1281 if (ok && traceStart) {
Hector Dearman11845782018-03-08 14:35:44 +00001282
1283 if (!traceStream && !onlyUserspace) {
Carmen Jacksonac53e732017-05-02 16:55:33 -07001284 printf("capturing trace...");
Martijn Coenend9535872015-11-26 10:00:55 +01001285 fflush(stdout);
1286 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001287
1288 // We clear the trace after starting it because tracing gets enabled for
1289 // each CPU individually in the kernel. Having the beginning of the trace
1290 // contain entries from only one CPU can cause "begin" entries without a
1291 // matching "end" entry to show up if a task gets migrated from one CPU to
1292 // another.
Hector Dearman11845782018-03-08 14:35:44 +00001293 if (!onlyUserspace)
1294 ok = clearTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001295
Martijn Coenen0bcd97a2015-07-15 14:25:23 +02001296 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 10:00:55 +01001297 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001298 // Sleep to allow the trace to be captured.
1299 struct timespec timeLeft;
1300 timeLeft.tv_sec = g_traceDurationSeconds;
1301 timeLeft.tv_nsec = 0;
1302 do {
1303 if (g_traceAborted) {
1304 break;
1305 }
1306 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1307 }
Martijn Coenend9535872015-11-26 10:00:55 +01001308
1309 if (traceStream) {
1310 streamTrace();
1311 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001312 }
1313
1314 // Stop the trace and restore the default settings.
Hector Dearman11845782018-03-08 14:35:44 +00001315 if (traceStop && !onlyUserspace)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001316 stopTrace();
1317
Hector Dearman11845782018-03-08 14:35:44 +00001318 if (ok && traceDump && !onlyUserspace) {
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001319 if (!g_traceAborted) {
John Reck40b26b42016-03-30 09:44:36 -07001320 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001321 fflush(stdout);
John Reck40b26b42016-03-30 09:44:36 -07001322 int outFd = STDOUT_FILENO;
1323 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 09:25:31 +01001324 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 09:44:36 -07001325 }
1326 if (outFd == -1) {
1327 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1328 } else {
1329 dprintf(outFd, "TRACE:\n");
1330 dumpTrace(outFd);
1331 if (g_outputFile) {
1332 close(outFd);
1333 }
1334 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001335 } else {
1336 printf("\ntrace aborted.\n");
1337 fflush(stdout);
1338 }
1339 clearTrace();
1340 } else if (!ok) {
1341 fprintf(stderr, "unable to start tracing\n");
1342 }
1343
1344 // Reset the trace buffer size to 1.
Hector Dearman11845782018-03-08 14:35:44 +00001345 if (traceStop) {
1346 cleanUpUserspaceTracing();
1347 if (!onlyUserspace)
1348 cleanUpKernelTracing();
1349 }
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001350
1351 return g_traceAborted ? 1 : 0;
1352}