blob: 9806661cae9991e7ade765e8aba66643a00d92cf [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 Schuh3458e492022-12-26 13:41:54 -080012int 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 Schuh27237362021-11-06 16:29:02 -070019Ftrace::Ftrace()
Austin Schuh3458e492022-12-26 13:41:54 -080020 : message_fd_(MaybeCheckOpen("/sys/kernel/debug/tracing/trace_marker")),
21 on_fd_(MaybeCheckOpen("/sys/kernel/debug/tracing/tracing_on")) {
22}
Austin Schuh27237362021-11-06 16:29:02 -070023
Brian Silverman79ec7fc2020-06-08 20:11:22 -050024Ftrace::~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
33void 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
47void 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