• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #ifndef ANDROID_PDX_TRACE_H_
2 #define ANDROID_PDX_TRACE_H_
3 
4 #include <array>
5 
6 #include <utils/Trace.h>
7 
8 // Enables internal tracing in libpdx. This is disabled by default to avoid
9 // spamming the trace buffers during normal trace activities. libpdx must be
10 // built with this set to true to enable internal tracing.
11 #ifndef PDX_LIB_TRACE_ENABLED
12 #define PDX_LIB_TRACE_ENABLED false
13 #endif
14 
15 namespace android {
16 namespace pdx {
17 
18 // Utility to generate scoped tracers with arguments.
19 class ScopedTraceArgs {
20  public:
21   template <typename... Args>
ScopedTraceArgs(uint64_t tag,const char * format,Args &&...args)22   ScopedTraceArgs(uint64_t tag, const char* format, Args&&... args)
23       : tag_{tag} {
24     if (atrace_is_tag_enabled(tag_)) {
25       std::array<char, 1024> buffer;
26       snprintf(buffer.data(), buffer.size(), format,
27                std::forward<Args>(args)...);
28       atrace_begin(tag_, buffer.data());
29     }
30   }
31 
~ScopedTraceArgs()32   ~ScopedTraceArgs() { atrace_end(tag_); }
33 
34  private:
35   uint64_t tag_;
36 
37   ScopedTraceArgs(const ScopedTraceArgs&) = delete;
38   void operator=(const ScopedTraceArgs&) = delete;
39 };
40 
41 // Utility to generate scoped tracers.
42 class ScopedTrace {
43  public:
44   template <typename... Args>
ScopedTrace(uint64_t tag,bool enabled,const char * name)45   ScopedTrace(uint64_t tag, bool enabled, const char* name)
46       : tag_{tag}, enabled_{enabled} {
47     if (enabled_)
48       atrace_begin(tag_, name);
49   }
50 
~ScopedTrace()51   ~ScopedTrace() {
52     if (enabled_)
53       atrace_end(tag_);
54   }
55 
56  private:
57   uint64_t tag_;
58   bool enabled_;
59 
60   ScopedTrace(const ScopedTrace&) = delete;
61   void operator=(const ScopedTrace&) = delete;
62 };
63 
64 }  // namespace pdx
65 }  // namespace android
66 
67 // Macro to define a scoped tracer with arguments. Uses PASTE(x, y) macro
68 // defined in utils/Trace.h.
69 #define PDX_TRACE_FORMAT(format, ...)                         \
70   ::android::pdx::ScopedTraceArgs PASTE(__tracer, __LINE__) { \
71     ATRACE_TAG, format, ##__VA_ARGS__                         \
72   }
73 
74 // TODO(eieio): Rename this to PDX_LIB_TRACE_NAME() for internal use by libpdx
75 // and rename internal uses inside the library. This version is only enabled
76 // when PDX_LIB_TRACE_ENABLED is true.
77 #define PDX_TRACE_NAME(name)                              \
78   ::android::pdx::ScopedTrace PASTE(__tracer, __LINE__) { \
79     ATRACE_TAG, PDX_LIB_TRACE_ENABLED, name               \
80   }
81 
82 #endif  // ANDROID_PDX_TRACE_H_
83