blob: 34dc9fef8d21ad1f2cef742a1d80f62cc578e1d0 [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
43enum { MAX_SYS_FILES = 8 };
44
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, {
102 { REQ, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable" },
103 { REQ, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable" },
104 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" },
105 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800106 } },
Ken Sumralld3fa5612013-07-03 12:32:03 -0700107 { "mmc", "eMMC commands", 0, {
108 { REQ, "/sys/kernel/debug/tracing/events/mmc/enable" },
109 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700110 { "load", "CPU Load", 0, {
111 { REQ, "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800112 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700113 { "sync", "Synchronization", 0, {
114 { REQ, "/sys/kernel/debug/tracing/events/sync/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800115 } },
Jamie Gennisb2a89e32013-03-11 19:37:53 -0700116 { "workq", "Kernel Workqueues", 0, {
117 { REQ, "/sys/kernel/debug/tracing/events/workqueue/enable" },
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800118 } },
119};
120
121/* Command line options */
122static int g_traceDurationSeconds = 5;
123static bool g_traceOverwrite = false;
124static int g_traceBufferSizeKB = 2048;
125static bool g_compress = false;
126static bool g_nohup = false;
127static int g_initialSleepSecs = 0;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700128static const char* g_kernelTraceFuncs = NULL;
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700129static const char* g_debugAppCmdLine = "";
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800130
131/* Global state */
132static bool g_traceAborted = false;
133static bool g_categoryEnables[NELEM(k_categories)] = {};
134
135/* Sys file paths */
136static const char* k_traceClockPath =
137 "/sys/kernel/debug/tracing/trace_clock";
138
139static const char* k_traceBufferSizePath =
140 "/sys/kernel/debug/tracing/buffer_size_kb";
141
142static const char* k_tracingOverwriteEnablePath =
143 "/sys/kernel/debug/tracing/options/overwrite";
144
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700145static const char* k_currentTracerPath =
146 "/sys/kernel/debug/tracing/current_tracer";
147
148static const char* k_printTgidPath =
149 "/sys/kernel/debug/tracing/options/print-tgid";
150
151static const char* k_funcgraphAbsTimePath =
152 "/sys/kernel/debug/tracing/options/funcgraph-abstime";
153
154static const char* k_funcgraphCpuPath =
155 "/sys/kernel/debug/tracing/options/funcgraph-cpu";
156
157static const char* k_funcgraphProcPath =
158 "/sys/kernel/debug/tracing/options/funcgraph-proc";
159
160static const char* k_funcgraphFlatPath =
161 "/sys/kernel/debug/tracing/options/funcgraph-flat";
162
163static const char* k_funcgraphDurationPath =
164 "/sys/kernel/debug/tracing/options/funcgraph-duration";
165
166static const char* k_ftraceFilterPath =
167 "/sys/kernel/debug/tracing/set_ftrace_filter";
168
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800169static const char* k_tracingOnPath =
170 "/sys/kernel/debug/tracing/tracing_on";
171
172static const char* k_tracePath =
173 "/sys/kernel/debug/tracing/trace";
174
175// Check whether a file exists.
176static bool fileExists(const char* filename) {
177 return access(filename, F_OK) != -1;
178}
179
180// Check whether a file is writable.
181static bool fileIsWritable(const char* filename) {
182 return access(filename, W_OK) != -1;
183}
184
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700185// Truncate a file.
186static bool truncateFile(const char* path)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800187{
Jamie Gennis43122e72013-03-21 14:06:31 -0700188 // This uses creat rather than truncate because some of the debug kernel
189 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
190 // calls to truncate, but they are cleared by calls to creat.
191 int traceFD = creat(path, 0);
192 if (traceFD == -1) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700193 fprintf(stderr, "error truncating %s: %s (%d)\n", path,
Jamie Gennis43122e72013-03-21 14:06:31 -0700194 strerror(errno), errno);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700195 return false;
196 }
197
Jamie Gennis43122e72013-03-21 14:06:31 -0700198 close(traceFD);
199
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700200 return true;
201}
202
203static bool _writeStr(const char* filename, const char* str, int flags)
204{
205 int fd = open(filename, flags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800206 if (fd == -1) {
207 fprintf(stderr, "error opening %s: %s (%d)\n", filename,
208 strerror(errno), errno);
209 return false;
210 }
211
212 bool ok = true;
213 ssize_t len = strlen(str);
214 if (write(fd, str, len) != len) {
215 fprintf(stderr, "error writing to %s: %s (%d)\n", filename,
216 strerror(errno), errno);
217 ok = false;
218 }
219
220 close(fd);
221
222 return ok;
223}
224
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700225// Write a string to a file, returning true if the write was successful.
226static bool writeStr(const char* filename, const char* str)
227{
228 return _writeStr(filename, str, O_WRONLY);
229}
230
231// Append a string to a file, returning true if the write was successful.
232static bool appendStr(const char* filename, const char* str)
233{
234 return _writeStr(filename, str, O_APPEND|O_WRONLY);
235}
236
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800237// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
238// file.
239static bool setKernelOptionEnable(const char* filename, bool enable)
240{
241 return writeStr(filename, enable ? "1" : "0");
242}
243
244// Check whether the category is supported on the device with the current
245// rootness. A category is supported only if all its required /sys/ files are
246// writable and if enabling the category will enable one or more tracing tags
247// or /sys/ files.
248static bool isCategorySupported(const TracingCategory& category)
249{
250 bool ok = category.tags != 0;
251 for (int i = 0; i < MAX_SYS_FILES; i++) {
252 const char* path = category.sysfiles[i].path;
253 bool req = category.sysfiles[i].required == REQ;
254 if (path != NULL) {
255 if (req) {
256 if (!fileIsWritable(path)) {
257 return false;
258 } else {
259 ok = true;
260 }
261 } else {
262 ok |= fileIsWritable(path);
263 }
264 }
265 }
266 return ok;
267}
268
269// Check whether the category would be supported on the device if the user
270// were root. This function assumes that root is able to write to any file
271// that exists. It performs the same logic as isCategorySupported, but it
272// uses file existance rather than writability in the /sys/ file checks.
273static bool isCategorySupportedForRoot(const TracingCategory& category)
274{
275 bool ok = category.tags != 0;
276 for (int i = 0; i < MAX_SYS_FILES; i++) {
277 const char* path = category.sysfiles[i].path;
278 bool req = category.sysfiles[i].required == REQ;
279 if (path != NULL) {
280 if (req) {
281 if (!fileExists(path)) {
282 return false;
283 } else {
284 ok = true;
285 }
286 } else {
287 ok |= fileExists(path);
288 }
289 }
290 }
291 return ok;
292}
293
294// Enable or disable overwriting of the kernel trace buffers. Disabling this
295// will cause tracing to stop once the trace buffers have filled up.
296static bool setTraceOverwriteEnable(bool enable)
297{
298 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
299}
300
301// Enable or disable kernel tracing.
302static bool setTracingEnabled(bool enable)
303{
304 return setKernelOptionEnable(k_tracingOnPath, enable);
305}
306
307// Clear the contents of the kernel trace.
308static bool clearTrace()
309{
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700310 return truncateFile(k_tracePath);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800311}
312
313// Set the size of the kernel's trace buffer in kilobytes.
314static bool setTraceBufferSizeKB(int size)
315{
316 char str[32] = "1";
317 int len;
318 if (size < 1) {
319 size = 1;
320 }
321 snprintf(str, 32, "%d", size);
322 return writeStr(k_traceBufferSizePath, str);
323}
324
325// Enable or disable the kernel's use of the global clock. Disabling the global
326// clock will result in the kernel using a per-CPU local clock.
327static bool setGlobalClockEnable(bool enable)
328{
329 return writeStr(k_traceClockPath, enable ? "global" : "local");
330}
331
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700332static bool setPrintTgidEnableIfPresent(bool enable)
333{
334 if (fileExists(k_printTgidPath)) {
335 return setKernelOptionEnable(k_printTgidPath, enable);
336 }
337 return true;
338}
339
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800340// Poke all the binder-enabled processes in the system to get them to re-read
341// their system properties.
342static bool pokeBinderServices()
343{
344 sp<IServiceManager> sm = defaultServiceManager();
345 Vector<String16> services = sm->listServices();
346 for (size_t i = 0; i < services.size(); i++) {
347 sp<IBinder> obj = sm->checkService(services[i]);
348 if (obj != NULL) {
349 Parcel data;
350 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
351 NULL, 0) != OK) {
352 if (false) {
353 // XXX: For some reason this fails on tablets trying to
354 // poke the "phone" service. It's not clear whether some
355 // are expected to fail.
356 String8 svc(services[i]);
357 fprintf(stderr, "error poking binder service %s\n",
358 svc.string());
359 return false;
360 }
361 }
362 }
363 }
364 return true;
365}
366
367// Set the trace tags that userland tracing uses, and poke the running
368// processes to pick up the new value.
369static bool setTagsProperty(uint64_t tags)
370{
371 char buf[64];
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700372 snprintf(buf, 64, "%#" PRIx64, tags);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800373 if (property_set(k_traceTagsProperty, buf) < 0) {
374 fprintf(stderr, "error setting trace tags system property\n");
375 return false;
376 }
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700377 return true;
378}
379
380// Set the system property that indicates which apps should perform
381// application-level tracing.
382static bool setAppCmdlineProperty(const char* cmdline)
383{
384 if (property_set(k_traceAppCmdlineProperty, cmdline) < 0) {
385 fprintf(stderr, "error setting trace app system property\n");
386 return false;
387 }
388 return true;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800389}
390
391// Disable all /sys/ enable files.
392static bool disableKernelTraceEvents() {
393 bool ok = true;
394 for (int i = 0; i < NELEM(k_categories); i++) {
395 const TracingCategory &c = k_categories[i];
396 for (int j = 0; j < MAX_SYS_FILES; j++) {
397 const char* path = c.sysfiles[j].path;
398 if (path != NULL && fileIsWritable(path)) {
399 ok &= setKernelOptionEnable(path, false);
400 }
401 }
402 }
403 return ok;
404}
405
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700406// Verify that the comma separated list of functions are being traced by the
407// kernel.
408static bool verifyKernelTraceFuncs(const char* funcs)
409{
410 int fd = open(k_ftraceFilterPath, O_RDONLY);
411 if (fd == -1) {
412 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
413 strerror(errno), errno);
414 return false;
415 }
416
417 char buf[4097];
418 ssize_t n = read(fd, buf, 4096);
419 close(fd);
420 if (n == -1) {
421 fprintf(stderr, "error reading %s: %s (%d)\n", k_ftraceFilterPath,
422 strerror(errno), errno);
423 return false;
424 }
425
426 buf[n] = '\0';
427 String8 funcList = String8::format("\n%s", buf);
428
429 // Make sure that every function listed in funcs is in the list we just
430 // read from the kernel.
431 bool ok = true;
432 char* myFuncs = strdup(funcs);
433 char* func = strtok(myFuncs, ",");
434 while (func) {
435 String8 fancyFunc = String8::format("\n%s\n", func);
436 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
437 if (!found || func[0] == '\0') {
438 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
439 "to trace.\n", func);
440 ok = false;
441 }
442 func = strtok(NULL, ",");
443 }
444 free(myFuncs);
445
446 return ok;
447}
448
449// Set the comma separated list of functions that the kernel is to trace.
450static bool setKernelTraceFuncs(const char* funcs)
451{
452 bool ok = true;
453
454 if (funcs == NULL || funcs[0] == '\0') {
455 // Disable kernel function tracing.
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700456 if (fileIsWritable(k_currentTracerPath)) {
457 ok &= writeStr(k_currentTracerPath, "nop");
458 }
459 if (fileIsWritable(k_ftraceFilterPath)) {
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700460 ok &= truncateFile(k_ftraceFilterPath);
461 }
462 } else {
463 // Enable kernel function tracing.
464 ok &= writeStr(k_currentTracerPath, "function_graph");
465 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
466 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
467 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
468 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
469
470 // Set the requested filter functions.
471 ok &= truncateFile(k_ftraceFilterPath);
472 char* myFuncs = strdup(funcs);
473 char* func = strtok(myFuncs, ",");
474 while (func) {
475 ok &= appendStr(k_ftraceFilterPath, func);
476 func = strtok(NULL, ",");
477 }
478 free(myFuncs);
479
480 // Verify that the set functions are being traced.
481 if (ok) {
482 ok &= verifyKernelTraceFuncs(funcs);
483 }
484 }
485
486 return ok;
487}
488
489// Set all the kernel tracing settings to the desired state for this trace
490// capture.
491static bool setUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800492{
493 bool ok = true;
494
495 // Set up the tracing options.
496 ok &= setTraceOverwriteEnable(g_traceOverwrite);
497 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
498 ok &= setGlobalClockEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700499 ok &= setPrintTgidEnableIfPresent(true);
500 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800501
502 // Set up the tags property.
503 uint64_t tags = 0;
504 for (int i = 0; i < NELEM(k_categories); i++) {
505 if (g_categoryEnables[i]) {
506 const TracingCategory &c = k_categories[i];
507 tags |= c.tags;
508 }
509 }
510 ok &= setTagsProperty(tags);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700511 ok &= setAppCmdlineProperty(g_debugAppCmdLine);
512 ok &= pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800513
514 // Disable all the sysfs enables. This is done as a separate loop from
515 // the enables to allow the same enable to exist in multiple categories.
516 ok &= disableKernelTraceEvents();
517
518 // Enable all the sysfs enables that are in an enabled category.
519 for (int i = 0; i < NELEM(k_categories); i++) {
520 if (g_categoryEnables[i]) {
521 const TracingCategory &c = k_categories[i];
522 for (int j = 0; j < MAX_SYS_FILES; j++) {
523 const char* path = c.sysfiles[j].path;
524 bool required = c.sysfiles[j].required == REQ;
525 if (path != NULL) {
526 if (fileIsWritable(path)) {
527 ok &= setKernelOptionEnable(path, true);
528 } else if (required) {
529 fprintf(stderr, "error writing file %s\n", path);
530 ok = false;
531 }
532 }
533 }
534 }
535 }
536
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800537 return ok;
538}
539
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700540// Reset all the kernel tracing settings to their default state.
541static void cleanUpTrace()
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800542{
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800543 // Disable all tracing that we're able to.
544 disableKernelTraceEvents();
545
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700546 // Reset the system properties.
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800547 setTagsProperty(0);
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700548 setAppCmdlineProperty("");
549 pokeBinderServices();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800550
551 // Set the options back to their defaults.
552 setTraceOverwriteEnable(true);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700553 setTraceBufferSizeKB(1);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800554 setGlobalClockEnable(false);
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700555 setPrintTgidEnableIfPresent(false);
556 setKernelTraceFuncs(NULL);
557}
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800558
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700559
560// Enable tracing in the kernel.
561static bool startTrace()
562{
563 return setTracingEnabled(true);
564}
565
566// Disable tracing in the kernel.
567static void stopTrace()
568{
569 setTracingEnabled(false);
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800570}
571
572// Read the current kernel trace and write it to stdout.
573static void dumpTrace()
574{
575 int traceFD = open(k_tracePath, O_RDWR);
576 if (traceFD == -1) {
577 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
578 strerror(errno), errno);
579 return;
580 }
581
582 if (g_compress) {
583 z_stream zs;
584 uint8_t *in, *out;
585 int result, flush;
586
587 bzero(&zs, sizeof(zs));
588 result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
589 if (result != Z_OK) {
590 fprintf(stderr, "error initializing zlib: %d\n", result);
591 close(traceFD);
592 return;
593 }
594
595 const size_t bufSize = 64*1024;
596 in = (uint8_t*)malloc(bufSize);
597 out = (uint8_t*)malloc(bufSize);
598 flush = Z_NO_FLUSH;
599
600 zs.next_out = out;
601 zs.avail_out = bufSize;
602
603 do {
604
605 if (zs.avail_in == 0) {
606 // More input is needed.
607 result = read(traceFD, in, bufSize);
608 if (result < 0) {
609 fprintf(stderr, "error reading trace: %s (%d)\n",
610 strerror(errno), errno);
611 result = Z_STREAM_END;
612 break;
613 } else if (result == 0) {
614 flush = Z_FINISH;
615 } else {
616 zs.next_in = in;
617 zs.avail_in = result;
618 }
619 }
620
621 if (zs.avail_out == 0) {
622 // Need to write the output.
623 result = write(STDOUT_FILENO, out, bufSize);
624 if ((size_t)result < bufSize) {
625 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
626 strerror(errno), errno);
627 result = Z_STREAM_END; // skip deflate error message
628 zs.avail_out = bufSize; // skip the final write
629 break;
630 }
631 zs.next_out = out;
632 zs.avail_out = bufSize;
633 }
634
635 } while ((result = deflate(&zs, flush)) == Z_OK);
636
637 if (result != Z_STREAM_END) {
638 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
639 }
640
641 if (zs.avail_out < bufSize) {
642 size_t bytes = bufSize - zs.avail_out;
643 result = write(STDOUT_FILENO, out, bytes);
644 if ((size_t)result < bytes) {
645 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
646 strerror(errno), errno);
647 }
648 }
649
650 result = deflateEnd(&zs);
651 if (result != Z_OK) {
652 fprintf(stderr, "error cleaning up zlib: %d\n", result);
653 }
654
655 free(in);
656 free(out);
657 } else {
658 ssize_t sent = 0;
659 while ((sent = sendfile(STDOUT_FILENO, traceFD, NULL, 64*1024*1024)) > 0);
660 if (sent == -1) {
661 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
662 errno);
663 }
664 }
665
666 close(traceFD);
667}
668
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700669static void handleSignal(int /*signo*/)
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800670{
671 if (!g_nohup) {
672 g_traceAborted = true;
673 }
674}
675
676static void registerSigHandler()
677{
678 struct sigaction sa;
679 sigemptyset(&sa.sa_mask);
680 sa.sa_flags = 0;
681 sa.sa_handler = handleSignal;
682 sigaction(SIGHUP, &sa, NULL);
683 sigaction(SIGINT, &sa, NULL);
684 sigaction(SIGQUIT, &sa, NULL);
685 sigaction(SIGTERM, &sa, NULL);
686}
687
688static bool setCategoryEnable(const char* name, bool enable)
689{
690 for (int i = 0; i < NELEM(k_categories); i++) {
691 const TracingCategory& c = k_categories[i];
692 if (strcmp(name, c.name) == 0) {
693 if (isCategorySupported(c)) {
694 g_categoryEnables[i] = enable;
695 return true;
696 } else {
697 if (isCategorySupportedForRoot(c)) {
698 fprintf(stderr, "error: category \"%s\" requires root "
699 "privileges.\n", name);
700 } else {
701 fprintf(stderr, "error: category \"%s\" is not supported "
702 "on this device.\n", name);
703 }
704 return false;
705 }
706 }
707 }
708 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
709 return false;
710}
711
712static void listSupportedCategories()
713{
714 for (int i = 0; i < NELEM(k_categories); i++) {
715 const TracingCategory& c = k_categories[i];
716 if (isCategorySupported(c)) {
717 printf(" %10s - %s\n", c.name, c.longname);
718 }
719 }
720}
721
722// Print the command usage help to stderr.
723static void showHelp(const char *cmd)
724{
725 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
726 fprintf(stderr, "options include:\n"
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700727 " -a appname enable app-level tracing for a comma "
728 "separated list of cmdlines\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800729 " -b N use a trace buffer size of N KB\n"
730 " -c trace into a circular buffer\n"
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700731 " -k fname,... trace the listed kernel functions\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800732 " -n ignore signals\n"
733 " -s N sleep for N seconds before tracing [default 0]\n"
734 " -t N trace for N seconds [defualt 5]\n"
735 " -z compress the trace dump\n"
736 " --async_start start circular trace and return immediatly\n"
737 " --async_dump dump the current contents of circular trace buffer\n"
738 " --async_stop stop tracing and dump the current contents of circular\n"
739 " trace buffer\n"
Jamie Gennis92573f12012-12-07 16:29:03 -0800740 " --list_categories\n"
741 " list the available tracing categories\n"
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800742 );
743}
744
745int main(int argc, char **argv)
746{
747 bool async = false;
748 bool traceStart = true;
749 bool traceStop = true;
750 bool traceDump = true;
751
752 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
753 showHelp(argv[0]);
754 exit(0);
755 }
756
757 for (;;) {
758 int ret;
759 int option_index = 0;
760 static struct option long_options[] = {
761 {"async_start", no_argument, 0, 0 },
762 {"async_stop", no_argument, 0, 0 },
763 {"async_dump", no_argument, 0, 0 },
764 {"list_categories", no_argument, 0, 0 },
765 { 0, 0, 0, 0 }
766 };
767
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700768 ret = getopt_long(argc, argv, "a:b:ck:ns:t:z",
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800769 long_options, &option_index);
770
771 if (ret < 0) {
772 for (int i = optind; i < argc; i++) {
773 if (!setCategoryEnable(argv[i], true)) {
774 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
775 exit(1);
776 }
777 }
778 break;
779 }
780
781 switch(ret) {
Jamie Gennisf7f29c82013-03-27 15:50:58 -0700782 case 'a':
783 g_debugAppCmdLine = optarg;
784 break;
785
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800786 case 'b':
787 g_traceBufferSizeKB = atoi(optarg);
788 break;
789
790 case 'c':
791 g_traceOverwrite = true;
792 break;
793
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700794 case 'k':
795 g_kernelTraceFuncs = optarg;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700796 break;
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700797
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800798 case 'n':
799 g_nohup = true;
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700800 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800801
802 case 's':
803 g_initialSleepSecs = atoi(optarg);
804 break;
805
806 case 't':
807 g_traceDurationSeconds = atoi(optarg);
808 break;
809
810 case 'z':
811 g_compress = true;
812 break;
813
814 case 0:
815 if (!strcmp(long_options[option_index].name, "async_start")) {
816 async = true;
817 traceStop = false;
818 traceDump = false;
819 g_traceOverwrite = true;
820 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
821 async = true;
822 traceStop = false;
823 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
824 async = true;
825 traceStart = false;
826 traceStop = false;
827 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
828 listSupportedCategories();
829 exit(0);
830 }
Jamie Gennis6f6f3f72013-03-27 15:50:30 -0700831 break;
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800832
833 default:
834 fprintf(stderr, "\n");
835 showHelp(argv[0]);
836 exit(-1);
837 break;
838 }
839 }
840
841 registerSigHandler();
842
843 if (g_initialSleepSecs > 0) {
844 sleep(g_initialSleepSecs);
845 }
846
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700847 bool ok = true;
848 ok &= setUpTrace();
849 ok &= startTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800850
851 if (ok && traceStart) {
852 printf("capturing trace...");
853 fflush(stdout);
854
855 // We clear the trace after starting it because tracing gets enabled for
856 // each CPU individually in the kernel. Having the beginning of the trace
857 // contain entries from only one CPU can cause "begin" entries without a
858 // matching "end" entry to show up if a task gets migrated from one CPU to
859 // another.
860 ok = clearTrace();
861
862 if (ok && !async) {
863 // Sleep to allow the trace to be captured.
864 struct timespec timeLeft;
865 timeLeft.tv_sec = g_traceDurationSeconds;
866 timeLeft.tv_nsec = 0;
867 do {
868 if (g_traceAborted) {
869 break;
870 }
871 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
872 }
873 }
874
875 // Stop the trace and restore the default settings.
876 if (traceStop)
877 stopTrace();
878
879 if (ok && traceDump) {
880 if (!g_traceAborted) {
881 printf(" done\nTRACE:\n");
882 fflush(stdout);
883 dumpTrace();
884 } else {
885 printf("\ntrace aborted.\n");
886 fflush(stdout);
887 }
888 clearTrace();
889 } else if (!ok) {
890 fprintf(stderr, "unable to start tracing\n");
891 }
892
893 // Reset the trace buffer size to 1.
894 if (traceStop)
Jamie Gennise9b8cfb2013-03-12 16:00:10 -0700895 cleanUpTrace();
Jamie Gennis6eea6fb2012-12-07 14:03:07 -0800896
897 return g_traceAborted ? 1 : 0;
898}