blob: e3dbbd56c90631a1b2dcb03116a3785a706a4501 [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
17#include <errno.h>
18#include <fcntl.h>
19#include <getopt.h>
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070020#include <inttypes.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080021#include <signal.h>
22#include <stdarg.h>
23#include <stdbool.h>
24#include <stdio.h>
25#include <stdlib.h>
Elliott Hughes3da5d232015-01-25 08:35:20 -080026#include <string.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080027#include <sys/sendfile.h>
28#include <time.h>
29#include <zlib.h>
30
31#include <binder/IBinder.h>
32#include <binder/IServiceManager.h>
33#include <binder/Parcel.h>
34
35#include <cutils/properties.h>
36
37#include <utils/String8.h>
John Reck469a1942015-03-26 15:31:35 -070038#include <utils/Timers.h>
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +090039#include <utils/Tokenizer.h>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080040#include <utils/Trace.h>
41
42using namespace android;
43
44#define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0])))
45
Mohamad Ayyash26dbcbe2014-04-08 15:24:11 -070046enum { MAX_SYS_FILES = 10 };
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080047
48const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
Jamie Gennisf7f29c82013-03-27 15:50:58 -070049const char* k_traceAppCmdlineProperty = "debug.atrace.app_cmdlines";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080050
51typedef enum { OPT, REQ } requiredness ;
52
53struct TracingCategory {
54 // The name identifying the category.
55 const char* name;
56
57 // A longer description of the category.
58 const char* longname;
59
60 // The userland tracing tags that the category enables.
61 uint64_t tags;
62
63 // The fname==NULL terminated list of /sys/ files that the category
64 // enables.
65 struct {
66 // Whether the file must be writable in order to enable the tracing
67 // category.
68 requiredness required;
69
70 // The path to the enable file.
71 const char* path;
72 } sysfiles[MAX_SYS_FILES];
73};
74
75/* Tracing categories */
76static const TracingCategory k_categories[] = {
Jamie Gennisb2a89e32013-03-11 19:37:53 -070077 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, { } },
78 { "input", "Input", ATRACE_TAG_INPUT, { } },
79 { "view", "View System", ATRACE_TAG_VIEW, { } },
80 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
81 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
82 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -050083 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070084 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
85 { "video", "Video", ATRACE_TAG_VIDEO, { } },
86 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
87 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -070088 { "app", "Application", ATRACE_TAG_APP, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -070089 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -070090 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -070091 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -070092 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -070093 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Todd Kennedy01e111b2015-07-31 14:36:20 -070094 { "pm", "Package Manager", ATRACE_TAG_PACKAGE_MANAGER, { } },
Yasuhiro Matsuda7cc49772015-07-01 01:46:25 +090095 { "ss", "System Server", ATRACE_TAG_SYSTEM_SERVER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070096 { "sched", "CPU Scheduling", 0, {
97 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_switch/enable" },
98 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_wakeup/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080099 } },
Dan Willemsenf440d392014-04-11 15:44:09 -0700100 { "irq", "IRQ Events", 0, {
101 { REQ, "/sys/kernel/debug/tracing/events/irq/enable" },
102 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700103 { "freq", "CPU Frequency", 0, {
104 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_frequency/enable" },
105 { OPT, "/sys/kernel/debug/tracing/events/power/clock_set_rate/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800106 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700107 { "membus", "Memory Bus Utilization", 0, {
108 { REQ, "/sys/kernel/debug/tracing/events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800109 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700110 { "idle", "CPU Idle", 0, {
111 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800112 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700113 { "disk", "Disk I/O", 0, {
Greg Hackmanne80d32c2014-11-20 12:59:44 -0800114 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_enter/enable" },
115 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_exit/enable" },
116 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_begin/enable" },
117 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_end/enable" },
118 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_begin/enable" },
119 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_end/enable" },
120 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable" },
121 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable" },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700122 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" },
123 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800124 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700125 { "mmc", "eMMC commands", 0, {
126 { REQ, "/sys/kernel/debug/tracing/events/mmc/enable" },
127 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700128 { "load", "CPU Load", 0, {
129 { REQ, "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800130 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700131 { "sync", "Synchronization", 0, {
132 { REQ, "/sys/kernel/debug/tracing/events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800133 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700134 { "workq", "Kernel Workqueues", 0, {
135 { REQ, "/sys/kernel/debug/tracing/events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800136 } },
Colin Cross580407f2014-08-18 15:22:13 -0700137 { "memreclaim", "Kernel Memory Reclaim", 0, {
138 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
139 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
140 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_wake/enable" },
141 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_sleep/enable" },
142 } },
Aaron Schulmanc2c6ecd2015-02-25 08:37:09 -0800143 { "regulators", "Voltage and Current Regulators", 0, {
144 { REQ, "/sys/kernel/debug/tracing/events/regulator/enable" },
145 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800146};
147
148/* Command line options */
149static int g_traceDurationSeconds = 5;
150static bool g_traceOverwrite = false;
151static int g_traceBufferSizeKB = 2048;
152static bool g_compress = false;
153static bool g_nohup = false;
154static int g_initialSleepSecs = 0;
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900155static const char* g_categoriesFile = NULL;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700156static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700157static const char* g_debugAppCmdLine = "";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800158
159/* Global state */
160static bool g_traceAborted = false;
161static bool g_categoryEnables[NELEM(k_categories)] = {};
162
163/* Sys file paths */
164static const char* k_traceClockPath =
165 "/sys/kernel/debug/tracing/trace_clock";
166
167static const char* k_traceBufferSizePath =
168 "/sys/kernel/debug/tracing/buffer_size_kb";
169
170static const char* k_tracingOverwriteEnablePath =
171 "/sys/kernel/debug/tracing/options/overwrite";
172
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700173static const char* k_currentTracerPath =
174 "/sys/kernel/debug/tracing/current_tracer";
175
176static const char* k_printTgidPath =
177 "/sys/kernel/debug/tracing/options/print-tgid";
178
179static const char* k_funcgraphAbsTimePath =
180 "/sys/kernel/debug/tracing/options/funcgraph-abstime";
181
182static const char* k_funcgraphCpuPath =
183 "/sys/kernel/debug/tracing/options/funcgraph-cpu";
184
185static const char* k_funcgraphProcPath =
186 "/sys/kernel/debug/tracing/options/funcgraph-proc";
187
188static const char* k_funcgraphFlatPath =
189 "/sys/kernel/debug/tracing/options/funcgraph-flat";
190
191static const char* k_funcgraphDurationPath =
192 "/sys/kernel/debug/tracing/options/funcgraph-duration";
193
194static const char* k_ftraceFilterPath =
195 "/sys/kernel/debug/tracing/set_ftrace_filter";
196
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800197static const char* k_tracingOnPath =
198 "/sys/kernel/debug/tracing/tracing_on";
199
200static const char* k_tracePath =
201 "/sys/kernel/debug/tracing/trace";
202
John Reck469a1942015-03-26 15:31:35 -0700203static const char* k_traceMarkerPath =
204 "/sys/kernel/debug/tracing/trace_marker";
205
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800206// Check whether a file exists.
207static bool fileExists(const char* filename) {
208 return access(filename, F_OK) != -1;
209}
210
211// Check whether a file is writable.
212static bool fileIsWritable(const char* filename) {
213 return access(filename, W_OK) != -1;
214}
215
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700216// Truncate a file.
217static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800218{
Jamie Gennis43122e72013-03-21 14:06:31 -0700219 // This uses creat rather than truncate because some of the debug kernel
220 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
221 // calls to truncate, but they are cleared by calls to creat.
222 int traceFD = creat(path, 0);
223 if (traceFD == -1) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700224 fprintf(stderr, "error truncating %s: %s (%d)\n", path,
Jamie Gennis43122e72013-03-21 14:06:31 -0700225 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700226 return false;
227 }
228
Jamie Gennis43122e72013-03-21 14:06:31 -0700229 close(traceFD);
230
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700231 return true;
232}
233
234static bool _writeStr(const char* filename, const char* str, int flags)
235{
236 int fd = open(filename, flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800237 if (fd == -1) {
238 fprintf(stderr, "error opening %s: %s (%d)\n", filename,
239 strerror(errno), errno);
240 return false;
241 }
242
243 bool ok = true;
244 ssize_t len = strlen(str);
245 if (write(fd, str, len) != len) {
246 fprintf(stderr, "error writing to %s: %s (%d)\n", filename,
247 strerror(errno), errno);
248 ok = false;
249 }
250
251 close(fd);
252
253 return ok;
254}
255
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700256// Write a string to a file, returning true if the write was successful.
257static bool writeStr(const char* filename, const char* str)
258{
259 return _writeStr(filename, str, O_WRONLY);
260}
261
262// Append a string to a file, returning true if the write was successful.
263static bool appendStr(const char* filename, const char* str)
264{
265 return _writeStr(filename, str, O_APPEND|O_WRONLY);
266}
267
John Reck469a1942015-03-26 15:31:35 -0700268static void writeClockSyncMarker()
269{
270 char buffer[128];
271 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
272 snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
273 writeStr(k_traceMarkerPath, buffer);
274}
275
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800276// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
277// file.
278static bool setKernelOptionEnable(const char* filename, bool enable)
279{
280 return writeStr(filename, enable ? "1" : "0");
281}
282
283// Check whether the category is supported on the device with the current
284// rootness. A category is supported only if all its required /sys/ files are
285// writable and if enabling the category will enable one or more tracing tags
286// or /sys/ files.
287static bool isCategorySupported(const TracingCategory& category)
288{
289 bool ok = category.tags != 0;
290 for (int i = 0; i < MAX_SYS_FILES; i++) {
291 const char* path = category.sysfiles[i].path;
292 bool req = category.sysfiles[i].required == REQ;
293 if (path != NULL) {
294 if (req) {
295 if (!fileIsWritable(path)) {
296 return false;
297 } else {
298 ok = true;
299 }
300 } else {
301 ok |= fileIsWritable(path);
302 }
303 }
304 }
305 return ok;
306}
307
308// Check whether the category would be supported on the device if the user
309// were root. This function assumes that root is able to write to any file
310// that exists. It performs the same logic as isCategorySupported, but it
311// uses file existance rather than writability in the /sys/ file checks.
312static bool isCategorySupportedForRoot(const TracingCategory& category)
313{
314 bool ok = category.tags != 0;
315 for (int i = 0; i < MAX_SYS_FILES; i++) {
316 const char* path = category.sysfiles[i].path;
317 bool req = category.sysfiles[i].required == REQ;
318 if (path != NULL) {
319 if (req) {
320 if (!fileExists(path)) {
321 return false;
322 } else {
323 ok = true;
324 }
325 } else {
326 ok |= fileExists(path);
327 }
328 }
329 }
330 return ok;
331}
332
333// Enable or disable overwriting of the kernel trace buffers. Disabling this
334// will cause tracing to stop once the trace buffers have filled up.
335static bool setTraceOverwriteEnable(bool enable)
336{
337 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
338}
339
340// Enable or disable kernel tracing.
341static bool setTracingEnabled(bool enable)
342{
343 return setKernelOptionEnable(k_tracingOnPath, enable);
344}
345
346// Clear the contents of the kernel trace.
347static bool clearTrace()
348{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700349 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800350}
351
352// Set the size of the kernel's trace buffer in kilobytes.
353static bool setTraceBufferSizeKB(int size)
354{
355 char str[32] = "1";
356 int len;
357 if (size < 1) {
358 size = 1;
359 }
360 snprintf(str, 32, "%d", size);
361 return writeStr(k_traceBufferSizePath, str);
362}
363
Colin Crossb1ce49b2014-08-20 14:28:47 -0700364// Read the trace_clock sysfs file and return true if it matches the requested
365// value. The trace_clock file format is:
366// local [global] counter uptime perf
367static bool isTraceClock(const char *mode)
368{
369 int fd = open(k_traceClockPath, O_RDONLY);
370 if (fd == -1) {
371 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceClockPath,
372 strerror(errno), errno);
373 return false;
374 }
375
376 char buf[4097];
377 ssize_t n = read(fd, buf, 4096);
378 close(fd);
379 if (n == -1) {
380 fprintf(stderr, "error reading %s: %s (%d)\n", k_traceClockPath,
381 strerror(errno), errno);
382 return false;
383 }
384 buf[n] = '\0';
385
386 char *start = strchr(buf, '[');
387 if (start == NULL) {
388 return false;
389 }
390 start++;
391
392 char *end = strchr(start, ']');
393 if (end == NULL) {
394 return false;
395 }
396 *end = '\0';
397
398 return strcmp(mode, start) == 0;
399}
400
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800401// Enable or disable the kernel's use of the global clock. Disabling the global
402// clock will result in the kernel using a per-CPU local clock.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700403// Any write to the trace_clock sysfs file will reset the buffer, so only
404// update it if the requested value is not the current value.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800405static bool setGlobalClockEnable(bool enable)
406{
Colin Crossb1ce49b2014-08-20 14:28:47 -0700407 const char *clock = enable ? "global" : "local";
408
409 if (isTraceClock(clock)) {
410 return true;
411 }
412
413 return writeStr(k_traceClockPath, clock);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800414}
415
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700416static bool setPrintTgidEnableIfPresent(bool enable)
417{
418 if (fileExists(k_printTgidPath)) {
419 return setKernelOptionEnable(k_printTgidPath, enable);
420 }
421 return true;
422}
423
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800424// Poke all the binder-enabled processes in the system to get them to re-read
425// their system properties.
426static bool pokeBinderServices()
427{
428 sp<IServiceManager> sm = defaultServiceManager();
429 Vector<String16> services = sm->listServices();
430 for (size_t i = 0; i < services.size(); i++) {
431 sp<IBinder> obj = sm->checkService(services[i]);
432 if (obj != NULL) {
433 Parcel data;
434 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
435 NULL, 0) != OK) {
436 if (false) {
437 // XXX: For some reason this fails on tablets trying to
438 // poke the "phone" service. It's not clear whether some
439 // are expected to fail.
440 String8 svc(services[i]);
441 fprintf(stderr, "error poking binder service %s\n",
442 svc.string());
443 return false;
444 }
445 }
446 }
447 }
448 return true;
449}
450
451// Set the trace tags that userland tracing uses, and poke the running
452// processes to pick up the new value.
453static bool setTagsProperty(uint64_t tags)
454{
455 char buf[64];
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700456 snprintf(buf, 64, "%#" PRIx64, tags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800457 if (property_set(k_traceTagsProperty, buf) < 0) {
458 fprintf(stderr, "error setting trace tags system property\n");
459 return false;
460 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700461 return true;
462}
463
464// Set the system property that indicates which apps should perform
465// application-level tracing.
466static bool setAppCmdlineProperty(const char* cmdline)
467{
468 if (property_set(k_traceAppCmdlineProperty, cmdline) < 0) {
469 fprintf(stderr, "error setting trace app system property\n");
470 return false;
471 }
472 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800473}
474
475// Disable all /sys/ enable files.
476static bool disableKernelTraceEvents() {
477 bool ok = true;
478 for (int i = 0; i < NELEM(k_categories); i++) {
479 const TracingCategory &c = k_categories[i];
480 for (int j = 0; j < MAX_SYS_FILES; j++) {
481 const char* path = c.sysfiles[j].path;
482 if (path != NULL && fileIsWritable(path)) {
483 ok &= setKernelOptionEnable(path, false);
484 }
485 }
486 }
487 return ok;
488}
489
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700490// Verify that the comma separated list of functions are being traced by the
491// kernel.
492static bool verifyKernelTraceFuncs(const char* funcs)
493{
494 int fd = open(k_ftraceFilterPath, O_RDONLY);
495 if (fd == -1) {
496 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
497 strerror(errno), errno);
498 return false;
499 }
500
501 char buf[4097];
502 ssize_t n = read(fd, buf, 4096);
503 close(fd);
504 if (n == -1) {
505 fprintf(stderr, "error reading %s: %s (%d)\n", k_ftraceFilterPath,
506 strerror(errno), errno);
507 return false;
508 }
509
510 buf[n] = '\0';
511 String8 funcList = String8::format("\n%s", buf);
512
513 // Make sure that every function listed in funcs is in the list we just
514 // read from the kernel.
515 bool ok = true;
516 char* myFuncs = strdup(funcs);
517 char* func = strtok(myFuncs, ",");
518 while (func) {
519 String8 fancyFunc = String8::format("\n%s\n", func);
520 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
521 if (!found || func[0] == '\0') {
522 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
523 "to trace.\n", func);
524 ok = false;
525 }
526 func = strtok(NULL, ",");
527 }
528 free(myFuncs);
529
530 return ok;
531}
532
533// Set the comma separated list of functions that the kernel is to trace.
534static bool setKernelTraceFuncs(const char* funcs)
535{
536 bool ok = true;
537
538 if (funcs == NULL || funcs[0] == '\0') {
539 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700540 if (fileIsWritable(k_currentTracerPath)) {
541 ok &= writeStr(k_currentTracerPath, "nop");
542 }
543 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700544 ok &= truncateFile(k_ftraceFilterPath);
545 }
546 } else {
547 // Enable kernel function tracing.
548 ok &= writeStr(k_currentTracerPath, "function_graph");
549 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
550 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
551 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
552 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
553
554 // Set the requested filter functions.
555 ok &= truncateFile(k_ftraceFilterPath);
556 char* myFuncs = strdup(funcs);
557 char* func = strtok(myFuncs, ",");
558 while (func) {
559 ok &= appendStr(k_ftraceFilterPath, func);
560 func = strtok(NULL, ",");
561 }
562 free(myFuncs);
563
564 // Verify that the set functions are being traced.
565 if (ok) {
566 ok &= verifyKernelTraceFuncs(funcs);
567 }
568 }
569
570 return ok;
571}
572
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900573static bool setCategoryEnable(const char* name, bool enable)
574{
575 for (int i = 0; i < NELEM(k_categories); i++) {
576 const TracingCategory& c = k_categories[i];
577 if (strcmp(name, c.name) == 0) {
578 if (isCategorySupported(c)) {
579 g_categoryEnables[i] = enable;
580 return true;
581 } else {
582 if (isCategorySupportedForRoot(c)) {
583 fprintf(stderr, "error: category \"%s\" requires root "
584 "privileges.\n", name);
585 } else {
586 fprintf(stderr, "error: category \"%s\" is not supported "
587 "on this device.\n", name);
588 }
589 return false;
590 }
591 }
592 }
593 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
594 return false;
595}
596
597static bool setCategoriesEnableFromFile(const char* categories_file)
598{
599 if (!categories_file) {
600 return true;
601 }
602 Tokenizer* tokenizer = NULL;
603 if (Tokenizer::open(String8(categories_file), &tokenizer) != NO_ERROR) {
604 return false;
605 }
606 bool ok = true;
607 while (!tokenizer->isEol()) {
608 String8 token = tokenizer->nextToken(" ");
609 if (token.isEmpty()) {
610 tokenizer->skipDelimiters(" ");
611 continue;
612 }
613 ok &= setCategoryEnable(token.string(), true);
614 }
615 delete tokenizer;
616 return ok;
617}
618
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700619// Set all the kernel tracing settings to the desired state for this trace
620// capture.
621static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800622{
623 bool ok = true;
624
625 // Set up the tracing options.
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900626 ok &= setCategoriesEnableFromFile(g_categoriesFile);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800627 ok &= setTraceOverwriteEnable(g_traceOverwrite);
628 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
629 ok &= setGlobalClockEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700630 ok &= setPrintTgidEnableIfPresent(true);
631 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800632
633 // Set up the tags property.
634 uint64_t tags = 0;
635 for (int i = 0; i < NELEM(k_categories); i++) {
636 if (g_categoryEnables[i]) {
637 const TracingCategory &c = k_categories[i];
638 tags |= c.tags;
639 }
640 }
641 ok &= setTagsProperty(tags);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700642 ok &= setAppCmdlineProperty(g_debugAppCmdLine);
643 ok &= pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800644
645 // Disable all the sysfs enables. This is done as a separate loop from
646 // the enables to allow the same enable to exist in multiple categories.
647 ok &= disableKernelTraceEvents();
648
649 // Enable all the sysfs enables that are in an enabled category.
650 for (int i = 0; i < NELEM(k_categories); i++) {
651 if (g_categoryEnables[i]) {
652 const TracingCategory &c = k_categories[i];
653 for (int j = 0; j < MAX_SYS_FILES; j++) {
654 const char* path = c.sysfiles[j].path;
655 bool required = c.sysfiles[j].required == REQ;
656 if (path != NULL) {
657 if (fileIsWritable(path)) {
658 ok &= setKernelOptionEnable(path, true);
659 } else if (required) {
660 fprintf(stderr, "error writing file %s\n", path);
661 ok = false;
662 }
663 }
664 }
665 }
666 }
667
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800668 return ok;
669}
670
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700671// Reset all the kernel tracing settings to their default state.
672static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800673{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800674 // Disable all tracing that we're able to.
675 disableKernelTraceEvents();
676
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700677 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800678 setTagsProperty(0);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700679 setAppCmdlineProperty("");
680 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800681
682 // Set the options back to their defaults.
683 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700684 setTraceBufferSizeKB(1);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800685 setGlobalClockEnable(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700686 setPrintTgidEnableIfPresent(false);
687 setKernelTraceFuncs(NULL);
688}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800689
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700690
691// Enable tracing in the kernel.
692static bool startTrace()
693{
694 return setTracingEnabled(true);
695}
696
697// Disable tracing in the kernel.
698static void stopTrace()
699{
John Reck469a1942015-03-26 15:31:35 -0700700 writeClockSyncMarker();
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700701 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800702}
703
704// Read the current kernel trace and write it to stdout.
705static void dumpTrace()
706{
707 int traceFD = open(k_tracePath, O_RDWR);
708 if (traceFD == -1) {
709 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
710 strerror(errno), errno);
711 return;
712 }
713
714 if (g_compress) {
715 z_stream zs;
716 uint8_t *in, *out;
717 int result, flush;
718
Elliott Hughes3da5d232015-01-25 08:35:20 -0800719 memset(&zs, 0, sizeof(zs));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800720 result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
721 if (result != Z_OK) {
722 fprintf(stderr, "error initializing zlib: %d\n", result);
723 close(traceFD);
724 return;
725 }
726
727 const size_t bufSize = 64*1024;
728 in = (uint8_t*)malloc(bufSize);
729 out = (uint8_t*)malloc(bufSize);
730 flush = Z_NO_FLUSH;
731
732 zs.next_out = out;
733 zs.avail_out = bufSize;
734
735 do {
736
737 if (zs.avail_in == 0) {
738 // More input is needed.
739 result = read(traceFD, in, bufSize);
740 if (result < 0) {
741 fprintf(stderr, "error reading trace: %s (%d)\n",
742 strerror(errno), errno);
743 result = Z_STREAM_END;
744 break;
745 } else if (result == 0) {
746 flush = Z_FINISH;
747 } else {
748 zs.next_in = in;
749 zs.avail_in = result;
750 }
751 }
752
753 if (zs.avail_out == 0) {
754 // Need to write the output.
755 result = write(STDOUT_FILENO, out, bufSize);
756 if ((size_t)result < bufSize) {
757 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
758 strerror(errno), errno);
759 result = Z_STREAM_END; // skip deflate error message
760 zs.avail_out = bufSize; // skip the final write
761 break;
762 }
763 zs.next_out = out;
764 zs.avail_out = bufSize;
765 }
766
767 } while ((result = deflate(&zs, flush)) == Z_OK);
768
769 if (result != Z_STREAM_END) {
770 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
771 }
772
773 if (zs.avail_out < bufSize) {
774 size_t bytes = bufSize - zs.avail_out;
775 result = write(STDOUT_FILENO, out, bytes);
776 if ((size_t)result < bytes) {
777 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
778 strerror(errno), errno);
779 }
780 }
781
782 result = deflateEnd(&zs);
783 if (result != Z_OK) {
784 fprintf(stderr, "error cleaning up zlib: %d\n", result);
785 }
786
787 free(in);
788 free(out);
789 } else {
790 ssize_t sent = 0;
791 while ((sent = sendfile(STDOUT_FILENO, traceFD, NULL, 64*1024*1024)) > 0);
792 if (sent == -1) {
793 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
794 errno);
795 }
796 }
797
798 close(traceFD);
799}
800
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700801static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800802{
803 if (!g_nohup) {
804 g_traceAborted = true;
805 }
806}
807
808static void registerSigHandler()
809{
810 struct sigaction sa;
811 sigemptyset(&sa.sa_mask);
812 sa.sa_flags = 0;
813 sa.sa_handler = handleSignal;
814 sigaction(SIGHUP, &sa, NULL);
815 sigaction(SIGINT, &sa, NULL);
816 sigaction(SIGQUIT, &sa, NULL);
817 sigaction(SIGTERM, &sa, NULL);
818}
819
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800820static void listSupportedCategories()
821{
822 for (int i = 0; i < NELEM(k_categories); i++) {
823 const TracingCategory& c = k_categories[i];
824 if (isCategorySupported(c)) {
825 printf(" %10s - %s\n", c.name, c.longname);
826 }
827 }
828}
829
830// Print the command usage help to stderr.
831static void showHelp(const char *cmd)
832{
833 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
834 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700835 " -a appname enable app-level tracing for a comma "
836 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800837 " -b N use a trace buffer size of N KB\n"
838 " -c trace into a circular buffer\n"
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900839 " -f filename use the categories written in a file as space-separated\n"
840 " values in a line\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700841 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800842 " -n ignore signals\n"
843 " -s N sleep for N seconds before tracing [default 0]\n"
844 " -t N trace for N seconds [defualt 5]\n"
845 " -z compress the trace dump\n"
846 " --async_start start circular trace and return immediatly\n"
847 " --async_dump dump the current contents of circular trace buffer\n"
848 " --async_stop stop tracing and dump the current contents of circular\n"
849 " trace buffer\n"
Jamie Gennis92573f12012-12-07 16:29:03 -0800850 " --list_categories\n"
851 " list the available tracing categories\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800852 );
853}
854
855int main(int argc, char **argv)
856{
857 bool async = false;
858 bool traceStart = true;
859 bool traceStop = true;
860 bool traceDump = true;
861
862 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
863 showHelp(argv[0]);
864 exit(0);
865 }
866
867 for (;;) {
868 int ret;
869 int option_index = 0;
870 static struct option long_options[] = {
871 {"async_start", no_argument, 0, 0 },
872 {"async_stop", no_argument, 0, 0 },
873 {"async_dump", no_argument, 0, 0 },
874 {"list_categories", no_argument, 0, 0 },
875 { 0, 0, 0, 0 }
876 };
877
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900878 ret = getopt_long(argc, argv, "a:b:cf:k:ns:t:z",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800879 long_options, &option_index);
880
881 if (ret < 0) {
882 for (int i = optind; i < argc; i++) {
883 if (!setCategoryEnable(argv[i], true)) {
884 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
885 exit(1);
886 }
887 }
888 break;
889 }
890
891 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700892 case 'a':
893 g_debugAppCmdLine = optarg;
894 break;
895
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800896 case 'b':
897 g_traceBufferSizeKB = atoi(optarg);
898 break;
899
900 case 'c':
901 g_traceOverwrite = true;
902 break;
903
Yasuhiro Matsuda46c51fb2015-06-29 19:20:39 +0900904 case 'f':
905 g_categoriesFile = optarg;
906 break;
907
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700908 case 'k':
909 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700910 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700911
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800912 case 'n':
913 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700914 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800915
916 case 's':
917 g_initialSleepSecs = atoi(optarg);
918 break;
919
920 case 't':
921 g_traceDurationSeconds = atoi(optarg);
922 break;
923
924 case 'z':
925 g_compress = true;
926 break;
927
928 case 0:
929 if (!strcmp(long_options[option_index].name, "async_start")) {
930 async = true;
931 traceStop = false;
932 traceDump = false;
933 g_traceOverwrite = true;
934 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
935 async = true;
John Reck4ba2b632015-05-15 10:00:34 -0700936 traceStart = false;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800937 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
938 async = true;
939 traceStart = false;
940 traceStop = false;
941 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
942 listSupportedCategories();
943 exit(0);
944 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700945 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800946
947 default:
948 fprintf(stderr, "\n");
949 showHelp(argv[0]);
950 exit(-1);
951 break;
952 }
953 }
954
955 registerSigHandler();
956
957 if (g_initialSleepSecs > 0) {
958 sleep(g_initialSleepSecs);
959 }
960
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700961 bool ok = true;
962 ok &= setUpTrace();
963 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800964
965 if (ok && traceStart) {
966 printf("capturing trace...");
967 fflush(stdout);
968
969 // We clear the trace after starting it because tracing gets enabled for
970 // each CPU individually in the kernel. Having the beginning of the trace
971 // contain entries from only one CPU can cause "begin" entries without a
972 // matching "end" entry to show up if a task gets migrated from one CPU to
973 // another.
974 ok = clearTrace();
975
976 if (ok && !async) {
977 // Sleep to allow the trace to be captured.
978 struct timespec timeLeft;
979 timeLeft.tv_sec = g_traceDurationSeconds;
980 timeLeft.tv_nsec = 0;
981 do {
982 if (g_traceAborted) {
983 break;
984 }
985 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
986 }
987 }
988
989 // Stop the trace and restore the default settings.
990 if (traceStop)
991 stopTrace();
992
993 if (ok && traceDump) {
994 if (!g_traceAborted) {
995 printf(" done\nTRACE:\n");
996 fflush(stdout);
997 dumpTrace();
998 } else {
999 printf("\ntrace aborted.\n");
1000 fflush(stdout);
1001 }
1002 clearTrace();
1003 } else if (!ok) {
1004 fprintf(stderr, "unable to start tracing\n");
1005 }
1006
1007 // Reset the trace buffer size to 1.
1008 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -07001009 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -08001010
1011 return g_traceAborted ? 1 : 0;
1012}