blob: 0afbcf519c23e216639d9e9e8d94a4e6e355d175 [file] [log] [blame]
Brian Silverman79ec7fc2020-06-08 20:11:22 -05001#include "aos/ftrace.h"
2
Tyler Chatowbf0609c2021-07-31 16:13:27 -07003#include <cstdarg>
4#include <cstdio>
Brian Silverman79ec7fc2020-06-08 20:11:22 -05005
Austin Schuh27237362021-11-06 16:29:02 -07006DEFINE_bool(
7 enable_ftrace, false,
8 "If false, disable logging to /sys/kernel/debug/tracing/trace_marker");
9
Brian Silverman79ec7fc2020-06-08 20:11:22 -050010namespace aos {
11
Austin Schuh27237362021-11-06 16:29:02 -070012Ftrace::Ftrace()
13 : message_fd_(FLAGS_enable_ftrace
14 ? open("/sys/kernel/debug/tracing/trace_marker", O_WRONLY)
15 : -1),
16 on_fd_(FLAGS_enable_ftrace
17 ? open("/sys/kernel/debug/tracing/tracing_on", O_WRONLY)
18 : -1) {}
19
Brian Silverman79ec7fc2020-06-08 20:11:22 -050020Ftrace::~Ftrace() {
21 if (message_fd_ != -1) {
22 PCHECK(close(message_fd_) == 0);
23 }
24 if (message_fd_ != -1) {
25 PCHECK(close(on_fd_) == 0);
26 }
27}
28
29void Ftrace::FormatMessage(const char *format, ...) {
30 if (message_fd_ == -1) {
31 return;
32 }
33 char buffer[512];
34 va_list ap;
35 va_start(ap, format);
36 const int result = vsnprintf(buffer, sizeof(buffer), format, ap);
37 va_end(ap);
38 CHECK_LE(static_cast<size_t>(result), sizeof(buffer))
39 << ": Format string ended up too long: " << format;
40 WriteMessage(std::string_view(buffer, result));
41}
42
43void Ftrace::WriteMessage(std::string_view content) {
44 if (message_fd_ == -1) {
45 return;
46 }
47 const int result = write(message_fd_, content.data(), content.size());
48 if (result == -1 && errno == EBADF) {
49 // This just means tracing is turned off. Ignore it.
50 return;
51 }
52 PCHECK(result >= 0) << ": Failed to write ftrace message: " << content;
53 CHECK_EQ(static_cast<size_t>(result), content.size())
54 << ": Failed to write complete ftrace message: " << content;
55}
56
57} // namespace aos