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 | 3458e49 | 2022-12-26 13:41:54 -0800 | [diff] [blame] | 12 | int MaybeCheckOpen(const char *file) { |
| 13 | if (!FLAGS_enable_ftrace) return -1; |
| 14 | int result = open(file, O_WRONLY); |
| 15 | PCHECK(result >= 0) << ": Failed to open " << file; |
| 16 | return result; |
| 17 | } |
| 18 | |
Austin Schuh | 2723736 | 2021-11-06 16:29:02 -0700 | [diff] [blame] | 19 | Ftrace::Ftrace() |
Austin Schuh | 3458e49 | 2022-12-26 13:41:54 -0800 | [diff] [blame] | 20 | : message_fd_(MaybeCheckOpen("/sys/kernel/debug/tracing/trace_marker")), |
| 21 | on_fd_(MaybeCheckOpen("/sys/kernel/debug/tracing/tracing_on")) { |
| 22 | } |
Austin Schuh | 2723736 | 2021-11-06 16:29:02 -0700 | [diff] [blame] | 23 | |
Brian Silverman | 79ec7fc | 2020-06-08 20:11:22 -0500 | [diff] [blame] | 24 | Ftrace::~Ftrace() { |
| 25 | if (message_fd_ != -1) { |
| 26 | PCHECK(close(message_fd_) == 0); |
| 27 | } |
| 28 | if (message_fd_ != -1) { |
| 29 | PCHECK(close(on_fd_) == 0); |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | void Ftrace::FormatMessage(const char *format, ...) { |
| 34 | if (message_fd_ == -1) { |
| 35 | return; |
| 36 | } |
| 37 | char buffer[512]; |
| 38 | va_list ap; |
| 39 | va_start(ap, format); |
| 40 | const int result = vsnprintf(buffer, sizeof(buffer), format, ap); |
| 41 | va_end(ap); |
| 42 | CHECK_LE(static_cast<size_t>(result), sizeof(buffer)) |
| 43 | << ": Format string ended up too long: " << format; |
| 44 | WriteMessage(std::string_view(buffer, result)); |
| 45 | } |
| 46 | |
| 47 | void Ftrace::WriteMessage(std::string_view content) { |
| 48 | if (message_fd_ == -1) { |
| 49 | return; |
| 50 | } |
| 51 | const int result = write(message_fd_, content.data(), content.size()); |
| 52 | if (result == -1 && errno == EBADF) { |
| 53 | // This just means tracing is turned off. Ignore it. |
| 54 | return; |
| 55 | } |
| 56 | PCHECK(result >= 0) << ": Failed to write ftrace message: " << content; |
| 57 | CHECK_EQ(static_cast<size_t>(result), content.size()) |
| 58 | << ": Failed to write complete ftrace message: " << content; |
| 59 | } |
| 60 | |
| 61 | } // namespace aos |