• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef INCLUDE_PERFETTO_TRACING_INTERNAL_TRACK_EVENT_MACROS_H_
18 #define INCLUDE_PERFETTO_TRACING_INTERNAL_TRACK_EVENT_MACROS_H_
19 
20 // This file contains underlying macros for the trace point track event
21 // implementation. Perfetto API users typically don't need to use anything here
22 // directly.
23 
24 #include "perfetto/base/compiler.h"
25 #include "perfetto/tracing/internal/track_event_data_source.h"
26 #include "perfetto/tracing/track_event_category_registry.h"
27 
28 // Ignore GCC warning about a missing argument for a variadic macro parameter.
29 #if defined(__GNUC__) || defined(__clang__)
30 #pragma GCC system_header
31 #endif
32 
33 // Defines data structures for backing a category registry.
34 //
35 // Each category has one enabled/disabled bit per possible data source instance.
36 // The bits are packed, i.e., each byte holds the state for instances. To
37 // improve cache locality, the bits for each instance are stored separately from
38 // the names of the categories:
39 //
40 //   byte 0                      byte 1
41 //   (inst0, inst1, ..., inst7), (inst0, inst1, ..., inst7)
42 //
43 #define PERFETTO_INTERNAL_DECLARE_CATEGORIES(...)                             \
44   namespace internal {                                                        \
45   constexpr ::perfetto::Category kCategories[] = {__VA_ARGS__};               \
46   constexpr size_t kCategoryCount =                                           \
47       sizeof(kCategories) / sizeof(kCategories[0]);                           \
48   /* The per-instance enable/disable state per category */                    \
49   PERFETTO_COMPONENT_EXPORT extern std::atomic<uint8_t>                       \
50       g_category_state_storage[kCategoryCount];                               \
51   /* The category registry which mediates access to the above structures. */  \
52   /* The registry is used for two purposes: */                                \
53   /**/                                                                        \
54   /*    1) For looking up categories at build (constexpr) time. */            \
55   /*    2) For declaring the per-namespace TrackEvent data source. */         \
56   /**/                                                                        \
57   /* Because usage #1 requires a constexpr type and usage #2 requires an */   \
58   /* extern type (to avoid declaring a type based on a translation-unit */    \
59   /* variable), we need two separate copies of the registry with different */ \
60   /* storage specifiers. */                                                   \
61   /**/                                                                        \
62   /* Note that because of a Clang/Windows bug, the constexpr category */      \
63   /* registry isn't given the enabled/disabled state array. All access */     \
64   /* to the category states should therefore be done through the */           \
65   /* non-constexpr registry. See */                                           \
66   /* https://bugs.llvm.org/show_bug.cgi?id=51558 */                           \
67   /**/                                                                        \
68   /* TODO(skyostil): Unify these using a C++17 inline constexpr variable. */  \
69   constexpr ::perfetto::internal::TrackEventCategoryRegistry                  \
70       kConstExprCategoryRegistry(kCategoryCount, &kCategories[0], nullptr);   \
71   PERFETTO_COMPONENT_EXPORT extern const ::perfetto::internal::               \
72       TrackEventCategoryRegistry kCategoryRegistry;                           \
73   static_assert(kConstExprCategoryRegistry.ValidateCategories(),              \
74                 "Invalid category names found");                              \
75   }  // namespace internal
76 
77 // In a .cc file, declares storage for each category's runtime state.
78 #define PERFETTO_INTERNAL_CATEGORY_STORAGE()             \
79   namespace internal {                                   \
80   PERFETTO_COMPONENT_EXPORT std::atomic<uint8_t>         \
81       g_category_state_storage[kCategoryCount];          \
82   PERFETTO_COMPONENT_EXPORT const ::perfetto::internal:: \
83       TrackEventCategoryRegistry kCategoryRegistry(      \
84           kCategoryCount,                                \
85           &kCategories[0],                               \
86           &g_category_state_storage[0]);                 \
87   }  // namespace internal
88 
89 // Defines the TrackEvent data source for the current track event namespace.
90 // `virtual ~TrackEvent` is added to avoid `-Wweak-vtables` warning.
91 // Learn more : aosp/2019906
92 #define PERFETTO_INTERNAL_DECLARE_TRACK_EVENT_DATA_SOURCE() \
93   struct PERFETTO_COMPONENT_EXPORT TrackEvent               \
94       : public ::perfetto::internal::TrackEventDataSource<  \
95             TrackEvent, &internal::kCategoryRegistry> {     \
96     virtual ~TrackEvent();                                  \
97   }
98 
99 #define PERFETTO_INTERNAL_DEFINE_TRACK_EVENT_DATA_SOURCE() \
100   TrackEvent::~TrackEvent() = default;
101 
102 // At compile time, turns a category name represented by a static string into an
103 // index into the current category registry. A build error will be generated if
104 // the category hasn't been registered or added to the list of allowed dynamic
105 // categories. See PERFETTO_DEFINE_CATEGORIES.
106 #define PERFETTO_GET_CATEGORY_INDEX(category)                                  \
107   ::PERFETTO_TRACK_EVENT_NAMESPACE::internal::kConstExprCategoryRegistry.Find( \
108       category,                                                                \
109       ::PERFETTO_TRACK_EVENT_NAMESPACE::internal::IsDynamicCategory(category))
110 
111 // Generate a unique variable name with a given prefix.
112 #define PERFETTO_INTERNAL_CONCAT2(a, b) a##b
113 #define PERFETTO_INTERNAL_CONCAT(a, b) PERFETTO_INTERNAL_CONCAT2(a, b)
114 #define PERFETTO_UID(prefix) PERFETTO_INTERNAL_CONCAT(prefix, __LINE__)
115 
116 // Efficiently determines whether tracing is enabled for the given category, and
117 // if so, emits one trace event with the given arguments.
118 #define PERFETTO_INTERNAL_TRACK_EVENT(category, ...)                           \
119   do {                                                                         \
120     namespace tns = ::PERFETTO_TRACK_EVENT_NAMESPACE;                          \
121     /* Compute the category index outside the lambda to work around a */       \
122     /* GCC 7 bug */                                                            \
123     static constexpr auto PERFETTO_UID(                                        \
124         kCatIndex_ADD_TO_PERFETTO_DEFINE_CATEGORIES_IF_FAILS_) =               \
125         PERFETTO_GET_CATEGORY_INDEX(category);                                 \
126     if (tns::internal::IsDynamicCategory(category)) {                          \
127       tns::TrackEvent::CallIfEnabled(                                          \
128           [&](uint32_t instances) PERFETTO_NO_THREAD_SAFETY_ANALYSIS {         \
129             tns::TrackEvent::TraceForCategory(instances, category,             \
130                                               ##__VA_ARGS__);                  \
131           });                                                                  \
132     } else {                                                                   \
133       tns::TrackEvent::CallIfCategoryEnabled(                                  \
134           PERFETTO_UID(kCatIndex_ADD_TO_PERFETTO_DEFINE_CATEGORIES_IF_FAILS_), \
135           [&](uint32_t instances) PERFETTO_NO_THREAD_SAFETY_ANALYSIS {         \
136             tns::TrackEvent::TraceForCategory(                                 \
137                 instances,                                                     \
138                 PERFETTO_UID(                                                  \
139                     kCatIndex_ADD_TO_PERFETTO_DEFINE_CATEGORIES_IF_FAILS_),    \
140                 ##__VA_ARGS__);                                                \
141           });                                                                  \
142     }                                                                          \
143   } while (false)
144 
145 #define PERFETTO_INTERNAL_SCOPED_TRACK_EVENT(category, name, ...)             \
146   struct PERFETTO_UID(ScopedEvent) {                                          \
147     struct EventFinalizer {                                                   \
148       /* The parameter is an implementation detail. It allows the          */ \
149       /* anonymous struct to use aggregate initialization to invoke the    */ \
150       /* lambda (which emits the BEGIN event and returns an integer)       */ \
151       /* with the proper reference capture for any                         */ \
152       /* TrackEventArgumentFunction in |__VA_ARGS__|. This is required so  */ \
153       /* that the scoped event is exactly ONE line and can't escape the    */ \
154       /* scope if used in a single line if statement.                      */ \
155       EventFinalizer(...) {}                                                  \
156       ~EventFinalizer() { TRACE_EVENT_END(category); }                        \
157     } finalizer;                                                              \
158   } PERFETTO_UID(scoped_event) {                                              \
159     [&]() {                                                                   \
160       TRACE_EVENT_BEGIN(category, name, ##__VA_ARGS__);                       \
161       return 0;                                                               \
162     }()                                                                       \
163   }
164 
165 #define PERFETTO_INTERNAL_CATEGORY_ENABLED(category)                         \
166   (::PERFETTO_TRACK_EVENT_NAMESPACE::internal::IsDynamicCategory(category)   \
167        ? ::PERFETTO_TRACK_EVENT_NAMESPACE::TrackEvent::                      \
168              IsDynamicCategoryEnabled(::perfetto::DynamicCategory(category)) \
169        : ::PERFETTO_TRACK_EVENT_NAMESPACE::TrackEvent::IsCategoryEnabled(    \
170              PERFETTO_GET_CATEGORY_INDEX(category)))
171 
172 // Emits an empty trace packet into the trace to ensure that the service can
173 // safely read the last event from the trace buffer. This can be used to
174 // periodically "flush" the last event on threads that don't support explicit
175 // flushing of the shared memory buffer chunk when the tracing session stops
176 // (e.g. thread pool workers in Chromium).
177 //
178 // This workaround is only required because the tracing service cannot safely
179 // read the last trace packet from an incomplete SMB chunk (crbug.com/1021571
180 // and b/162206162) when scraping the SMB. Adding an empty trace packet ensures
181 // that all prior events can be scraped by the service.
182 #define PERFETTO_INTERNAL_ADD_EMPTY_EVENT()                                  \
183   do {                                                                       \
184     ::PERFETTO_TRACK_EVENT_NAMESPACE::TrackEvent::Trace(                     \
185         [](::PERFETTO_TRACK_EVENT_NAMESPACE::TrackEvent::TraceContext ctx) { \
186           ctx.NewTracePacket();                                              \
187         });                                                                  \
188   } while (false)
189 
190 #endif  // INCLUDE_PERFETTO_TRACING_INTERNAL_TRACK_EVENT_MACROS_H_
191