Brian Silverman | 79ec7fc | 2020-06-08 20:11:22 -0500 | [diff] [blame] | 1 | #include "aos/ftrace.h" |
| 2 | |
Tyler Chatow | bf0609c | 2021-07-31 16:13:27 -0700 | [diff] [blame] | 3 | #include <cstdarg> |
| 4 | #include <cstdio> |
Brian Silverman | 79ec7fc | 2020-06-08 20:11:22 -0500 | [diff] [blame] | 5 | |
Austin Schuh | 2723736 | 2021-11-06 16:29:02 -0700 | [diff] [blame] | 6 | DEFINE_bool( |
| 7 | enable_ftrace, false, |
| 8 | "If false, disable logging to /sys/kernel/debug/tracing/trace_marker"); |
| 9 | |
Brian Silverman | 79ec7fc | 2020-06-08 20:11:22 -0500 | [diff] [blame] | 10 | namespace aos { |
| 11 | |
Austin Schuh | 2723736 | 2021-11-06 16:29:02 -0700 | [diff] [blame] | 12 | Ftrace::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 Silverman | 79ec7fc | 2020-06-08 20:11:22 -0500 | [diff] [blame] | 20 | Ftrace::~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 | |
| 29 | void 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 | |
| 43 | void 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 |