blob: eff7c9204b4f21ff45c4dd0ce280911e4666488a [file] [log] [blame]
Jamie Gennis6eea6fb2012-12-07 22:03:071/*
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 17:50:1817#define LOG_TAG "atrace"
John Reck40b26b42016-03-30 16:44:3618
Jamie Gennis6eea6fb2012-12-07 22:03:0719#include <errno.h>
20#include <fcntl.h>
21#include <getopt.h>
Mark Salyzyn92dc3fc2014-03-12 20:12:4422#include <inttypes.h>
Jamie Gennis6eea6fb2012-12-07 22:03:0723#include <signal.h>
24#include <stdarg.h>
25#include <stdbool.h>
26#include <stdio.h>
27#include <stdlib.h>
Elliott Hughes3da5d232015-01-25 16:35:2028#include <string.h>
Jamie Gennis6eea6fb2012-12-07 22:03:0729#include <time.h>
Martijn Coenend9535872015-11-26 09:00:5530#include <unistd.h>
Jamie Gennis6eea6fb2012-12-07 22:03:0731#include <zlib.h>
32
Carmen Jacksonea826792017-05-05 18:42:3233#include <fstream>
Elliott Hughesa252f4d2016-07-22 00:12:1534#include <memory>
35
Jamie Gennis6eea6fb2012-12-07 22:03:0736#include <binder/IBinder.h>
37#include <binder/IServiceManager.h>
38#include <binder/Parcel.h>
39
Martijn Coenenee9b97e2016-11-16 15:00:2640#include <android/hidl/manager/1.0/IServiceManager.h>
41#include <hidl/ServiceManagement.h>
Jamie Gennis6eea6fb2012-12-07 22:03:0742
43#include <utils/String8.h>
John Reck469a1942015-03-26 22:31:3544#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 10:20:3945#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 22:03:0746#include <utils/Trace.h>
Stephane Gasparinid8419c22016-03-02 12:45:1547#include <android-base/file.h>
Elliott Hughes5fd6ff62017-03-28 21:55:3148#include <android-base/macros.h>
49#include <android-base/properties.h>
50#include <android-base/stringprintf.h>
Jamie Gennis6eea6fb2012-12-07 22:03:0751
52using namespace android;
53
Martijn Coenenee9b97e2016-11-16 15:00:2654using std::string;
Jamie Gennis6eea6fb2012-12-07 22:03:0755
sergeyv4144eff2016-04-28 18:40:0456#define MAX_SYS_FILES 10
57#define MAX_PACKAGES 16
Jamie Gennis6eea6fb2012-12-07 22:03:0758
59const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
sergeyv4144eff2016-04-28 18:40:0460
61const char* k_traceAppsNumberProperty = "debug.atrace.app_number";
62const char* k_traceAppsPropertyTemplate = "debug.atrace.app_%d";
sergeyvdb404152016-05-03 02:26:0763const char* k_coreServiceCategory = "core_services";
64const char* k_coreServicesProp = "ro.atrace.core.services";
Jamie Gennis6eea6fb2012-12-07 22:03:0765
66typedef enum { OPT, REQ } requiredness ;
67
68struct TracingCategory {
69 // The name identifying the category.
70 const char* name;
71
72 // A longer description of the category.
73 const char* longname;
74
75 // The userland tracing tags that the category enables.
76 uint64_t tags;
77
78 // The fname==NULL terminated list of /sys/ files that the category
79 // enables.
80 struct {
81 // Whether the file must be writable in order to enable the tracing
82 // category.
83 requiredness required;
84
85 // The path to the enable file.
86 const char* path;
87 } sysfiles[MAX_SYS_FILES];
88};
89
90/* Tracing categories */
91static const TracingCategory k_categories[] = {
John Reck732a29a2017-05-24 23:09:2192 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, {
93 { OPT, "events/mdss/enable" },
94 } },
Jamie Gennisb2a89e32013-03-12 02:37:5395 { "input", "Input", ATRACE_TAG_INPUT, { } },
96 { "view", "View System", ATRACE_TAG_VIEW, { } },
97 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
98 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
99 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 20:38:30100 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-12 02:37:53101 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
102 { "video", "Video", ATRACE_TAG_VIDEO, { } },
103 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
104 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Jeff Brown3200b0b2014-08-15 02:24:47105 { "app", "Application", ATRACE_TAG_APP, { } },
Dianne Hackborn9380d782013-04-12 21:52:35106 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 22:20:39107 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 21:39:42108 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 21:23:24109 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-15 02:24:47110 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 21:36:20111 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-06-30 16:46:25112 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Greg Hackmannbbd7d992014-12-01 22:43:34113 { "database", "Database", ATRACE_TAG_DATABASE, { } },
Felipe Leme0f97c1d2016-09-07 18:33:26114 { "network", "Network", ATRACE_TAG_NETWORK, { } },
Josh Gao468b4cb2016-11-29 18:55:21115 { "adb", "ADB", ATRACE_TAG_ADB, { } },
sergeyvdb404152016-05-03 02:26:07116 { k_coreServiceCategory, "Core services", 0, { } },
Jamie Gennisb2a89e32013-03-12 02:37:53117 { "sched", "CPU Scheduling", 0, {
Paul Lawrence2cd93cc2017-01-17 17:50:18118 { REQ, "events/sched/sched_switch/enable" },
119 { REQ, "events/sched/sched_wakeup/enable" },
120 { OPT, "events/sched/sched_blocked_reason/enable" },
121 { OPT, "events/sched/sched_cpu_hotplug/enable" },
Jamie Gennis6eea6fb2012-12-07 22:03:07122 } },
Dan Willemsenf440d392014-04-11 22:44:09123 { "irq", "IRQ Events", 0, {
Paul Lawrence2cd93cc2017-01-17 17:50:18124 { REQ, "events/irq/enable" },
125 { OPT, "events/ipi/enable" },
Dan Willemsenf440d392014-04-11 22:44:09126 } },
Michael Wright43fb6782016-08-18 18:56:43127 { "i2c", "I2C Events", 0, {
Paul Lawrence2cd93cc2017-01-17 17:50:18128 { REQ, "events/i2c/enable" },
129 { REQ, "events/i2c/i2c_read/enable" },
130 { REQ, "events/i2c/i2c_write/enable" },
131 { REQ, "events/i2c/i2c_result/enable" },
132 { REQ, "events/i2c/i2c_reply/enable" },
133 { OPT, "events/i2c/smbus_read/enable" },
134 { OPT, "events/i2c/smbus_write/enable" },
135 { OPT, "events/i2c/smbus_result/enable" },
136 { OPT, "events/i2c/smbus_reply/enable" },
Michael Wright43fb6782016-08-18 18:56:43137 } },
Jamie Gennisb2a89e32013-03-12 02:37:53138 { "freq", "CPU Frequency", 0, {
Paul Lawrence2cd93cc2017-01-17 17:50:18139 { REQ, "events/power/cpu_frequency/enable" },
140 { OPT, "events/power/clock_set_rate/enable" },
141 { OPT, "events/power/cpu_frequency_limits/enable" },
Jamie Gennis6eea6fb2012-12-07 22:03:07142 } },
Jamie Gennisb2a89e32013-03-12 02:37:53143 { "membus", "Memory Bus Utilization", 0, {
Paul Lawrence2cd93cc2017-01-17 17:50:18144 { REQ, "events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 22:03:07145 } },
Jamie Gennisb2a89e32013-03-12 02:37:53146 { "idle", "CPU Idle", 0, {
Paul Lawrence2cd93cc2017-01-17 17:50:18147 { REQ, "events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 22:03:07148 } },
Jamie Gennisb2a89e32013-03-12 02:37:53149 { "disk", "Disk I/O", 0, {
Paul Lawrence2cd93cc2017-01-17 17:50:18150 { OPT, "events/f2fs/f2fs_sync_file_enter/enable" },
151 { OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
152 { OPT, "events/f2fs/f2fs_write_begin/enable" },
153 { OPT, "events/f2fs/f2fs_write_end/enable" },
154 { OPT, "events/ext4/ext4_da_write_begin/enable" },
155 { OPT, "events/ext4/ext4_da_write_end/enable" },
156 { OPT, "events/ext4/ext4_sync_file_enter/enable" },
157 { OPT, "events/ext4/ext4_sync_file_exit/enable" },
158 { REQ, "events/block/block_rq_issue/enable" },
159 { REQ, "events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 22:03:07160 } },
Ken Sumralld3fa5612013-07-03 19:32:03161 { "mmc", "eMMC commands", 0, {
Paul Lawrence2cd93cc2017-01-17 17:50:18162 { REQ, "events/mmc/enable" },
Ken Sumralld3fa5612013-07-03 19:32:03163 } },
Jamie Gennisb2a89e32013-03-12 02:37:53164 { "load", "CPU Load", 0, {
Paul Lawrence2cd93cc2017-01-17 17:50:18165 { REQ, "events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 22:03:07166 } },
Jamie Gennisb2a89e32013-03-12 02:37:53167 { "sync", "Synchronization", 0, {
Paul Lawrence2cd93cc2017-01-17 17:50:18168 { REQ, "events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 22:03:07169 } },
Jamie Gennisb2a89e32013-03-12 02:37:53170 { "workq", "Kernel Workqueues", 0, {
Paul Lawrence2cd93cc2017-01-17 17:50:18171 { REQ, "events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 22:03:07172 } },
Colin Cross580407f2014-08-18 22:22:13173 { "memreclaim", "Kernel Memory Reclaim", 0, {
Paul Lawrence2cd93cc2017-01-17 17:50:18174 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
175 { REQ, "events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
176 { REQ, "events/vmscan/mm_vmscan_kswapd_wake/enable" },
177 { REQ, "events/vmscan/mm_vmscan_kswapd_sleep/enable" },
Marc Hittingerf1f62e32017-05-17 22:57:43178 { REQ, "events/lowmemorykiller/enable" },
Colin Cross580407f2014-08-18 22:22:13179 } },
Aaron Schulmanc2c6ecd2015-02-25 16:37:09180 { "regulators", "Voltage and Current Regulators", 0, {
Paul Lawrence2cd93cc2017-01-17 17:50:18181 { REQ, "events/regulator/enable" },
Aaron Schulmanc2c6ecd2015-02-25 16:37:09182 } },
Scott Bauerae473362015-06-08 23:32:36183 { "binder_driver", "Binder Kernel driver", 0, {
Paul Lawrence2cd93cc2017-01-17 17:50:18184 { REQ, "events/binder/binder_transaction/enable" },
185 { REQ, "events/binder/binder_transaction_received/enable" },
Scott Bauerae473362015-06-08 23:32:36186 } },
187 { "binder_lock", "Binder global lock trace", 0, {
Howard Cheneb8acbf2017-05-10 08:32:11188 { OPT, "events/binder/binder_lock/enable" },
189 { OPT, "events/binder/binder_locked/enable" },
190 { OPT, "events/binder/binder_unlock/enable" },
Scott Bauerae473362015-06-08 23:32:36191 } },
Martijn Coenen70481612015-10-23 11:57:05192 { "pagecache", "Page cache", 0, {
Paul Lawrence2cd93cc2017-01-17 17:50:18193 { REQ, "events/filemap/enable" },
Martijn Coenen70481612015-10-23 11:57:05194 } },
Jamie Gennis6eea6fb2012-12-07 22:03:07195};
196
197/* Command line options */
198static int g_traceDurationSeconds = 5;
199static bool g_traceOverwrite = false;
200static int g_traceBufferSizeKB = 2048;
201static bool g_compress = false;
202static bool g_nohup = false;
203static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 10:20:39204static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 23:00:10205static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 22:50:58206static const char* g_debugAppCmdLine = "";
John Reck40b26b42016-03-30 16:44:36207static const char* g_outputFile = nullptr;
Jamie Gennis6eea6fb2012-12-07 22:03:07208
209/* Global state */
210static bool g_traceAborted = false;
Elliott Hughes5fd6ff62017-03-28 21:55:31211static bool g_categoryEnables[arraysize(k_categories)] = {};
Paul Lawrence2cd93cc2017-01-17 17:50:18212static std::string g_traceFolder;
Jamie Gennis6eea6fb2012-12-07 22:03:07213
214/* Sys file paths */
215static const char* k_traceClockPath =
Paul Lawrence2cd93cc2017-01-17 17:50:18216 "trace_clock";
Jamie Gennis6eea6fb2012-12-07 22:03:07217
218static const char* k_traceBufferSizePath =
Paul Lawrence2cd93cc2017-01-17 17:50:18219 "buffer_size_kb";
Jamie Gennis6eea6fb2012-12-07 22:03:07220
Joel Fernandesed80bd02017-06-02 17:19:28221static const char* k_traceCmdlineSizePath =
222 "saved_cmdlines_size";
223
Jamie Gennis6eea6fb2012-12-07 22:03:07224static const char* k_tracingOverwriteEnablePath =
Paul Lawrence2cd93cc2017-01-17 17:50:18225 "options/overwrite";
Jamie Gennis6eea6fb2012-12-07 22:03:07226
Jamie Gennise9b8cfb2013-03-12 23:00:10227static const char* k_currentTracerPath =
Paul Lawrence2cd93cc2017-01-17 17:50:18228 "current_tracer";
Jamie Gennise9b8cfb2013-03-12 23:00:10229
230static const char* k_printTgidPath =
Paul Lawrence2cd93cc2017-01-17 17:50:18231 "options/print-tgid";
Jamie Gennise9b8cfb2013-03-12 23:00:10232
233static const char* k_funcgraphAbsTimePath =
Paul Lawrence2cd93cc2017-01-17 17:50:18234 "options/funcgraph-abstime";
Jamie Gennise9b8cfb2013-03-12 23:00:10235
236static const char* k_funcgraphCpuPath =
Paul Lawrence2cd93cc2017-01-17 17:50:18237 "options/funcgraph-cpu";
Jamie Gennise9b8cfb2013-03-12 23:00:10238
239static const char* k_funcgraphProcPath =
Paul Lawrence2cd93cc2017-01-17 17:50:18240 "options/funcgraph-proc";
Jamie Gennise9b8cfb2013-03-12 23:00:10241
242static const char* k_funcgraphFlatPath =
Paul Lawrence2cd93cc2017-01-17 17:50:18243 "options/funcgraph-flat";
Jamie Gennise9b8cfb2013-03-12 23:00:10244
245static const char* k_funcgraphDurationPath =
Paul Lawrence2cd93cc2017-01-17 17:50:18246 "options/funcgraph-duration";
Jamie Gennise9b8cfb2013-03-12 23:00:10247
248static const char* k_ftraceFilterPath =
Paul Lawrence2cd93cc2017-01-17 17:50:18249 "set_ftrace_filter";
Jamie Gennise9b8cfb2013-03-12 23:00:10250
Jamie Gennis6eea6fb2012-12-07 22:03:07251static const char* k_tracingOnPath =
Paul Lawrence2cd93cc2017-01-17 17:50:18252 "tracing_on";
Jamie Gennis6eea6fb2012-12-07 22:03:07253
254static const char* k_tracePath =
Paul Lawrence2cd93cc2017-01-17 17:50:18255 "trace";
Jamie Gennis6eea6fb2012-12-07 22:03:07256
Martijn Coenend9535872015-11-26 09:00:55257static const char* k_traceStreamPath =
Paul Lawrence2cd93cc2017-01-17 17:50:18258 "trace_pipe";
Martijn Coenend9535872015-11-26 09:00:55259
John Reck469a1942015-03-26 22:31:35260static const char* k_traceMarkerPath =
Paul Lawrence2cd93cc2017-01-17 17:50:18261 "trace_marker";
John Reck469a1942015-03-26 22:31:35262
Jamie Gennis6eea6fb2012-12-07 22:03:07263// Check whether a file exists.
264static bool fileExists(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 17:50:18265 return access((g_traceFolder + filename).c_str(), F_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 22:03:07266}
267
268// Check whether a file is writable.
269static bool fileIsWritable(const char* filename) {
Paul Lawrence2cd93cc2017-01-17 17:50:18270 return access((g_traceFolder + filename).c_str(), W_OK) != -1;
Jamie Gennis6eea6fb2012-12-07 22:03:07271}
272
Jamie Gennise9b8cfb2013-03-12 23:00:10273// Truncate a file.
274static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 22:03:07275{
Jamie Gennis43122e72013-03-21 21:06:31276 // This uses creat rather than truncate because some of the debug kernel
277 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
278 // calls to truncate, but they are cleared by calls to creat.
Paul Lawrence2cd93cc2017-01-17 17:50:18279 int traceFD = creat((g_traceFolder + path).c_str(), 0);
Jamie Gennis43122e72013-03-21 21:06:31280 if (traceFD == -1) {
Paul Lawrence2cd93cc2017-01-17 17:50:18281 fprintf(stderr, "error truncating %s: %s (%d)\n", (g_traceFolder + path).c_str(),
Jamie Gennis43122e72013-03-21 21:06:31282 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 23:00:10283 return false;
284 }
285
Jamie Gennis43122e72013-03-21 21:06:31286 close(traceFD);
287
Jamie Gennise9b8cfb2013-03-12 23:00:10288 return true;
289}
290
291static bool _writeStr(const char* filename, const char* str, int flags)
292{
Paul Lawrence2cd93cc2017-01-17 17:50:18293 std::string fullFilename = g_traceFolder + filename;
294 int fd = open(fullFilename.c_str(), flags);
Jamie Gennis6eea6fb2012-12-07 22:03:07295 if (fd == -1) {
Paul Lawrence2cd93cc2017-01-17 17:50:18296 fprintf(stderr, "error opening %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 22:03:07297 strerror(errno), errno);
298 return false;
299 }
300
301 bool ok = true;
302 ssize_t len = strlen(str);
303 if (write(fd, str, len) != len) {
Paul Lawrence2cd93cc2017-01-17 17:50:18304 fprintf(stderr, "error writing to %s: %s (%d)\n", fullFilename.c_str(),
Jamie Gennis6eea6fb2012-12-07 22:03:07305 strerror(errno), errno);
306 ok = false;
307 }
308
309 close(fd);
310
311 return ok;
312}
313
Jamie Gennise9b8cfb2013-03-12 23:00:10314// Write a string to a file, returning true if the write was successful.
315static bool writeStr(const char* filename, const char* str)
316{
317 return _writeStr(filename, str, O_WRONLY);
318}
319
320// Append a string to a file, returning true if the write was successful.
321static bool appendStr(const char* filename, const char* str)
322{
323 return _writeStr(filename, str, O_APPEND|O_WRONLY);
324}
325
John Reck469a1942015-03-26 22:31:35326static void writeClockSyncMarker()
327{
328 char buffer[128];
Martijn Coenen0bcd97a2015-07-15 12:25:23329 int len = 0;
Paul Lawrence2cd93cc2017-01-17 17:50:18330 int fd = open((g_traceFolder + k_traceMarkerPath).c_str(), O_WRONLY);
Martijn Coenen0bcd97a2015-07-15 12:25:23331 if (fd == -1) {
332 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceMarkerPath,
333 strerror(errno), errno);
334 return;
335 }
John Reck469a1942015-03-26 22:31:35336 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
Martijn Coenen0bcd97a2015-07-15 12:25:23337
338 len = snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
339 if (write(fd, buffer, len) != len) {
340 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
341 }
342
343 int64_t realtime_in_ms = systemTime(CLOCK_REALTIME) / 1000000;
344 len = snprintf(buffer, 128, "trace_event_clock_sync: realtime_ts=%" PRId64 "\n", realtime_in_ms);
345 if (write(fd, buffer, len) != len) {
346 fprintf(stderr, "error writing clock sync marker %s (%d)\n", strerror(errno), errno);
347 }
348
349 close(fd);
John Reck469a1942015-03-26 22:31:35350}
351
Jamie Gennis6eea6fb2012-12-07 22:03:07352// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
353// file.
354static bool setKernelOptionEnable(const char* filename, bool enable)
355{
356 return writeStr(filename, enable ? "1" : "0");
357}
358
359// Check whether the category is supported on the device with the current
360// rootness. A category is supported only if all its required /sys/ files are
361// writable and if enabling the category will enable one or more tracing tags
362// or /sys/ files.
363static bool isCategorySupported(const TracingCategory& category)
364{
sergeyvdb404152016-05-03 02:26:07365 if (strcmp(category.name, k_coreServiceCategory) == 0) {
Elliott Hughes5fd6ff62017-03-28 21:55:31366 return !android::base::GetProperty(k_coreServicesProp, "").empty();
sergeyvdb404152016-05-03 02:26:07367 }
368
Jamie Gennis6eea6fb2012-12-07 22:03:07369 bool ok = category.tags != 0;
370 for (int i = 0; i < MAX_SYS_FILES; i++) {
371 const char* path = category.sysfiles[i].path;
372 bool req = category.sysfiles[i].required == REQ;
373 if (path != NULL) {
374 if (req) {
375 if (!fileIsWritable(path)) {
376 return false;
377 } else {
378 ok = true;
379 }
380 } else {
Howard Cheneb8acbf2017-05-10 08:32:11381 ok = true;
Jamie Gennis6eea6fb2012-12-07 22:03:07382 }
383 }
384 }
385 return ok;
386}
387
388// Check whether the category would be supported on the device if the user
389// were root. This function assumes that root is able to write to any file
390// that exists. It performs the same logic as isCategorySupported, but it
Fabien Sanglardb5c95472016-06-08 18:40:12391// uses file existence rather than writability in the /sys/ file checks.
Jamie Gennis6eea6fb2012-12-07 22:03:07392static bool isCategorySupportedForRoot(const TracingCategory& category)
393{
394 bool ok = category.tags != 0;
395 for (int i = 0; i < MAX_SYS_FILES; i++) {
396 const char* path = category.sysfiles[i].path;
397 bool req = category.sysfiles[i].required == REQ;
398 if (path != NULL) {
399 if (req) {
400 if (!fileExists(path)) {
401 return false;
402 } else {
403 ok = true;
404 }
405 } else {
406 ok |= fileExists(path);
407 }
408 }
409 }
410 return ok;
411}
412
413// Enable or disable overwriting of the kernel trace buffers. Disabling this
414// will cause tracing to stop once the trace buffers have filled up.
415static bool setTraceOverwriteEnable(bool enable)
416{
417 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
418}
419
420// Enable or disable kernel tracing.
421static bool setTracingEnabled(bool enable)
422{
423 return setKernelOptionEnable(k_tracingOnPath, enable);
424}
425
426// Clear the contents of the kernel trace.
427static bool clearTrace()
428{
Jamie Gennise9b8cfb2013-03-12 23:00:10429 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 22:03:07430}
431
432// Set the size of the kernel's trace buffer in kilobytes.
433static bool setTraceBufferSizeKB(int size)
434{
435 char str[32] = "1";
436 int len;
437 if (size < 1) {
438 size = 1;
439 }
440 snprintf(str, 32, "%d", size);
441 return writeStr(k_traceBufferSizePath, str);
442}
443
Joel Fernandesed80bd02017-06-02 17:19:28444// Set the default size of cmdline hashtable
445static bool setCmdlineSize()
446{
447 return writeStr(k_traceCmdlineSizePath, "8192");
448}
449
Carmen Jacksonea826792017-05-05 18:42:32450// Set the clock to the best available option while tracing. Use 'boot' if it's
451// available; otherwise, use 'mono'. If neither are available use 'global'.
Colin Crossb1ce49b2014-08-20 21:28:47452// Any write to the trace_clock sysfs file will reset the buffer, so only
453// update it if the requested value is not the current value.
Carmen Jacksonea826792017-05-05 18:42:32454static bool setClock()
Jamie Gennis6eea6fb2012-12-07 22:03:07455{
Carmen Jacksonea826792017-05-05 18:42:32456 std::ifstream clockFile((g_traceFolder + k_traceClockPath).c_str(), O_RDONLY);
457 std::string clockStr((std::istreambuf_iterator<char>(clockFile)),
458 std::istreambuf_iterator<char>());
Colin Crossb1ce49b2014-08-20 21:28:47459
Carmen Jacksonea826792017-05-05 18:42:32460 std::string newClock;
461 if (clockStr.find("boot") != std::string::npos) {
462 newClock = "boot";
463 } else if (clockStr.find("mono") != std::string::npos) {
464 newClock = "mono";
465 } else {
466 newClock = "global";
Colin Crossb1ce49b2014-08-20 21:28:47467 }
468
Carmen Jacksonea826792017-05-05 18:42:32469 size_t begin = clockStr.find("[") + 1;
470 size_t end = clockStr.find("]");
471 if (newClock.compare(0, std::string::npos, clockStr, begin, end-begin) == 0) {
472 return true;
473 }
474 return writeStr(k_traceClockPath, newClock.c_str());
Jamie Gennis6eea6fb2012-12-07 22:03:07475}
476
Jamie Gennise9b8cfb2013-03-12 23:00:10477static bool setPrintTgidEnableIfPresent(bool enable)
478{
479 if (fileExists(k_printTgidPath)) {
480 return setKernelOptionEnable(k_printTgidPath, enable);
481 }
482 return true;
483}
484
Jamie Gennis6eea6fb2012-12-07 22:03:07485// Poke all the binder-enabled processes in the system to get them to re-read
486// their system properties.
487static bool pokeBinderServices()
488{
489 sp<IServiceManager> sm = defaultServiceManager();
490 Vector<String16> services = sm->listServices();
491 for (size_t i = 0; i < services.size(); i++) {
492 sp<IBinder> obj = sm->checkService(services[i]);
493 if (obj != NULL) {
494 Parcel data;
495 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
496 NULL, 0) != OK) {
497 if (false) {
498 // XXX: For some reason this fails on tablets trying to
499 // poke the "phone" service. It's not clear whether some
500 // are expected to fail.
501 String8 svc(services[i]);
502 fprintf(stderr, "error poking binder service %s\n",
503 svc.string());
504 return false;
505 }
506 }
507 }
508 }
509 return true;
510}
511
Martijn Coenenee9b97e2016-11-16 15:00:26512// Poke all the HAL processes in the system to get them to re-read
513// their system properties.
514static void pokeHalServices()
515{
Martijn Coenenf6ac8482017-01-02 14:17:11516 using ::android::hidl::base::V1_0::IBase;
Martijn Coenenee9b97e2016-11-16 15:00:26517 using ::android::hidl::manager::V1_0::IServiceManager;
Martijn Coenenee9b97e2016-11-16 15:00:26518 using ::android::hardware::hidl_string;
Martijn Coenenf6ac8482017-01-02 14:17:11519 using ::android::hardware::Return;
Martijn Coenenee9b97e2016-11-16 15:00:26520
521 sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
Steven Morelanda42866b2016-12-12 23:18:06522
523 if (sm == nullptr) {
524 fprintf(stderr, "failed to get IServiceManager to poke hal services\n");
525 return;
526 }
527
Yifan Hong8cf4ed12016-12-01 01:28:58528 auto listRet = sm->list([&](const auto &interfaces) {
Martijn Coenenee9b97e2016-11-16 15:00:26529 for (size_t i = 0; i < interfaces.size(); i++) {
530 string fqInstanceName = interfaces[i];
531 string::size_type n = fqInstanceName.find("/");
532 if (n == std::string::npos || interfaces[i].size() == n+1)
533 continue;
534 hidl_string fqInterfaceName = fqInstanceName.substr(0, n);
535 hidl_string instanceName = fqInstanceName.substr(n+1, std::string::npos);
Martijn Coenenf6ac8482017-01-02 14:17:11536 Return<sp<IBase>> interfaceRet = sm->get(fqInterfaceName, instanceName);
537 if (!interfaceRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 13:57:38538 // ignore
Martijn Coenenf6ac8482017-01-02 14:17:11539 continue;
540 }
Carmen Jackson73206122017-04-18 22:37:57541
Martijn Coenenf6ac8482017-01-02 14:17:11542 sp<IBase> interface = interfaceRet;
Carmen Jackson73206122017-04-18 22:37:57543 if (interface == nullptr) {
544 // ignore
545 continue;
546 }
547
Martijn Coenenf6ac8482017-01-02 14:17:11548 auto notifyRet = interface->notifySyspropsChanged();
549 if (!notifyRet.isOk()) {
Martijn Coenen1e4a7fb2017-02-17 13:57:38550 // ignore
Yifan Hong8cf4ed12016-12-01 01:28:58551 }
Martijn Coenenee9b97e2016-11-16 15:00:26552 }
553 });
Yifan Hong8cf4ed12016-12-01 01:28:58554 if (!listRet.isOk()) {
Martijn Coenen64d54eb2017-01-12 16:16:31555 // TODO(b/34242478) fix this when we determine the correct ACL
556 //fprintf(stderr, "failed to list services: %s\n", listRet.description().c_str());
Yifan Hong8cf4ed12016-12-01 01:28:58557 }
Martijn Coenenee9b97e2016-11-16 15:00:26558}
559
Jamie Gennis6eea6fb2012-12-07 22:03:07560// Set the trace tags that userland tracing uses, and poke the running
561// processes to pick up the new value.
562static bool setTagsProperty(uint64_t tags)
563{
Elliott Hughes5fd6ff62017-03-28 21:55:31564 std::string value = android::base::StringPrintf("%#" PRIx64, tags);
565 if (!android::base::SetProperty(k_traceTagsProperty, value)) {
Jamie Gennis6eea6fb2012-12-07 22:03:07566 fprintf(stderr, "error setting trace tags system property\n");
567 return false;
568 }
Jamie Gennisf7f29c82013-03-27 22:50:58569 return true;
570}
571
sergeyv4144eff2016-04-28 18:40:04572static void clearAppProperties()
573{
sergeyv4144eff2016-04-28 18:40:04574 for (int i = 0; i < MAX_PACKAGES; i++) {
Elliott Hughes5fd6ff62017-03-28 21:55:31575 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
576 if (!android::base::SetProperty(key, "")) {
577 fprintf(stderr, "failed to clear system property: %s\n", key.c_str());
sergeyv4144eff2016-04-28 18:40:04578 }
579 }
Elliott Hughes5fd6ff62017-03-28 21:55:31580 if (!android::base::SetProperty(k_traceAppsNumberProperty, "")) {
sergeyv4144eff2016-04-28 18:40:04581 fprintf(stderr, "failed to clear system property: %s",
582 k_traceAppsNumberProperty);
583 }
584}
585
Jamie Gennisf7f29c82013-03-27 22:50:58586// Set the system property that indicates which apps should perform
587// application-level tracing.
Dan Austin09a79872016-05-31 20:27:03588static bool setAppCmdlineProperty(char* cmdline)
Jamie Gennisf7f29c82013-03-27 22:50:58589{
sergeyv4144eff2016-04-28 18:40:04590 int i = 0;
Dan Austin09a79872016-05-31 20:27:03591 char* start = cmdline;
sergeyv4144eff2016-04-28 18:40:04592 while (start != NULL) {
593 if (i == MAX_PACKAGES) {
594 fprintf(stderr, "error: only 16 packages could be traced at once\n");
595 clearAppProperties();
596 return false;
597 }
598 char* end = strchr(start, ',');
599 if (end != NULL) {
600 *end = '\0';
601 end++;
602 }
Elliott Hughes5fd6ff62017-03-28 21:55:31603 std::string key = android::base::StringPrintf(k_traceAppsPropertyTemplate, i);
604 if (!android::base::SetProperty(key, start)) {
605 fprintf(stderr, "error setting trace app %d property to %s\n", i, key.c_str());
sergeyv4144eff2016-04-28 18:40:04606 clearAppProperties();
607 return false;
608 }
609 start = end;
610 i++;
611 }
612
Elliott Hughes5fd6ff62017-03-28 21:55:31613 std::string value = android::base::StringPrintf("%d", i);
614 if (!android::base::SetProperty(k_traceAppsNumberProperty, value)) {
615 fprintf(stderr, "error setting trace app number property to %s\n", value.c_str());
sergeyv4144eff2016-04-28 18:40:04616 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 22:50:58617 return false;
618 }
619 return true;
Jamie Gennis6eea6fb2012-12-07 22:03:07620}
621
622// Disable all /sys/ enable files.
623static bool disableKernelTraceEvents() {
624 bool ok = true;
Elliott Hughes5fd6ff62017-03-28 21:55:31625 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 22:03:07626 const TracingCategory &c = k_categories[i];
627 for (int j = 0; j < MAX_SYS_FILES; j++) {
628 const char* path = c.sysfiles[j].path;
629 if (path != NULL && fileIsWritable(path)) {
630 ok &= setKernelOptionEnable(path, false);
631 }
632 }
633 }
634 return ok;
635}
636
Jamie Gennise9b8cfb2013-03-12 23:00:10637// Verify that the comma separated list of functions are being traced by the
638// kernel.
639static bool verifyKernelTraceFuncs(const char* funcs)
640{
Stephane Gasparinid8419c22016-03-02 12:45:15641 std::string buf;
Paul Lawrence2cd93cc2017-01-17 17:50:18642 if (!android::base::ReadFileToString(g_traceFolder + k_ftraceFilterPath, &buf)) {
Stephane Gasparinid8419c22016-03-02 12:45:15643 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
Jamie Gennise9b8cfb2013-03-12 23:00:10644 strerror(errno), errno);
Stephane Gasparinid8419c22016-03-02 12:45:15645 return false;
Jamie Gennise9b8cfb2013-03-12 23:00:10646 }
647
Stephane Gasparinid8419c22016-03-02 12:45:15648 String8 funcList = String8::format("\n%s",buf.c_str());
Jamie Gennise9b8cfb2013-03-12 23:00:10649
650 // Make sure that every function listed in funcs is in the list we just
Thomas Buhota2c22872016-01-27 08:44:31651 // read from the kernel, except for wildcard inputs.
Jamie Gennise9b8cfb2013-03-12 23:00:10652 bool ok = true;
653 char* myFuncs = strdup(funcs);
654 char* func = strtok(myFuncs, ",");
655 while (func) {
Thomas Buhota2c22872016-01-27 08:44:31656 if (!strchr(func, '*')) {
657 String8 fancyFunc = String8::format("\n%s\n", func);
658 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
659 if (!found || func[0] == '\0') {
660 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
661 "to trace.\n", func);
662 ok = false;
663 }
Jamie Gennise9b8cfb2013-03-12 23:00:10664 }
665 func = strtok(NULL, ",");
666 }
667 free(myFuncs);
Jamie Gennise9b8cfb2013-03-12 23:00:10668 return ok;
669}
670
671// Set the comma separated list of functions that the kernel is to trace.
672static bool setKernelTraceFuncs(const char* funcs)
673{
674 bool ok = true;
675
676 if (funcs == NULL || funcs[0] == '\0') {
677 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 22:50:30678 if (fileIsWritable(k_currentTracerPath)) {
679 ok &= writeStr(k_currentTracerPath, "nop");
680 }
681 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 23:00:10682 ok &= truncateFile(k_ftraceFilterPath);
683 }
684 } else {
685 // Enable kernel function tracing.
686 ok &= writeStr(k_currentTracerPath, "function_graph");
687 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
688 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
689 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
690 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
691
692 // Set the requested filter functions.
693 ok &= truncateFile(k_ftraceFilterPath);
694 char* myFuncs = strdup(funcs);
695 char* func = strtok(myFuncs, ",");
696 while (func) {
697 ok &= appendStr(k_ftraceFilterPath, func);
698 func = strtok(NULL, ",");
699 }
700 free(myFuncs);
701
702 // Verify that the set functions are being traced.
703 if (ok) {
704 ok &= verifyKernelTraceFuncs(funcs);
705 }
706 }
707
708 return ok;
709}
710
Yasuhiro Matsuda46c51fb2015-06-29 10:20:39711static bool setCategoryEnable(const char* name, bool enable)
712{
Elliott Hughes5fd6ff62017-03-28 21:55:31713 for (size_t i = 0; i < arraysize(k_categories); i++) {
Yasuhiro Matsuda46c51fb2015-06-29 10:20:39714 const TracingCategory& c = k_categories[i];
715 if (strcmp(name, c.name) == 0) {
716 if (isCategorySupported(c)) {
717 g_categoryEnables[i] = enable;
718 return true;
719 } else {
720 if (isCategorySupportedForRoot(c)) {
721 fprintf(stderr, "error: category \"%s\" requires root "
722 "privileges.\n", name);
723 } else {
724 fprintf(stderr, "error: category \"%s\" is not supported "
725 "on this device.\n", name);
726 }
727 return false;
728 }
729 }
730 }
731 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
732 return false;
733}
734
735static bool setCategoriesEnableFromFile(const char* categories_file)
736{
737 if (!categories_file) {
738 return true;
739 }
740 Tokenizer* tokenizer = NULL;
741 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
742 return false;
743 }
744 bool ok = true;
745 while (!tokenizer->isEol()) {
746 String8 token = tokenizer->nextToken(" ");
747 if (token.isEmpty()) {
748 tokenizer->skipDelimiters(" ");
749 continue;
750 }
751 ok &= setCategoryEnable(token.string(), true);
752 }
753 delete tokenizer;
754 return ok;
755}
756
Jamie Gennise9b8cfb2013-03-12 23:00:10757// Set all the kernel tracing settings to the desired state for this trace
758// capture.
759static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 22:03:07760{
761 bool ok = true;
762
763 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 10:20:39764 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 22:03:07765 ok &= setTraceOverwriteEnable(g_traceOverwrite);
766 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
Joel Fernandesed80bd02017-06-02 17:19:28767 ok &= setCmdlineSize();
Carmen Jacksonea826792017-05-05 18:42:32768 ok &= setClock();
Jamie Gennise9b8cfb2013-03-12 23:00:10769 ok &= setPrintTgidEnableIfPresent(true);
770 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 22:03:07771
772 // Set up the tags property.
773 uint64_t tags = 0;
Elliott Hughes5fd6ff62017-03-28 21:55:31774 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 22:03:07775 if (g_categoryEnables[i]) {
776 const TracingCategory &c = k_categories[i];
777 tags |= c.tags;
778 }
779 }
780 ok &= setTagsProperty(tags);
sergeyvdb404152016-05-03 02:26:07781
782 bool coreServicesTagEnabled = false;
Elliott Hughes5fd6ff62017-03-28 21:55:31783 for (size_t i = 0; i < arraysize(k_categories); i++) {
sergeyvdb404152016-05-03 02:26:07784 if (strcmp(k_categories[i].name, k_coreServiceCategory) == 0) {
785 coreServicesTagEnabled = g_categoryEnables[i];
786 }
787 }
788
789 std::string packageList(g_debugAppCmdLine);
790 if (coreServicesTagEnabled) {
sergeyvdb404152016-05-03 02:26:07791 if (!packageList.empty()) {
792 packageList += ",";
793 }
Elliott Hughes5fd6ff62017-03-28 21:55:31794 packageList += android::base::GetProperty(k_coreServicesProp, "");
sergeyvdb404152016-05-03 02:26:07795 }
Dan Austin09a79872016-05-31 20:27:03796 ok &= setAppCmdlineProperty(&packageList[0]);
Jamie Gennisf7f29c82013-03-27 22:50:58797 ok &= pokeBinderServices();
Martijn Coenenee9b97e2016-11-16 15:00:26798 pokeHalServices();
Jamie Gennis6eea6fb2012-12-07 22:03:07799
800 // Disable all the sysfs enables. This is done as a separate loop from
801 // the enables to allow the same enable to exist in multiple categories.
802 ok &= disableKernelTraceEvents();
803
804 // Enable all the sysfs enables that are in an enabled category.
Elliott Hughes5fd6ff62017-03-28 21:55:31805 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 22:03:07806 if (g_categoryEnables[i]) {
807 const TracingCategory &c = k_categories[i];
808 for (int j = 0; j < MAX_SYS_FILES; j++) {
809 const char* path = c.sysfiles[j].path;
810 bool required = c.sysfiles[j].required == REQ;
811 if (path != NULL) {
812 if (fileIsWritable(path)) {
813 ok &= setKernelOptionEnable(path, true);
814 } else if (required) {
815 fprintf(stderr, "error writing file %s\n", path);
816 ok = false;
817 }
818 }
819 }
820 }
821 }
822
Jamie Gennis6eea6fb2012-12-07 22:03:07823 return ok;
824}
825
Jamie Gennise9b8cfb2013-03-12 23:00:10826// Reset all the kernel tracing settings to their default state.
827static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 22:03:07828{
Jamie Gennis6eea6fb2012-12-07 22:03:07829 // Disable all tracing that we're able to.
830 disableKernelTraceEvents();
831
Jamie Gennisf7f29c82013-03-27 22:50:58832 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 22:03:07833 setTagsProperty(0);
sergeyv4144eff2016-04-28 18:40:04834 clearAppProperties();
Jamie Gennisf7f29c82013-03-27 22:50:58835 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 22:03:07836
837 // Set the options back to their defaults.
838 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 23:00:10839 setTraceBufferSizeKB(1);
Jamie Gennise9b8cfb2013-03-12 23:00:10840 setPrintTgidEnableIfPresent(false);
841 setKernelTraceFuncs(NULL);
842}
Jamie Gennis6eea6fb2012-12-07 22:03:07843
Jamie Gennise9b8cfb2013-03-12 23:00:10844
845// Enable tracing in the kernel.
846static bool startTrace()
847{
848 return setTracingEnabled(true);
849}
850
851// Disable tracing in the kernel.
852static void stopTrace()
853{
854 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 22:03:07855}
856
Martijn Coenend9535872015-11-26 09:00:55857// Read data from the tracing pipe and forward to stdout
858static void streamTrace()
859{
860 char trace_data[4096];
Paul Lawrence2cd93cc2017-01-17 17:50:18861 int traceFD = open((g_traceFolder + k_traceStreamPath).c_str(), O_RDWR);
Martijn Coenend9535872015-11-26 09:00:55862 if (traceFD == -1) {
863 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceStreamPath,
864 strerror(errno), errno);
865 return;
866 }
867 while (!g_traceAborted) {
868 ssize_t bytes_read = read(traceFD, trace_data, 4096);
869 if (bytes_read > 0) {
870 write(STDOUT_FILENO, trace_data, bytes_read);
871 fflush(stdout);
872 } else {
873 if (!g_traceAborted) {
874 fprintf(stderr, "read returned %zd bytes err %d (%s)\n",
875 bytes_read, errno, strerror(errno));
876 }
877 break;
878 }
879 }
880}
881
Jamie Gennis6eea6fb2012-12-07 22:03:07882// Read the current kernel trace and write it to stdout.
John Reck40b26b42016-03-30 16:44:36883static void dumpTrace(int outFd)
Jamie Gennis6eea6fb2012-12-07 22:03:07884{
John Reck6c8ac922016-03-28 18:25:30885 ALOGI("Dumping trace");
Paul Lawrence2cd93cc2017-01-17 17:50:18886 int traceFD = open((g_traceFolder + k_tracePath).c_str(), O_RDWR);
Jamie Gennis6eea6fb2012-12-07 22:03:07887 if (traceFD == -1) {
888 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
889 strerror(errno), errno);
890 return;
891 }
892
893 if (g_compress) {
894 z_stream zs;
Elliott Hughes3da5d232015-01-25 16:35:20895 memset(&zs, 0, sizeof(zs));
Elliott Hughesa252f4d2016-07-22 00:12:15896
897 int result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
Jamie Gennis6eea6fb2012-12-07 22:03:07898 if (result != Z_OK) {
899 fprintf(stderr, "error initializing zlib: %d\n", result);
900 close(traceFD);
901 return;
902 }
903
Elliott Hughesa252f4d2016-07-22 00:12:15904 constexpr size_t bufSize = 64*1024;
905 std::unique_ptr<uint8_t> in(new uint8_t[bufSize]);
906 std::unique_ptr<uint8_t> out(new uint8_t[bufSize]);
907 if (!in || !out) {
908 fprintf(stderr, "couldn't allocate buffers\n");
909 close(traceFD);
910 return;
911 }
Jamie Gennis6eea6fb2012-12-07 22:03:07912
Elliott Hughesa252f4d2016-07-22 00:12:15913 int flush = Z_NO_FLUSH;
914
915 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 22:03:07916 zs.avail_out = bufSize;
917
918 do {
919
920 if (zs.avail_in == 0) {
921 // More input is needed.
Elliott Hughesa252f4d2016-07-22 00:12:15922 result = read(traceFD, in.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 22:03:07923 if (result < 0) {
924 fprintf(stderr, "error reading trace: %s (%d)\n",
925 strerror(errno), errno);
926 result = Z_STREAM_END;
927 break;
928 } else if (result == 0) {
929 flush = Z_FINISH;
930 } else {
Elliott Hughesa252f4d2016-07-22 00:12:15931 zs.next_in = reinterpret_cast<Bytef*>(in.get());
Jamie Gennis6eea6fb2012-12-07 22:03:07932 zs.avail_in = result;
933 }
934 }
935
936 if (zs.avail_out == 0) {
937 // Need to write the output.
Elliott Hughesb59e2962016-07-22 16:00:59938 result = write(outFd, out.get(), bufSize);
Jamie Gennis6eea6fb2012-12-07 22:03:07939 if ((size_t)result < bufSize) {
940 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
941 strerror(errno), errno);
942 result = Z_STREAM_END; // skip deflate error message
943 zs.avail_out = bufSize; // skip the final write
944 break;
945 }
Elliott Hughesa252f4d2016-07-22 00:12:15946 zs.next_out = reinterpret_cast<Bytef*>(out.get());
Jamie Gennis6eea6fb2012-12-07 22:03:07947 zs.avail_out = bufSize;
948 }
949
950 } while ((result = deflate(&zs, flush)) == Z_OK);
951
952 if (result != Z_STREAM_END) {
953 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
954 }
955
956 if (zs.avail_out < bufSize) {
957 size_t bytes = bufSize - zs.avail_out;
Elliott Hughesb59e2962016-07-22 16:00:59958 result = write(outFd, out.get(), bytes);
Jamie Gennis6eea6fb2012-12-07 22:03:07959 if ((size_t)result < bytes) {
960 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
961 strerror(errno), errno);
962 }
963 }
964
965 result = deflateEnd(&zs);
966 if (result != Z_OK) {
967 fprintf(stderr, "error cleaning up zlib: %d\n", result);
968 }
Jamie Gennis6eea6fb2012-12-07 22:03:07969 } else {
Josh Gaod3d36e72017-04-11 22:21:13970 char buf[4096];
971 ssize_t rc;
972 while ((rc = TEMP_FAILURE_RETRY(read(traceFD, buf, sizeof(buf)))) > 0) {
973 if (!android::base::WriteFully(outFd, buf, rc)) {
974 fprintf(stderr, "error writing trace: %s\n", strerror(errno));
975 break;
976 }
977 }
978 if (rc == -1) {
979 fprintf(stderr, "error dumping trace: %s\n", strerror(errno));
Jamie Gennis6eea6fb2012-12-07 22:03:07980 }
981 }
982
983 close(traceFD);
984}
985
Mark Salyzyn92dc3fc2014-03-12 20:12:44986static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 22:03:07987{
988 if (!g_nohup) {
989 g_traceAborted = true;
990 }
991}
992
993static void registerSigHandler()
994{
995 struct sigaction sa;
996 sigemptyset(&sa.sa_mask);
997 sa.sa_flags = 0;
998 sa.sa_handler = handleSignal;
999 sigaction(SIGHUP, &sa, NULL);
1000 sigaction(SIGINT, &sa, NULL);
1001 sigaction(SIGQUIT, &sa, NULL);
1002 sigaction(SIGTERM, &sa, NULL);
1003}
1004
Jamie Gennis6eea6fb2012-12-07 22:03:071005static void listSupportedCategories()
1006{
Elliott Hughes5fd6ff62017-03-28 21:55:311007 for (size_t i = 0; i < arraysize(k_categories); i++) {
Jamie Gennis6eea6fb2012-12-07 22:03:071008 const TracingCategory& c = k_categories[i];
1009 if (isCategorySupported(c)) {
1010 printf(" %10s - %s\n", c.name, c.longname);
1011 }
1012 }
1013}
1014
1015// Print the command usage help to stderr.
1016static void showHelp(const char *cmd)
1017{
1018 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
1019 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 22:50:581020 " -a appname enable app-level tracing for a comma "
1021 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 22:03:071022 " -b N use a trace buffer size of N KB\n"
1023 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 10:20:391024 " -f filename use the categories written in a file as space-separated\n"
1025 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 23:00:101026 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 22:03:071027 " -n ignore signals\n"
1028 " -s N sleep for N seconds before tracing [default 0]\n"
Fabien Sanglardb5c95472016-06-08 18:40:121029 " -t N trace for N seconds [default 5]\n"
Jamie Gennis6eea6fb2012-12-07 22:03:071030 " -z compress the trace dump\n"
Fabien Sanglardb5c95472016-06-08 18:40:121031 " --async_start start circular trace and return immediately\n"
Jamie Gennis6eea6fb2012-12-07 22:03:071032 " --async_dump dump the current contents of circular trace buffer\n"
1033 " --async_stop stop tracing and dump the current contents of circular\n"
1034 " trace buffer\n"
Martijn Coenend9535872015-11-26 09:00:551035 " --stream stream trace to stdout as it enters the trace buffer\n"
1036 " Note: this can take significant CPU time, and is best\n"
1037 " used for measuring things that are not affected by\n"
1038 " CPU performance, like pagecache usage.\n"
Jamie Gennis92573f12012-12-08 00:29:031039 " --list_categories\n"
1040 " list the available tracing categories\n"
John Reck40b26b42016-03-30 16:44:361041 " -o filename write the trace to the specified file instead\n"
1042 " of stdout.\n"
Jamie Gennis6eea6fb2012-12-07 22:03:071043 );
1044}
1045
Paul Lawrence2cd93cc2017-01-17 17:50:181046bool findTraceFiles()
1047{
1048 static const std::string debugfs_path = "/sys/kernel/debug/tracing/";
1049 static const std::string tracefs_path = "/sys/kernel/tracing/";
1050 static const std::string trace_file = "trace_marker";
1051
1052 bool tracefs = access((tracefs_path + trace_file).c_str(), F_OK) != -1;
1053 bool debugfs = access((debugfs_path + trace_file).c_str(), F_OK) != -1;
1054
1055 if (!tracefs && !debugfs) {
1056 fprintf(stderr, "Error: Did not find trace folder\n");
1057 return false;
1058 }
1059
1060 if (tracefs) {
1061 g_traceFolder = tracefs_path;
1062 } else {
1063 g_traceFolder = debugfs_path;
1064 }
1065
1066 return true;
1067}
1068
Jamie Gennis6eea6fb2012-12-07 22:03:071069int main(int argc, char **argv)
1070{
1071 bool async = false;
1072 bool traceStart = true;
1073 bool traceStop = true;
1074 bool traceDump = true;
Martijn Coenend9535872015-11-26 09:00:551075 bool traceStream = false;
Jamie Gennis6eea6fb2012-12-07 22:03:071076
1077 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
1078 showHelp(argv[0]);
1079 exit(0);
1080 }
1081
Paul Lawrence2cd93cc2017-01-17 17:50:181082 if (!findTraceFiles()) {
1083 fprintf(stderr, "No trace folder found\n");
1084 exit(-1);
1085 }
1086
Jamie Gennis6eea6fb2012-12-07 22:03:071087 for (;;) {
1088 int ret;
1089 int option_index = 0;
1090 static struct option long_options[] = {
1091 {"async_start", no_argument, 0, 0 },
1092 {"async_stop", no_argument, 0, 0 },
1093 {"async_dump", no_argument, 0, 0 },
1094 {"list_categories", no_argument, 0, 0 },
Martijn Coenend9535872015-11-26 09:00:551095 {"stream", no_argument, 0, 0 },
Jamie Gennis6eea6fb2012-12-07 22:03:071096 { 0, 0, 0, 0 }
1097 };
1098
John Reck40b26b42016-03-30 16:44:361099 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:zo:",
Jamie Gennis6eea6fb2012-12-07 22:03:071100 long_options, &option_index);
1101
1102 if (ret < 0) {
1103 for (int i = optind; i < argc; i++) {
1104 if (!setCategoryEnable(argv[i], true)) {
1105 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
1106 exit(1);
1107 }
1108 }
1109 break;
1110 }
1111
1112 switch(ret) {
Jamie Gennisf7f29c82013-03-27 22:50:581113 case 'a':
1114 g_debugAppCmdLine = optarg;
1115 break;
1116
Jamie Gennis6eea6fb2012-12-07 22:03:071117 case 'b':
1118 g_traceBufferSizeKB = atoi(optarg);
1119 break;
1120
1121 case 'c':
1122 g_traceOverwrite = true;
1123 break;
1124
Yasuhiro Matsuda46c51fb2015-06-29 10:20:391125 case 'f':
1126 g_categoriesFile = optarg;
1127 break;
1128
Jamie Gennise9b8cfb2013-03-12 23:00:101129 case 'k':
1130 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 22:50:301131 break;
Jamie Gennise9b8cfb2013-03-12 23:00:101132
Jamie Gennis6eea6fb2012-12-07 22:03:071133 case 'n':
1134 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 22:50:301135 break;
Jamie Gennis6eea6fb2012-12-07 22:03:071136
1137 case 's':
1138 g_initialSleepSecs = atoi(optarg);
1139 break;
1140
1141 case 't':
1142 g_traceDurationSeconds = atoi(optarg);
1143 break;
1144
1145 case 'z':
1146 g_compress = true;
1147 break;
1148
John Reck40b26b42016-03-30 16:44:361149 case 'o':
1150 g_outputFile = optarg;
1151 break;
1152
Jamie Gennis6eea6fb2012-12-07 22:03:071153 case 0:
1154 if (!strcmp(long_options[option_index].name, "async_start")) {
1155 async = true;
1156 traceStop = false;
1157 traceDump = false;
1158 g_traceOverwrite = true;
1159 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
1160 async = true;
John Reck4ba2b632015-05-15 17:00:341161 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 22:03:071162 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
1163 async = true;
1164 traceStart = false;
1165 traceStop = false;
Martijn Coenend9535872015-11-26 09:00:551166 } else if (!strcmp(long_options[option_index].name, "stream")) {
1167 traceStream = true;
1168 traceDump = false;
Jamie Gennis6eea6fb2012-12-07 22:03:071169 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
1170 listSupportedCategories();
1171 exit(0);
1172 }
Jamie Gennis6f6f3f72013-03-27 22:50:301173 break;
Jamie Gennis6eea6fb2012-12-07 22:03:071174
1175 default:
1176 fprintf(stderr, "\n");
1177 showHelp(argv[0]);
1178 exit(-1);
1179 break;
1180 }
1181 }
1182
1183 registerSigHandler();
1184
1185 if (g_initialSleepSecs > 0) {
1186 sleep(g_initialSleepSecs);
1187 }
1188
Jamie Gennise9b8cfb2013-03-12 23:00:101189 bool ok = true;
1190 ok &= setUpTrace();
1191 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 22:03:071192
1193 if (ok && traceStart) {
Martijn Coenend9535872015-11-26 09:00:551194 if (!traceStream) {
Carmen Jacksonac53e732017-05-02 23:55:331195 printf("capturing trace...");
Martijn Coenend9535872015-11-26 09:00:551196 fflush(stdout);
1197 }
Jamie Gennis6eea6fb2012-12-07 22:03:071198
1199 // We clear the trace after starting it because tracing gets enabled for
1200 // each CPU individually in the kernel. Having the beginning of the trace
1201 // contain entries from only one CPU can cause "begin" entries without a
1202 // matching "end" entry to show up if a task gets migrated from one CPU to
1203 // another.
1204 ok = clearTrace();
1205
Martijn Coenen0bcd97a2015-07-15 12:25:231206 writeClockSyncMarker();
Martijn Coenend9535872015-11-26 09:00:551207 if (ok && !async && !traceStream) {
Jamie Gennis6eea6fb2012-12-07 22:03:071208 // Sleep to allow the trace to be captured.
1209 struct timespec timeLeft;
1210 timeLeft.tv_sec = g_traceDurationSeconds;
1211 timeLeft.tv_nsec = 0;
1212 do {
1213 if (g_traceAborted) {
1214 break;
1215 }
1216 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
1217 }
Martijn Coenend9535872015-11-26 09:00:551218
1219 if (traceStream) {
1220 streamTrace();
1221 }
Jamie Gennis6eea6fb2012-12-07 22:03:071222 }
1223
1224 // Stop the trace and restore the default settings.
1225 if (traceStop)
1226 stopTrace();
1227
1228 if (ok && traceDump) {
1229 if (!g_traceAborted) {
John Reck40b26b42016-03-30 16:44:361230 printf(" done\n");
Jamie Gennis6eea6fb2012-12-07 22:03:071231 fflush(stdout);
John Reck40b26b42016-03-30 16:44:361232 int outFd = STDOUT_FILENO;
1233 if (g_outputFile) {
Martijn Coenenc5791982017-02-22 08:25:311234 outFd = open(g_outputFile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
John Reck40b26b42016-03-30 16:44:361235 }
1236 if (outFd == -1) {
1237 printf("Failed to open '%s', err=%d", g_outputFile, errno);
1238 } else {
1239 dprintf(outFd, "TRACE:\n");
1240 dumpTrace(outFd);
1241 if (g_outputFile) {
1242 close(outFd);
1243 }
1244 }
Jamie Gennis6eea6fb2012-12-07 22:03:071245 } else {
1246 printf("\ntrace aborted.\n");
1247 fflush(stdout);
1248 }
1249 clearTrace();
1250 } else if (!ok) {
1251 fprintf(stderr, "unable to start tracing\n");
1252 }
1253
1254 // Reset the trace buffer size to 1.
1255 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 23:00:101256 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 22:03:071257
1258 return g_traceAborted ? 1 : 0;
1259}