blob: 515d761f4fd5e998be3748a9dc1653ff1cf251e3 [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>
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080039#include <utils/Trace.h>
40
41using namespace android;
42
43#define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0])))
44
Mohamad Ayyash26dbcbe2014-04-08 15:24:11 -070045enum { MAX_SYS_FILES = 10 };
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080046
47const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
Jamie Gennisf7f29c82013-03-27 15:50:58 -070048const char* k_traceAppCmdlineProperty = "debug.atrace.app_cmdlines";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080049
50typedef enum { OPT, REQ } requiredness ;
51
52struct TracingCategory {
53 // The name identifying the category.
54 const char* name;
55
56 // A longer description of the category.
57 const char* longname;
58
59 // The userland tracing tags that the category enables.
60 uint64_t tags;
61
62 // The fname==NULL terminated list of /sys/ files that the category
63 // enables.
64 struct {
65 // Whether the file must be writable in order to enable the tracing
66 // category.
67 requiredness required;
68
69 // The path to the enable file.
70 const char* path;
71 } sysfiles[MAX_SYS_FILES];
72};
73
74/* Tracing categories */
75static const TracingCategory k_categories[] = {
Jamie Gennisb2a89e32013-03-11 19:37:53 -070076 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, { } },
77 { "input", "Input", ATRACE_TAG_INPUT, { } },
78 { "view", "View System", ATRACE_TAG_VIEW, { } },
79 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
80 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
81 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
Patrick Auchter70ec2942014-09-30 15:38:30 -050082 { "sm", "Sync Manager", ATRACE_TAG_SYNC_MANAGER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070083 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
84 { "video", "Video", ATRACE_TAG_VIDEO, { } },
85 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
86 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -070087 { "app", "Application", ATRACE_TAG_APP, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -070088 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -070089 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -070090 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Brigid Smith750aa972014-05-28 14:23:24 -070091 { "bionic", "Bionic C Library", ATRACE_TAG_BIONIC, { } },
Jeff Brown3200b0b2014-08-14 19:24:47 -070092 { "power", "Power Management", ATRACE_TAG_POWER, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070093 { "sched", "CPU Scheduling", 0, {
94 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_switch/enable" },
95 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_wakeup/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080096 } },
Dan Willemsenf440d392014-04-11 15:44:09 -070097 { "irq", "IRQ Events", 0, {
98 { REQ, "/sys/kernel/debug/tracing/events/irq/enable" },
99 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700100 { "freq", "CPU Frequency", 0, {
101 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_frequency/enable" },
102 { OPT, "/sys/kernel/debug/tracing/events/power/clock_set_rate/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800103 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700104 { "membus", "Memory Bus Utilization", 0, {
105 { REQ, "/sys/kernel/debug/tracing/events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800106 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700107 { "idle", "CPU Idle", 0, {
108 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800109 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700110 { "disk", "Disk I/O", 0, {
Greg Hackmanne80d32c2014-11-20 12:59:44 -0800111 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_enter/enable" },
112 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_exit/enable" },
113 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_begin/enable" },
114 { OPT, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_end/enable" },
115 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_begin/enable" },
116 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_end/enable" },
117 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable" },
118 { OPT, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable" },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700119 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" },
120 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800121 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700122 { "mmc", "eMMC commands", 0, {
123 { REQ, "/sys/kernel/debug/tracing/events/mmc/enable" },
124 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700125 { "load", "CPU Load", 0, {
126 { REQ, "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800127 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700128 { "sync", "Synchronization", 0, {
129 { REQ, "/sys/kernel/debug/tracing/events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800130 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700131 { "workq", "Kernel Workqueues", 0, {
132 { REQ, "/sys/kernel/debug/tracing/events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800133 } },
Colin Cross580407f2014-08-18 15:22:13 -0700134 { "memreclaim", "Kernel Memory Reclaim", 0, {
135 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_begin/enable" },
136 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_direct_reclaim_end/enable" },
137 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_wake/enable" },
138 { REQ, "/sys/kernel/debug/tracing/events/vmscan/mm_vmscan_kswapd_sleep/enable" },
139 } },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800140};
141
142/* Command line options */
143static int g_traceDurationSeconds = 5;
144static bool g_traceOverwrite = false;
145static int g_traceBufferSizeKB = 2048;
146static bool g_compress = false;
147static bool g_nohup = false;
148static int g_initialSleepSecs = 0;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700149static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700150static const char* g_debugAppCmdLine = "";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800151
152/* Global state */
153static bool g_traceAborted = false;
154static bool g_categoryEnables[NELEM(k_categories)] = {};
155
156/* Sys file paths */
157static const char* k_traceClockPath =
158 "/sys/kernel/debug/tracing/trace_clock";
159
160static const char* k_traceBufferSizePath =
161 "/sys/kernel/debug/tracing/buffer_size_kb";
162
163static const char* k_tracingOverwriteEnablePath =
164 "/sys/kernel/debug/tracing/options/overwrite";
165
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700166static const char* k_currentTracerPath =
167 "/sys/kernel/debug/tracing/current_tracer";
168
169static const char* k_printTgidPath =
170 "/sys/kernel/debug/tracing/options/print-tgid";
171
172static const char* k_funcgraphAbsTimePath =
173 "/sys/kernel/debug/tracing/options/funcgraph-abstime";
174
175static const char* k_funcgraphCpuPath =
176 "/sys/kernel/debug/tracing/options/funcgraph-cpu";
177
178static const char* k_funcgraphProcPath =
179 "/sys/kernel/debug/tracing/options/funcgraph-proc";
180
181static const char* k_funcgraphFlatPath =
182 "/sys/kernel/debug/tracing/options/funcgraph-flat";
183
184static const char* k_funcgraphDurationPath =
185 "/sys/kernel/debug/tracing/options/funcgraph-duration";
186
187static const char* k_ftraceFilterPath =
188 "/sys/kernel/debug/tracing/set_ftrace_filter";
189
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800190static const char* k_tracingOnPath =
191 "/sys/kernel/debug/tracing/tracing_on";
192
193static const char* k_tracePath =
194 "/sys/kernel/debug/tracing/trace";
195
John Reck469a1942015-03-26 15:31:35 -0700196static const char* k_traceMarkerPath =
197 "/sys/kernel/debug/tracing/trace_marker";
198
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800199// Check whether a file exists.
200static bool fileExists(const char* filename) {
201 return access(filename, F_OK) != -1;
202}
203
204// Check whether a file is writable.
205static bool fileIsWritable(const char* filename) {
206 return access(filename, W_OK) != -1;
207}
208
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700209// Truncate a file.
210static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800211{
Jamie Gennis43122e72013-03-21 14:06:31 -0700212 // This uses creat rather than truncate because some of the debug kernel
213 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
214 // calls to truncate, but they are cleared by calls to creat.
215 int traceFD = creat(path, 0);
216 if (traceFD == -1) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700217 fprintf(stderr, "error truncating %s: %s (%d)\n", path,
Jamie Gennis43122e72013-03-21 14:06:31 -0700218 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700219 return false;
220 }
221
Jamie Gennis43122e72013-03-21 14:06:31 -0700222 close(traceFD);
223
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700224 return true;
225}
226
227static bool _writeStr(const char* filename, const char* str, int flags)
228{
229 int fd = open(filename, flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800230 if (fd == -1) {
231 fprintf(stderr, "error opening %s: %s (%d)\n", filename,
232 strerror(errno), errno);
233 return false;
234 }
235
236 bool ok = true;
237 ssize_t len = strlen(str);
238 if (write(fd, str, len) != len) {
239 fprintf(stderr, "error writing to %s: %s (%d)\n", filename,
240 strerror(errno), errno);
241 ok = false;
242 }
243
244 close(fd);
245
246 return ok;
247}
248
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700249// Write a string to a file, returning true if the write was successful.
250static bool writeStr(const char* filename, const char* str)
251{
252 return _writeStr(filename, str, O_WRONLY);
253}
254
255// Append a string to a file, returning true if the write was successful.
256static bool appendStr(const char* filename, const char* str)
257{
258 return _writeStr(filename, str, O_APPEND|O_WRONLY);
259}
260
John Reck469a1942015-03-26 15:31:35 -0700261static void writeClockSyncMarker()
262{
263 char buffer[128];
264 float now_in_seconds = systemTime(CLOCK_MONOTONIC) / 1000000000.0f;
265 snprintf(buffer, 128, "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
266 writeStr(k_traceMarkerPath, buffer);
267}
268
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800269// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
270// file.
271static bool setKernelOptionEnable(const char* filename, bool enable)
272{
273 return writeStr(filename, enable ? "1" : "0");
274}
275
276// Check whether the category is supported on the device with the current
277// rootness. A category is supported only if all its required /sys/ files are
278// writable and if enabling the category will enable one or more tracing tags
279// or /sys/ files.
280static bool isCategorySupported(const TracingCategory& category)
281{
282 bool ok = category.tags != 0;
283 for (int i = 0; i < MAX_SYS_FILES; i++) {
284 const char* path = category.sysfiles[i].path;
285 bool req = category.sysfiles[i].required == REQ;
286 if (path != NULL) {
287 if (req) {
288 if (!fileIsWritable(path)) {
289 return false;
290 } else {
291 ok = true;
292 }
293 } else {
294 ok |= fileIsWritable(path);
295 }
296 }
297 }
298 return ok;
299}
300
301// Check whether the category would be supported on the device if the user
302// were root. This function assumes that root is able to write to any file
303// that exists. It performs the same logic as isCategorySupported, but it
304// uses file existance rather than writability in the /sys/ file checks.
305static bool isCategorySupportedForRoot(const TracingCategory& category)
306{
307 bool ok = category.tags != 0;
308 for (int i = 0; i < MAX_SYS_FILES; i++) {
309 const char* path = category.sysfiles[i].path;
310 bool req = category.sysfiles[i].required == REQ;
311 if (path != NULL) {
312 if (req) {
313 if (!fileExists(path)) {
314 return false;
315 } else {
316 ok = true;
317 }
318 } else {
319 ok |= fileExists(path);
320 }
321 }
322 }
323 return ok;
324}
325
326// Enable or disable overwriting of the kernel trace buffers. Disabling this
327// will cause tracing to stop once the trace buffers have filled up.
328static bool setTraceOverwriteEnable(bool enable)
329{
330 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
331}
332
333// Enable or disable kernel tracing.
334static bool setTracingEnabled(bool enable)
335{
336 return setKernelOptionEnable(k_tracingOnPath, enable);
337}
338
339// Clear the contents of the kernel trace.
340static bool clearTrace()
341{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700342 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800343}
344
345// Set the size of the kernel's trace buffer in kilobytes.
346static bool setTraceBufferSizeKB(int size)
347{
348 char str[32] = "1";
349 int len;
350 if (size < 1) {
351 size = 1;
352 }
353 snprintf(str, 32, "%d", size);
354 return writeStr(k_traceBufferSizePath, str);
355}
356
Colin Crossb1ce49b2014-08-20 14:28:47 -0700357// Read the trace_clock sysfs file and return true if it matches the requested
358// value. The trace_clock file format is:
359// local [global] counter uptime perf
360static bool isTraceClock(const char *mode)
361{
362 int fd = open(k_traceClockPath, O_RDONLY);
363 if (fd == -1) {
364 fprintf(stderr, "error opening %s: %s (%d)\n", k_traceClockPath,
365 strerror(errno), errno);
366 return false;
367 }
368
369 char buf[4097];
370 ssize_t n = read(fd, buf, 4096);
371 close(fd);
372 if (n == -1) {
373 fprintf(stderr, "error reading %s: %s (%d)\n", k_traceClockPath,
374 strerror(errno), errno);
375 return false;
376 }
377 buf[n] = '\0';
378
379 char *start = strchr(buf, '[');
380 if (start == NULL) {
381 return false;
382 }
383 start++;
384
385 char *end = strchr(start, ']');
386 if (end == NULL) {
387 return false;
388 }
389 *end = '\0';
390
391 return strcmp(mode, start) == 0;
392}
393
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800394// Enable or disable the kernel's use of the global clock. Disabling the global
395// clock will result in the kernel using a per-CPU local clock.
Colin Crossb1ce49b2014-08-20 14:28:47 -0700396// Any write to the trace_clock sysfs file will reset the buffer, so only
397// update it if the requested value is not the current value.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800398static bool setGlobalClockEnable(bool enable)
399{
Colin Crossb1ce49b2014-08-20 14:28:47 -0700400 const char *clock = enable ? "global" : "local";
401
402 if (isTraceClock(clock)) {
403 return true;
404 }
405
406 return writeStr(k_traceClockPath, clock);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800407}
408
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700409static bool setPrintTgidEnableIfPresent(bool enable)
410{
411 if (fileExists(k_printTgidPath)) {
412 return setKernelOptionEnable(k_printTgidPath, enable);
413 }
414 return true;
415}
416
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800417// Poke all the binder-enabled processes in the system to get them to re-read
418// their system properties.
419static bool pokeBinderServices()
420{
421 sp<IServiceManager> sm = defaultServiceManager();
422 Vector<String16> services = sm->listServices();
423 for (size_t i = 0; i < services.size(); i++) {
424 sp<IBinder> obj = sm->checkService(services[i]);
425 if (obj != NULL) {
426 Parcel data;
427 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
428 NULL, 0) != OK) {
429 if (false) {
430 // XXX: For some reason this fails on tablets trying to
431 // poke the "phone" service. It's not clear whether some
432 // are expected to fail.
433 String8 svc(services[i]);
434 fprintf(stderr, "error poking binder service %s\n",
435 svc.string());
436 return false;
437 }
438 }
439 }
440 }
441 return true;
442}
443
444// Set the trace tags that userland tracing uses, and poke the running
445// processes to pick up the new value.
446static bool setTagsProperty(uint64_t tags)
447{
448 char buf[64];
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700449 snprintf(buf, 64, "%#" PRIx64, tags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800450 if (property_set(k_traceTagsProperty, buf) < 0) {
451 fprintf(stderr, "error setting trace tags system property\n");
452 return false;
453 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700454 return true;
455}
456
457// Set the system property that indicates which apps should perform
458// application-level tracing.
459static bool setAppCmdlineProperty(const char* cmdline)
460{
461 if (property_set(k_traceAppCmdlineProperty, cmdline) < 0) {
462 fprintf(stderr, "error setting trace app system property\n");
463 return false;
464 }
465 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800466}
467
468// Disable all /sys/ enable files.
469static bool disableKernelTraceEvents() {
470 bool ok = true;
471 for (int i = 0; i < NELEM(k_categories); i++) {
472 const TracingCategory &c = k_categories[i];
473 for (int j = 0; j < MAX_SYS_FILES; j++) {
474 const char* path = c.sysfiles[j].path;
475 if (path != NULL && fileIsWritable(path)) {
476 ok &= setKernelOptionEnable(path, false);
477 }
478 }
479 }
480 return ok;
481}
482
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700483// Verify that the comma separated list of functions are being traced by the
484// kernel.
485static bool verifyKernelTraceFuncs(const char* funcs)
486{
487 int fd = open(k_ftraceFilterPath, O_RDONLY);
488 if (fd == -1) {
489 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
490 strerror(errno), errno);
491 return false;
492 }
493
494 char buf[4097];
495 ssize_t n = read(fd, buf, 4096);
496 close(fd);
497 if (n == -1) {
498 fprintf(stderr, "error reading %s: %s (%d)\n", k_ftraceFilterPath,
499 strerror(errno), errno);
500 return false;
501 }
502
503 buf[n] = '\0';
504 String8 funcList = String8::format("\n%s", buf);
505
506 // Make sure that every function listed in funcs is in the list we just
507 // read from the kernel.
508 bool ok = true;
509 char* myFuncs = strdup(funcs);
510 char* func = strtok(myFuncs, ",");
511 while (func) {
512 String8 fancyFunc = String8::format("\n%s\n", func);
513 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
514 if (!found || func[0] == '\0') {
515 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
516 "to trace.\n", func);
517 ok = false;
518 }
519 func = strtok(NULL, ",");
520 }
521 free(myFuncs);
522
523 return ok;
524}
525
526// Set the comma separated list of functions that the kernel is to trace.
527static bool setKernelTraceFuncs(const char* funcs)
528{
529 bool ok = true;
530
531 if (funcs == NULL || funcs[0] == '\0') {
532 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700533 if (fileIsWritable(k_currentTracerPath)) {
534 ok &= writeStr(k_currentTracerPath, "nop");
535 }
536 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700537 ok &= truncateFile(k_ftraceFilterPath);
538 }
539 } else {
540 // Enable kernel function tracing.
541 ok &= writeStr(k_currentTracerPath, "function_graph");
542 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
543 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
544 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
545 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
546
547 // Set the requested filter functions.
548 ok &= truncateFile(k_ftraceFilterPath);
549 char* myFuncs = strdup(funcs);
550 char* func = strtok(myFuncs, ",");
551 while (func) {
552 ok &= appendStr(k_ftraceFilterPath, func);
553 func = strtok(NULL, ",");
554 }
555 free(myFuncs);
556
557 // Verify that the set functions are being traced.
558 if (ok) {
559 ok &= verifyKernelTraceFuncs(funcs);
560 }
561 }
562
563 return ok;
564}
565
566// Set all the kernel tracing settings to the desired state for this trace
567// capture.
568static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800569{
570 bool ok = true;
571
572 // Set up the tracing options.
573 ok &= setTraceOverwriteEnable(g_traceOverwrite);
574 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
575 ok &= setGlobalClockEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700576 ok &= setPrintTgidEnableIfPresent(true);
577 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800578
579 // Set up the tags property.
580 uint64_t tags = 0;
581 for (int i = 0; i < NELEM(k_categories); i++) {
582 if (g_categoryEnables[i]) {
583 const TracingCategory &c = k_categories[i];
584 tags |= c.tags;
585 }
586 }
587 ok &= setTagsProperty(tags);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700588 ok &= setAppCmdlineProperty(g_debugAppCmdLine);
589 ok &= pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800590
591 // Disable all the sysfs enables. This is done as a separate loop from
592 // the enables to allow the same enable to exist in multiple categories.
593 ok &= disableKernelTraceEvents();
594
595 // Enable all the sysfs enables that are in an enabled category.
596 for (int i = 0; i < NELEM(k_categories); i++) {
597 if (g_categoryEnables[i]) {
598 const TracingCategory &c = k_categories[i];
599 for (int j = 0; j < MAX_SYS_FILES; j++) {
600 const char* path = c.sysfiles[j].path;
601 bool required = c.sysfiles[j].required == REQ;
602 if (path != NULL) {
603 if (fileIsWritable(path)) {
604 ok &= setKernelOptionEnable(path, true);
605 } else if (required) {
606 fprintf(stderr, "error writing file %s\n", path);
607 ok = false;
608 }
609 }
610 }
611 }
612 }
613
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800614 return ok;
615}
616
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700617// Reset all the kernel tracing settings to their default state.
618static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800619{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800620 // Disable all tracing that we're able to.
621 disableKernelTraceEvents();
622
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700623 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800624 setTagsProperty(0);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700625 setAppCmdlineProperty("");
626 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800627
628 // Set the options back to their defaults.
629 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700630 setTraceBufferSizeKB(1);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800631 setGlobalClockEnable(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700632 setPrintTgidEnableIfPresent(false);
633 setKernelTraceFuncs(NULL);
634}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800635
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700636
637// Enable tracing in the kernel.
638static bool startTrace()
639{
640 return setTracingEnabled(true);
641}
642
643// Disable tracing in the kernel.
644static void stopTrace()
645{
John Reck469a1942015-03-26 15:31:35 -0700646 writeClockSyncMarker();
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700647 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800648}
649
650// Read the current kernel trace and write it to stdout.
651static void dumpTrace()
652{
653 int traceFD = open(k_tracePath, O_RDWR);
654 if (traceFD == -1) {
655 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
656 strerror(errno), errno);
657 return;
658 }
659
660 if (g_compress) {
661 z_stream zs;
662 uint8_t *in, *out;
663 int result, flush;
664
Elliott Hughes3da5d232015-01-25 08:35:20 -0800665 memset(&zs, 0, sizeof(zs));
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800666 result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
667 if (result != Z_OK) {
668 fprintf(stderr, "error initializing zlib: %d\n", result);
669 close(traceFD);
670 return;
671 }
672
673 const size_t bufSize = 64*1024;
674 in = (uint8_t*)malloc(bufSize);
675 out = (uint8_t*)malloc(bufSize);
676 flush = Z_NO_FLUSH;
677
678 zs.next_out = out;
679 zs.avail_out = bufSize;
680
681 do {
682
683 if (zs.avail_in == 0) {
684 // More input is needed.
685 result = read(traceFD, in, bufSize);
686 if (result < 0) {
687 fprintf(stderr, "error reading trace: %s (%d)\n",
688 strerror(errno), errno);
689 result = Z_STREAM_END;
690 break;
691 } else if (result == 0) {
692 flush = Z_FINISH;
693 } else {
694 zs.next_in = in;
695 zs.avail_in = result;
696 }
697 }
698
699 if (zs.avail_out == 0) {
700 // Need to write the output.
701 result = write(STDOUT_FILENO, out, bufSize);
702 if ((size_t)result < bufSize) {
703 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
704 strerror(errno), errno);
705 result = Z_STREAM_END; // skip deflate error message
706 zs.avail_out = bufSize; // skip the final write
707 break;
708 }
709 zs.next_out = out;
710 zs.avail_out = bufSize;
711 }
712
713 } while ((result = deflate(&zs, flush)) == Z_OK);
714
715 if (result != Z_STREAM_END) {
716 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
717 }
718
719 if (zs.avail_out < bufSize) {
720 size_t bytes = bufSize - zs.avail_out;
721 result = write(STDOUT_FILENO, out, bytes);
722 if ((size_t)result < bytes) {
723 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
724 strerror(errno), errno);
725 }
726 }
727
728 result = deflateEnd(&zs);
729 if (result != Z_OK) {
730 fprintf(stderr, "error cleaning up zlib: %d\n", result);
731 }
732
733 free(in);
734 free(out);
735 } else {
736 ssize_t sent = 0;
737 while ((sent = sendfile(STDOUT_FILENO, traceFD, NULL, 64*1024*1024)) > 0);
738 if (sent == -1) {
739 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
740 errno);
741 }
742 }
743
744 close(traceFD);
745}
746
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700747static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800748{
749 if (!g_nohup) {
750 g_traceAborted = true;
751 }
752}
753
754static void registerSigHandler()
755{
756 struct sigaction sa;
757 sigemptyset(&sa.sa_mask);
758 sa.sa_flags = 0;
759 sa.sa_handler = handleSignal;
760 sigaction(SIGHUP, &sa, NULL);
761 sigaction(SIGINT, &sa, NULL);
762 sigaction(SIGQUIT, &sa, NULL);
763 sigaction(SIGTERM, &sa, NULL);
764}
765
766static bool setCategoryEnable(const char* name, bool enable)
767{
768 for (int i = 0; i < NELEM(k_categories); i++) {
769 const TracingCategory& c = k_categories[i];
770 if (strcmp(name, c.name) == 0) {
771 if (isCategorySupported(c)) {
772 g_categoryEnables[i] = enable;
773 return true;
774 } else {
775 if (isCategorySupportedForRoot(c)) {
776 fprintf(stderr, "error: category \"%s\" requires root "
777 "privileges.\n", name);
778 } else {
779 fprintf(stderr, "error: category \"%s\" is not supported "
780 "on this device.\n", name);
781 }
782 return false;
783 }
784 }
785 }
786 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
787 return false;
788}
789
790static void listSupportedCategories()
791{
792 for (int i = 0; i < NELEM(k_categories); i++) {
793 const TracingCategory& c = k_categories[i];
794 if (isCategorySupported(c)) {
795 printf(" %10s - %s\n", c.name, c.longname);
796 }
797 }
798}
799
800// Print the command usage help to stderr.
801static void showHelp(const char *cmd)
802{
803 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
804 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700805 " -a appname enable app-level tracing for a comma "
806 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800807 " -b N use a trace buffer size of N KB\n"
808 " -c trace into a circular buffer\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700809 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800810 " -n ignore signals\n"
811 " -s N sleep for N seconds before tracing [default 0]\n"
812 " -t N trace for N seconds [defualt 5]\n"
813 " -z compress the trace dump\n"
814 " --async_start start circular trace and return immediatly\n"
815 " --async_dump dump the current contents of circular trace buffer\n"
816 " --async_stop stop tracing and dump the current contents of circular\n"
817 " trace buffer\n"
Jamie Gennis92573f12012-12-07 16:29:03 -0800818 " --list_categories\n"
819 " list the available tracing categories\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800820 );
821}
822
823int main(int argc, char **argv)
824{
825 bool async = false;
826 bool traceStart = true;
827 bool traceStop = true;
828 bool traceDump = true;
829
830 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
831 showHelp(argv[0]);
832 exit(0);
833 }
834
835 for (;;) {
836 int ret;
837 int option_index = 0;
838 static struct option long_options[] = {
839 {"async_start", no_argument, 0, 0 },
840 {"async_stop", no_argument, 0, 0 },
841 {"async_dump", no_argument, 0, 0 },
842 {"list_categories", no_argument, 0, 0 },
843 { 0, 0, 0, 0 }
844 };
845
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700846 ret = getopt_long(argc, argv, "a:b:ck:ns:t:z",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800847 long_options, &option_index);
848
849 if (ret < 0) {
850 for (int i = optind; i < argc; i++) {
851 if (!setCategoryEnable(argv[i], true)) {
852 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
853 exit(1);
854 }
855 }
856 break;
857 }
858
859 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700860 case 'a':
861 g_debugAppCmdLine = optarg;
862 break;
863
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800864 case 'b':
865 g_traceBufferSizeKB = atoi(optarg);
866 break;
867
868 case 'c':
869 g_traceOverwrite = true;
870 break;
871
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700872 case 'k':
873 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700874 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700875
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800876 case 'n':
877 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700878 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800879
880 case 's':
881 g_initialSleepSecs = atoi(optarg);
882 break;
883
884 case 't':
885 g_traceDurationSeconds = atoi(optarg);
886 break;
887
888 case 'z':
889 g_compress = true;
890 break;
891
892 case 0:
893 if (!strcmp(long_options[option_index].name, "async_start")) {
894 async = true;
895 traceStop = false;
896 traceDump = false;
897 g_traceOverwrite = true;
898 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
899 async = true;
900 traceStop = false;
901 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
902 async = true;
903 traceStart = false;
904 traceStop = false;
905 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
906 listSupportedCategories();
907 exit(0);
908 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700909 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800910
911 default:
912 fprintf(stderr, "\n");
913 showHelp(argv[0]);
914 exit(-1);
915 break;
916 }
917 }
918
919 registerSigHandler();
920
921 if (g_initialSleepSecs > 0) {
922 sleep(g_initialSleepSecs);
923 }
924
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700925 bool ok = true;
926 ok &= setUpTrace();
927 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800928
929 if (ok && traceStart) {
930 printf("capturing trace...");
931 fflush(stdout);
932
933 // We clear the trace after starting it because tracing gets enabled for
934 // each CPU individually in the kernel. Having the beginning of the trace
935 // contain entries from only one CPU can cause "begin" entries without a
936 // matching "end" entry to show up if a task gets migrated from one CPU to
937 // another.
938 ok = clearTrace();
939
940 if (ok && !async) {
941 // Sleep to allow the trace to be captured.
942 struct timespec timeLeft;
943 timeLeft.tv_sec = g_traceDurationSeconds;
944 timeLeft.tv_nsec = 0;
945 do {
946 if (g_traceAborted) {
947 break;
948 }
949 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
950 }
951 }
952
953 // Stop the trace and restore the default settings.
954 if (traceStop)
955 stopTrace();
956
957 if (ok && traceDump) {
958 if (!g_traceAborted) {
959 printf(" done\nTRACE:\n");
960 fflush(stdout);
961 dumpTrace();
962 } else {
963 printf("\ntrace aborted.\n");
964 fflush(stdout);
965 }
966 clearTrace();
967 } else if (!ok) {
968 fprintf(stderr, "unable to start tracing\n");
969 }
970
971 // Reset the trace buffer size to 1.
972 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700973 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800974
975 return g_traceAborted ? 1 : 0;
976}