blob: 099c3df4700f92207f8ec883e40e9c9fa9b5bd69 [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>
26#include <sys/sendfile.h>
27#include <time.h>
28#include <zlib.h>
29
30#include <binder/IBinder.h>
31#include <binder/IServiceManager.h>
32#include <binder/Parcel.h>
33
34#include <cutils/properties.h>
35
36#include <utils/String8.h>
37#include <utils/Trace.h>
38
39using namespace android;
40
41#define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0])))
42
Mohamad Ayyash26dbcbe2014-04-08 15:24:11 -070043enum { MAX_SYS_FILES = 10 };
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080044
45const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
Jamie Gennisf7f29c82013-03-27 15:50:58 -070046const char* k_traceAppCmdlineProperty = "debug.atrace.app_cmdlines";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080047
48typedef enum { OPT, REQ } requiredness ;
49
50struct TracingCategory {
51 // The name identifying the category.
52 const char* name;
53
54 // A longer description of the category.
55 const char* longname;
56
57 // The userland tracing tags that the category enables.
58 uint64_t tags;
59
60 // The fname==NULL terminated list of /sys/ files that the category
61 // enables.
62 struct {
63 // Whether the file must be writable in order to enable the tracing
64 // category.
65 requiredness required;
66
67 // The path to the enable file.
68 const char* path;
69 } sysfiles[MAX_SYS_FILES];
70};
71
72/* Tracing categories */
73static const TracingCategory k_categories[] = {
Jamie Gennisb2a89e32013-03-11 19:37:53 -070074 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, { } },
75 { "input", "Input", ATRACE_TAG_INPUT, { } },
76 { "view", "View System", ATRACE_TAG_VIEW, { } },
77 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
78 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
79 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
80 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
81 { "video", "Video", ATRACE_TAG_VIDEO, { } },
82 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
83 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
Dianne Hackborn9380d782013-04-12 14:52:35 -070084 { "res", "Resource Loading", ATRACE_TAG_RESOURCES, { } },
Jamie Genniseff2e8d2013-05-07 15:20:39 -070085 { "dalvik", "Dalvik VM", ATRACE_TAG_DALVIK, { } },
Tim Murrayf0f28412013-05-23 14:39:42 -070086 { "rs", "RenderScript", ATRACE_TAG_RS, { } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070087 { "sched", "CPU Scheduling", 0, {
88 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_switch/enable" },
89 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_wakeup/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080090 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070091 { "freq", "CPU Frequency", 0, {
92 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_frequency/enable" },
93 { OPT, "/sys/kernel/debug/tracing/events/power/clock_set_rate/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080094 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070095 { "membus", "Memory Bus Utilization", 0, {
96 { REQ, "/sys/kernel/debug/tracing/events/memory_bus/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -080097 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -070098 { "idle", "CPU Idle", 0, {
99 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_idle/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800100 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700101 { "disk", "Disk I/O", 0, {
Mohamad Ayyash26dbcbe2014-04-08 15:24:11 -0700102 { REQ, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_enter/enable" },
103 { REQ, "/sys/kernel/debug/tracing/events/f2fs/f2fs_sync_file_exit/enable" },
104 { REQ, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_begin/enable" },
105 { REQ, "/sys/kernel/debug/tracing/events/f2fs/f2fs_write_end/enable" },
106 { REQ, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_begin/enable" },
107 { REQ, "/sys/kernel/debug/tracing/events/ext4/ext4_da_write_end/enable" },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700108 { REQ, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable" },
109 { REQ, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable" },
110 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" },
111 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800112 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700113 { "mmc", "eMMC commands", 0, {
114 { REQ, "/sys/kernel/debug/tracing/events/mmc/enable" },
115 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700116 { "load", "CPU Load", 0, {
117 { REQ, "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800118 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700119 { "sync", "Synchronization", 0, {
120 { REQ, "/sys/kernel/debug/tracing/events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800121 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700122 { "workq", "Kernel Workqueues", 0, {
123 { REQ, "/sys/kernel/debug/tracing/events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800124 } },
125};
126
127/* Command line options */
128static int g_traceDurationSeconds = 5;
129static bool g_traceOverwrite = false;
130static int g_traceBufferSizeKB = 2048;
131static bool g_compress = false;
132static bool g_nohup = false;
133static int g_initialSleepSecs = 0;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700134static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700135static const char* g_debugAppCmdLine = "";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800136
137/* Global state */
138static bool g_traceAborted = false;
139static bool g_categoryEnables[NELEM(k_categories)] = {};
140
141/* Sys file paths */
142static const char* k_traceClockPath =
143 "/sys/kernel/debug/tracing/trace_clock";
144
145static const char* k_traceBufferSizePath =
146 "/sys/kernel/debug/tracing/buffer_size_kb";
147
148static const char* k_tracingOverwriteEnablePath =
149 "/sys/kernel/debug/tracing/options/overwrite";
150
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700151static const char* k_currentTracerPath =
152 "/sys/kernel/debug/tracing/current_tracer";
153
154static const char* k_printTgidPath =
155 "/sys/kernel/debug/tracing/options/print-tgid";
156
157static const char* k_funcgraphAbsTimePath =
158 "/sys/kernel/debug/tracing/options/funcgraph-abstime";
159
160static const char* k_funcgraphCpuPath =
161 "/sys/kernel/debug/tracing/options/funcgraph-cpu";
162
163static const char* k_funcgraphProcPath =
164 "/sys/kernel/debug/tracing/options/funcgraph-proc";
165
166static const char* k_funcgraphFlatPath =
167 "/sys/kernel/debug/tracing/options/funcgraph-flat";
168
169static const char* k_funcgraphDurationPath =
170 "/sys/kernel/debug/tracing/options/funcgraph-duration";
171
172static const char* k_ftraceFilterPath =
173 "/sys/kernel/debug/tracing/set_ftrace_filter";
174
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800175static const char* k_tracingOnPath =
176 "/sys/kernel/debug/tracing/tracing_on";
177
178static const char* k_tracePath =
179 "/sys/kernel/debug/tracing/trace";
180
181// Check whether a file exists.
182static bool fileExists(const char* filename) {
183 return access(filename, F_OK) != -1;
184}
185
186// Check whether a file is writable.
187static bool fileIsWritable(const char* filename) {
188 return access(filename, W_OK) != -1;
189}
190
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700191// Truncate a file.
192static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800193{
Jamie Gennis43122e72013-03-21 14:06:31 -0700194 // This uses creat rather than truncate because some of the debug kernel
195 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
196 // calls to truncate, but they are cleared by calls to creat.
197 int traceFD = creat(path, 0);
198 if (traceFD == -1) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700199 fprintf(stderr, "error truncating %s: %s (%d)\n", path,
Jamie Gennis43122e72013-03-21 14:06:31 -0700200 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700201 return false;
202 }
203
Jamie Gennis43122e72013-03-21 14:06:31 -0700204 close(traceFD);
205
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700206 return true;
207}
208
209static bool _writeStr(const char* filename, const char* str, int flags)
210{
211 int fd = open(filename, flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800212 if (fd == -1) {
213 fprintf(stderr, "error opening %s: %s (%d)\n", filename,
214 strerror(errno), errno);
215 return false;
216 }
217
218 bool ok = true;
219 ssize_t len = strlen(str);
220 if (write(fd, str, len) != len) {
221 fprintf(stderr, "error writing to %s: %s (%d)\n", filename,
222 strerror(errno), errno);
223 ok = false;
224 }
225
226 close(fd);
227
228 return ok;
229}
230
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700231// Write a string to a file, returning true if the write was successful.
232static bool writeStr(const char* filename, const char* str)
233{
234 return _writeStr(filename, str, O_WRONLY);
235}
236
237// Append a string to a file, returning true if the write was successful.
238static bool appendStr(const char* filename, const char* str)
239{
240 return _writeStr(filename, str, O_APPEND|O_WRONLY);
241}
242
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800243// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
244// file.
245static bool setKernelOptionEnable(const char* filename, bool enable)
246{
247 return writeStr(filename, enable ? "1" : "0");
248}
249
250// Check whether the category is supported on the device with the current
251// rootness. A category is supported only if all its required /sys/ files are
252// writable and if enabling the category will enable one or more tracing tags
253// or /sys/ files.
254static bool isCategorySupported(const TracingCategory& category)
255{
256 bool ok = category.tags != 0;
257 for (int i = 0; i < MAX_SYS_FILES; i++) {
258 const char* path = category.sysfiles[i].path;
259 bool req = category.sysfiles[i].required == REQ;
260 if (path != NULL) {
261 if (req) {
262 if (!fileIsWritable(path)) {
263 return false;
264 } else {
265 ok = true;
266 }
267 } else {
268 ok |= fileIsWritable(path);
269 }
270 }
271 }
272 return ok;
273}
274
275// Check whether the category would be supported on the device if the user
276// were root. This function assumes that root is able to write to any file
277// that exists. It performs the same logic as isCategorySupported, but it
278// uses file existance rather than writability in the /sys/ file checks.
279static bool isCategorySupportedForRoot(const TracingCategory& category)
280{
281 bool ok = category.tags != 0;
282 for (int i = 0; i < MAX_SYS_FILES; i++) {
283 const char* path = category.sysfiles[i].path;
284 bool req = category.sysfiles[i].required == REQ;
285 if (path != NULL) {
286 if (req) {
287 if (!fileExists(path)) {
288 return false;
289 } else {
290 ok = true;
291 }
292 } else {
293 ok |= fileExists(path);
294 }
295 }
296 }
297 return ok;
298}
299
300// Enable or disable overwriting of the kernel trace buffers. Disabling this
301// will cause tracing to stop once the trace buffers have filled up.
302static bool setTraceOverwriteEnable(bool enable)
303{
304 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
305}
306
307// Enable or disable kernel tracing.
308static bool setTracingEnabled(bool enable)
309{
310 return setKernelOptionEnable(k_tracingOnPath, enable);
311}
312
313// Clear the contents of the kernel trace.
314static bool clearTrace()
315{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700316 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800317}
318
319// Set the size of the kernel's trace buffer in kilobytes.
320static bool setTraceBufferSizeKB(int size)
321{
322 char str[32] = "1";
323 int len;
324 if (size < 1) {
325 size = 1;
326 }
327 snprintf(str, 32, "%d", size);
328 return writeStr(k_traceBufferSizePath, str);
329}
330
331// Enable or disable the kernel's use of the global clock. Disabling the global
332// clock will result in the kernel using a per-CPU local clock.
333static bool setGlobalClockEnable(bool enable)
334{
335 return writeStr(k_traceClockPath, enable ? "global" : "local");
336}
337
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700338static bool setPrintTgidEnableIfPresent(bool enable)
339{
340 if (fileExists(k_printTgidPath)) {
341 return setKernelOptionEnable(k_printTgidPath, enable);
342 }
343 return true;
344}
345
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800346// Poke all the binder-enabled processes in the system to get them to re-read
347// their system properties.
348static bool pokeBinderServices()
349{
350 sp<IServiceManager> sm = defaultServiceManager();
351 Vector<String16> services = sm->listServices();
352 for (size_t i = 0; i < services.size(); i++) {
353 sp<IBinder> obj = sm->checkService(services[i]);
354 if (obj != NULL) {
355 Parcel data;
356 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
357 NULL, 0) != OK) {
358 if (false) {
359 // XXX: For some reason this fails on tablets trying to
360 // poke the "phone" service. It's not clear whether some
361 // are expected to fail.
362 String8 svc(services[i]);
363 fprintf(stderr, "error poking binder service %s\n",
364 svc.string());
365 return false;
366 }
367 }
368 }
369 }
370 return true;
371}
372
373// Set the trace tags that userland tracing uses, and poke the running
374// processes to pick up the new value.
375static bool setTagsProperty(uint64_t tags)
376{
377 char buf[64];
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700378 snprintf(buf, 64, "%#" PRIx64, tags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800379 if (property_set(k_traceTagsProperty, buf) < 0) {
380 fprintf(stderr, "error setting trace tags system property\n");
381 return false;
382 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700383 return true;
384}
385
386// Set the system property that indicates which apps should perform
387// application-level tracing.
388static bool setAppCmdlineProperty(const char* cmdline)
389{
390 if (property_set(k_traceAppCmdlineProperty, cmdline) < 0) {
391 fprintf(stderr, "error setting trace app system property\n");
392 return false;
393 }
394 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800395}
396
397// Disable all /sys/ enable files.
398static bool disableKernelTraceEvents() {
399 bool ok = true;
400 for (int i = 0; i < NELEM(k_categories); i++) {
401 const TracingCategory &c = k_categories[i];
402 for (int j = 0; j < MAX_SYS_FILES; j++) {
403 const char* path = c.sysfiles[j].path;
404 if (path != NULL && fileIsWritable(path)) {
405 ok &= setKernelOptionEnable(path, false);
406 }
407 }
408 }
409 return ok;
410}
411
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700412// Verify that the comma separated list of functions are being traced by the
413// kernel.
414static bool verifyKernelTraceFuncs(const char* funcs)
415{
416 int fd = open(k_ftraceFilterPath, O_RDONLY);
417 if (fd == -1) {
418 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
419 strerror(errno), errno);
420 return false;
421 }
422
423 char buf[4097];
424 ssize_t n = read(fd, buf, 4096);
425 close(fd);
426 if (n == -1) {
427 fprintf(stderr, "error reading %s: %s (%d)\n", k_ftraceFilterPath,
428 strerror(errno), errno);
429 return false;
430 }
431
432 buf[n] = '\0';
433 String8 funcList = String8::format("\n%s", buf);
434
435 // Make sure that every function listed in funcs is in the list we just
436 // read from the kernel.
437 bool ok = true;
438 char* myFuncs = strdup(funcs);
439 char* func = strtok(myFuncs, ",");
440 while (func) {
441 String8 fancyFunc = String8::format("\n%s\n", func);
442 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
443 if (!found || func[0] == '\0') {
444 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
445 "to trace.\n", func);
446 ok = false;
447 }
448 func = strtok(NULL, ",");
449 }
450 free(myFuncs);
451
452 return ok;
453}
454
455// Set the comma separated list of functions that the kernel is to trace.
456static bool setKernelTraceFuncs(const char* funcs)
457{
458 bool ok = true;
459
460 if (funcs == NULL || funcs[0] == '\0') {
461 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700462 if (fileIsWritable(k_currentTracerPath)) {
463 ok &= writeStr(k_currentTracerPath, "nop");
464 }
465 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700466 ok &= truncateFile(k_ftraceFilterPath);
467 }
468 } else {
469 // Enable kernel function tracing.
470 ok &= writeStr(k_currentTracerPath, "function_graph");
471 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
472 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
473 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
474 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
475
476 // Set the requested filter functions.
477 ok &= truncateFile(k_ftraceFilterPath);
478 char* myFuncs = strdup(funcs);
479 char* func = strtok(myFuncs, ",");
480 while (func) {
481 ok &= appendStr(k_ftraceFilterPath, func);
482 func = strtok(NULL, ",");
483 }
484 free(myFuncs);
485
486 // Verify that the set functions are being traced.
487 if (ok) {
488 ok &= verifyKernelTraceFuncs(funcs);
489 }
490 }
491
492 return ok;
493}
494
495// Set all the kernel tracing settings to the desired state for this trace
496// capture.
497static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800498{
499 bool ok = true;
500
501 // Set up the tracing options.
502 ok &= setTraceOverwriteEnable(g_traceOverwrite);
503 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
504 ok &= setGlobalClockEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700505 ok &= setPrintTgidEnableIfPresent(true);
506 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800507
508 // Set up the tags property.
509 uint64_t tags = 0;
510 for (int i = 0; i < NELEM(k_categories); i++) {
511 if (g_categoryEnables[i]) {
512 const TracingCategory &c = k_categories[i];
513 tags |= c.tags;
514 }
515 }
516 ok &= setTagsProperty(tags);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700517 ok &= setAppCmdlineProperty(g_debugAppCmdLine);
518 ok &= pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800519
520 // Disable all the sysfs enables. This is done as a separate loop from
521 // the enables to allow the same enable to exist in multiple categories.
522 ok &= disableKernelTraceEvents();
523
524 // Enable all the sysfs enables that are in an enabled category.
525 for (int i = 0; i < NELEM(k_categories); i++) {
526 if (g_categoryEnables[i]) {
527 const TracingCategory &c = k_categories[i];
528 for (int j = 0; j < MAX_SYS_FILES; j++) {
529 const char* path = c.sysfiles[j].path;
530 bool required = c.sysfiles[j].required == REQ;
531 if (path != NULL) {
532 if (fileIsWritable(path)) {
533 ok &= setKernelOptionEnable(path, true);
534 } else if (required) {
535 fprintf(stderr, "error writing file %s\n", path);
536 ok = false;
537 }
538 }
539 }
540 }
541 }
542
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800543 return ok;
544}
545
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700546// Reset all the kernel tracing settings to their default state.
547static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800548{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800549 // Disable all tracing that we're able to.
550 disableKernelTraceEvents();
551
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700552 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800553 setTagsProperty(0);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700554 setAppCmdlineProperty("");
555 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800556
557 // Set the options back to their defaults.
558 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700559 setTraceBufferSizeKB(1);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800560 setGlobalClockEnable(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700561 setPrintTgidEnableIfPresent(false);
562 setKernelTraceFuncs(NULL);
563}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800564
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700565
566// Enable tracing in the kernel.
567static bool startTrace()
568{
569 return setTracingEnabled(true);
570}
571
572// Disable tracing in the kernel.
573static void stopTrace()
574{
575 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800576}
577
578// Read the current kernel trace and write it to stdout.
579static void dumpTrace()
580{
581 int traceFD = open(k_tracePath, O_RDWR);
582 if (traceFD == -1) {
583 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
584 strerror(errno), errno);
585 return;
586 }
587
588 if (g_compress) {
589 z_stream zs;
590 uint8_t *in, *out;
591 int result, flush;
592
593 bzero(&zs, sizeof(zs));
594 result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
595 if (result != Z_OK) {
596 fprintf(stderr, "error initializing zlib: %d\n", result);
597 close(traceFD);
598 return;
599 }
600
601 const size_t bufSize = 64*1024;
602 in = (uint8_t*)malloc(bufSize);
603 out = (uint8_t*)malloc(bufSize);
604 flush = Z_NO_FLUSH;
605
606 zs.next_out = out;
607 zs.avail_out = bufSize;
608
609 do {
610
611 if (zs.avail_in == 0) {
612 // More input is needed.
613 result = read(traceFD, in, bufSize);
614 if (result < 0) {
615 fprintf(stderr, "error reading trace: %s (%d)\n",
616 strerror(errno), errno);
617 result = Z_STREAM_END;
618 break;
619 } else if (result == 0) {
620 flush = Z_FINISH;
621 } else {
622 zs.next_in = in;
623 zs.avail_in = result;
624 }
625 }
626
627 if (zs.avail_out == 0) {
628 // Need to write the output.
629 result = write(STDOUT_FILENO, out, bufSize);
630 if ((size_t)result < bufSize) {
631 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
632 strerror(errno), errno);
633 result = Z_STREAM_END; // skip deflate error message
634 zs.avail_out = bufSize; // skip the final write
635 break;
636 }
637 zs.next_out = out;
638 zs.avail_out = bufSize;
639 }
640
641 } while ((result = deflate(&zs, flush)) == Z_OK);
642
643 if (result != Z_STREAM_END) {
644 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
645 }
646
647 if (zs.avail_out < bufSize) {
648 size_t bytes = bufSize - zs.avail_out;
649 result = write(STDOUT_FILENO, out, bytes);
650 if ((size_t)result < bytes) {
651 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
652 strerror(errno), errno);
653 }
654 }
655
656 result = deflateEnd(&zs);
657 if (result != Z_OK) {
658 fprintf(stderr, "error cleaning up zlib: %d\n", result);
659 }
660
661 free(in);
662 free(out);
663 } else {
664 ssize_t sent = 0;
665 while ((sent = sendfile(STDOUT_FILENO, traceFD, NULL, 64*1024*1024)) > 0);
666 if (sent == -1) {
667 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
668 errno);
669 }
670 }
671
672 close(traceFD);
673}
674
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700675static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800676{
677 if (!g_nohup) {
678 g_traceAborted = true;
679 }
680}
681
682static void registerSigHandler()
683{
684 struct sigaction sa;
685 sigemptyset(&sa.sa_mask);
686 sa.sa_flags = 0;
687 sa.sa_handler = handleSignal;
688 sigaction(SIGHUP, &sa, NULL);
689 sigaction(SIGINT, &sa, NULL);
690 sigaction(SIGQUIT, &sa, NULL);
691 sigaction(SIGTERM, &sa, NULL);
692}
693
694static bool setCategoryEnable(const char* name, bool enable)
695{
696 for (int i = 0; i < NELEM(k_categories); i++) {
697 const TracingCategory& c = k_categories[i];
698 if (strcmp(name, c.name) == 0) {
699 if (isCategorySupported(c)) {
700 g_categoryEnables[i] = enable;
701 return true;
702 } else {
703 if (isCategorySupportedForRoot(c)) {
704 fprintf(stderr, "error: category \"%s\" requires root "
705 "privileges.\n", name);
706 } else {
707 fprintf(stderr, "error: category \"%s\" is not supported "
708 "on this device.\n", name);
709 }
710 return false;
711 }
712 }
713 }
714 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
715 return false;
716}
717
718static void listSupportedCategories()
719{
720 for (int i = 0; i < NELEM(k_categories); i++) {
721 const TracingCategory& c = k_categories[i];
722 if (isCategorySupported(c)) {
723 printf(" %10s - %s\n", c.name, c.longname);
724 }
725 }
726}
727
728// Print the command usage help to stderr.
729static void showHelp(const char *cmd)
730{
731 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
732 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700733 " -a appname enable app-level tracing for a comma "
734 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800735 " -b N use a trace buffer size of N KB\n"
736 " -c trace into a circular buffer\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700737 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800738 " -n ignore signals\n"
739 " -s N sleep for N seconds before tracing [default 0]\n"
740 " -t N trace for N seconds [defualt 5]\n"
741 " -z compress the trace dump\n"
742 " --async_start start circular trace and return immediatly\n"
743 " --async_dump dump the current contents of circular trace buffer\n"
744 " --async_stop stop tracing and dump the current contents of circular\n"
745 " trace buffer\n"
Jamie Gennis92573f12012-12-07 16:29:03 -0800746 " --list_categories\n"
747 " list the available tracing categories\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800748 );
749}
750
751int main(int argc, char **argv)
752{
753 bool async = false;
754 bool traceStart = true;
755 bool traceStop = true;
756 bool traceDump = true;
757
758 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
759 showHelp(argv[0]);
760 exit(0);
761 }
762
763 for (;;) {
764 int ret;
765 int option_index = 0;
766 static struct option long_options[] = {
767 {"async_start", no_argument, 0, 0 },
768 {"async_stop", no_argument, 0, 0 },
769 {"async_dump", no_argument, 0, 0 },
770 {"list_categories", no_argument, 0, 0 },
771 { 0, 0, 0, 0 }
772 };
773
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700774 ret = getopt_long(argc, argv, "a:b:ck:ns:t:z",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800775 long_options, &option_index);
776
777 if (ret < 0) {
778 for (int i = optind; i < argc; i++) {
779 if (!setCategoryEnable(argv[i], true)) {
780 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
781 exit(1);
782 }
783 }
784 break;
785 }
786
787 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700788 case 'a':
789 g_debugAppCmdLine = optarg;
790 break;
791
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800792 case 'b':
793 g_traceBufferSizeKB = atoi(optarg);
794 break;
795
796 case 'c':
797 g_traceOverwrite = true;
798 break;
799
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700800 case 'k':
801 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700802 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700803
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800804 case 'n':
805 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700806 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800807
808 case 's':
809 g_initialSleepSecs = atoi(optarg);
810 break;
811
812 case 't':
813 g_traceDurationSeconds = atoi(optarg);
814 break;
815
816 case 'z':
817 g_compress = true;
818 break;
819
820 case 0:
821 if (!strcmp(long_options[option_index].name, "async_start")) {
822 async = true;
823 traceStop = false;
824 traceDump = false;
825 g_traceOverwrite = true;
826 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
827 async = true;
828 traceStop = false;
829 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
830 async = true;
831 traceStart = false;
832 traceStop = false;
833 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
834 listSupportedCategories();
835 exit(0);
836 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700837 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800838
839 default:
840 fprintf(stderr, "\n");
841 showHelp(argv[0]);
842 exit(-1);
843 break;
844 }
845 }
846
847 registerSigHandler();
848
849 if (g_initialSleepSecs > 0) {
850 sleep(g_initialSleepSecs);
851 }
852
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700853 bool ok = true;
854 ok &= setUpTrace();
855 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800856
857 if (ok && traceStart) {
858 printf("capturing trace...");
859 fflush(stdout);
860
861 // We clear the trace after starting it because tracing gets enabled for
862 // each CPU individually in the kernel. Having the beginning of the trace
863 // contain entries from only one CPU can cause "begin" entries without a
864 // matching "end" entry to show up if a task gets migrated from one CPU to
865 // another.
866 ok = clearTrace();
867
868 if (ok && !async) {
869 // Sleep to allow the trace to be captured.
870 struct timespec timeLeft;
871 timeLeft.tv_sec = g_traceDurationSeconds;
872 timeLeft.tv_nsec = 0;
873 do {
874 if (g_traceAborted) {
875 break;
876 }
877 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
878 }
879 }
880
881 // Stop the trace and restore the default settings.
882 if (traceStop)
883 stopTrace();
884
885 if (ok && traceDump) {
886 if (!g_traceAborted) {
887 printf(" done\nTRACE:\n");
888 fflush(stdout);
889 dumpTrace();
890 } else {
891 printf("\ntrace aborted.\n");
892 fflush(stdout);
893 }
894 clearTrace();
895 } else if (!ok) {
896 fprintf(stderr, "unable to start tracing\n");
897 }
898
899 // Reset the trace buffer size to 1.
900 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700901 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800902
903 return g_traceAborted ? 1 : 0;
904}