• 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/string_helpers.h"
27 #include "perfetto/tracing/track_event_category_registry.h"
28 
29 // Ignore GCC warning about a missing argument for a variadic macro parameter.
30 #if defined(__GNUC__) || defined(__clang__)
31 #pragma GCC system_header
32 #endif
33 
34 // Defines data structures for backing a category registry.
35 //
36 // Each category has one enabled/disabled bit per possible data source instance.
37 // The bits are packed, i.e., each byte holds the state for instances. To
38 // improve cache locality, the bits for each instance are stored separately from
39 // the names of the categories:
40 //
41 //   byte 0                      byte 1
42 //   (inst0, inst1, ..., inst7), (inst0, inst1, ..., inst7)
43 //
44 #define PERFETTO_INTERNAL_DECLARE_CATEGORIES(attrs, ...)                      \
45   namespace internal {                                                        \
46   constexpr ::perfetto::Category kCategories[] = {__VA_ARGS__};               \
47   constexpr size_t kCategoryCount =                                           \
48       sizeof(kCategories) / sizeof(kCategories[0]);                           \
49   /* The per-instance enable/disable state per category */                    \
50   attrs extern std::atomic<uint8_t> 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   attrs extern const ::perfetto::internal::TrackEventCategoryRegistry         \
72       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(attrs)                      \
79   namespace internal {                                                 \
80   attrs std::atomic<uint8_t> g_category_state_storage[kCategoryCount]; \
81   attrs const ::perfetto::internal::TrackEventCategoryRegistry         \
82       kCategoryRegistry(kCategoryCount,                                \
83                         &kCategories[0],                               \
84                         &g_category_state_storage[0]);                 \
85   }  // namespace internal
86 
87 // Defines the TrackEvent data source for the current track event namespace.
88 // `virtual ~TrackEvent` is added to avoid `-Wweak-vtables` warning.
89 // Learn more : aosp/2019906
90 #define PERFETTO_INTERNAL_DECLARE_TRACK_EVENT_DATA_SOURCE(attrs)               \
91   struct attrs TrackEvent : public ::perfetto::internal::TrackEventDataSource< \
92                                 TrackEvent, &internal::kCategoryRegistry> {    \
93     virtual ~TrackEvent();                                                     \
94   }
95 
96 #define PERFETTO_INTERNAL_DEFINE_TRACK_EVENT_DATA_SOURCE() \
97   TrackEvent::~TrackEvent() = default;
98 
99 // At compile time, turns a category name represented by a static string into an
100 // index into the current category registry. A build error will be generated if
101 // the category hasn't been registered or added to the list of allowed dynamic
102 // categories. See PERFETTO_DEFINE_CATEGORIES.
103 #define PERFETTO_GET_CATEGORY_INDEX(category)                                \
104   PERFETTO_TRACK_EVENT_NAMESPACE::internal::kConstExprCategoryRegistry.Find( \
105       category,                                                              \
106       ::PERFETTO_TRACK_EVENT_NAMESPACE::internal::IsDynamicCategory(category))
107 
108 // Generate a unique variable name with a given prefix.
109 #define PERFETTO_INTERNAL_CONCAT2(a, b) a##b
110 #define PERFETTO_INTERNAL_CONCAT(a, b) PERFETTO_INTERNAL_CONCAT2(a, b)
111 #define PERFETTO_UID(prefix) PERFETTO_INTERNAL_CONCAT(prefix, __LINE__)
112 
113 // Efficiently determines whether tracing is enabled for the given category, and
114 // if so, emits one trace event with the given arguments.
115 #define PERFETTO_INTERNAL_TRACK_EVENT_WITH_METHOD(method, category, name, ...) \
116   do {                                                                         \
117     ::perfetto::internal::ValidateEventNameType<decltype(name)>();             \
118     namespace tns = PERFETTO_TRACK_EVENT_NAMESPACE;                            \
119     /* Compute the category index outside the lambda to work around a */       \
120     /* GCC 7 bug */                                                            \
121     constexpr auto PERFETTO_UID(                                               \
122         kCatIndex_ADD_TO_PERFETTO_DEFINE_CATEGORIES_IF_FAILS_) =               \
123         PERFETTO_GET_CATEGORY_INDEX(category);                                 \
124     if (::PERFETTO_TRACK_EVENT_NAMESPACE::internal::IsDynamicCategory(         \
125             category)) {                                                       \
126       tns::TrackEvent::CallIfEnabled(                                          \
127           [&](uint32_t instances) PERFETTO_NO_THREAD_SAFETY_ANALYSIS {         \
128             tns::TrackEvent::method(instances, category, name, ##__VA_ARGS__); \
129           });                                                                  \
130     } else {                                                                   \
131       tns::TrackEvent::CallIfCategoryEnabled(                                  \
132           PERFETTO_UID(kCatIndex_ADD_TO_PERFETTO_DEFINE_CATEGORIES_IF_FAILS_), \
133           [&](uint32_t instances) PERFETTO_NO_THREAD_SAFETY_ANALYSIS {         \
134             tns::TrackEvent::method(                                           \
135                 instances,                                                     \
136                 PERFETTO_UID(                                                  \
137                     kCatIndex_ADD_TO_PERFETTO_DEFINE_CATEGORIES_IF_FAILS_),    \
138                 name, ##__VA_ARGS__);                                          \
139           });                                                                  \
140     }                                                                          \
141   } while (false)
142 
143 #define PERFETTO_INTERNAL_TRACK_EVENT(...) \
144   PERFETTO_INTERNAL_TRACK_EVENT_WITH_METHOD(TraceForCategory, ##__VA_ARGS__)
145 
146 #if PERFETTO_ENABLE_LEGACY_TRACE_EVENTS
147 #define PERFETTO_INTERNAL_LEGACY_TRACK_EVENT(...)                   \
148   PERFETTO_INTERNAL_TRACK_EVENT_WITH_METHOD(TraceForCategoryLegacy, \
149                                             ##__VA_ARGS__)
150 
151 #define PERFETTO_INTERNAL_LEGACY_TRACK_EVENT_WITH_ID(...)                 \
152   PERFETTO_INTERNAL_TRACK_EVENT_WITH_METHOD(TraceForCategoryLegacyWithId, \
153                                             ##__VA_ARGS__)
154 #endif  // PERFETTO_ENABLE_LEGACY_TRACE_EVENTS
155 
156 // C++17 doesn't like a move constructor being defined for the EventFinalizer
157 // class but C++11 and MSVC doesn't compile without it being defined so support
158 // both.
159 #if !PERFETTO_BUILDFLAG(PERFETTO_COMPILER_MSVC)
160 #define PERFETTO_INTERNAL_EVENT_FINALIZER_KEYWORD delete
161 #else
162 #define PERFETTO_INTERNAL_EVENT_FINALIZER_KEYWORD default
163 #endif
164 
165 #define PERFETTO_INTERNAL_SCOPED_EVENT_FINALIZER(category)                    \
166   struct PERFETTO_UID(ScopedEvent) {                                          \
167     struct EventFinalizer {                                                   \
168       /* The parameter is an implementation detail. It allows the          */ \
169       /* anonymous struct to use aggregate initialization to invoke the    */ \
170       /* lambda (which emits the BEGIN event and returns an integer)       */ \
171       /* with the proper reference capture for any                         */ \
172       /* TrackEventArgumentFunction in |__VA_ARGS__|. This is required so  */ \
173       /* that the scoped event is exactly ONE line and can't escape the    */ \
174       /* scope if used in a single line if statement.                      */ \
175       EventFinalizer(...) {}                                                  \
176       ~EventFinalizer() { TRACE_EVENT_END(category); }                        \
177                                                                               \
178       EventFinalizer(const EventFinalizer&) = delete;                         \
179       inline EventFinalizer& operator=(const EventFinalizer&) = delete;       \
180                                                                               \
181       EventFinalizer(EventFinalizer&&) =                                      \
182           PERFETTO_INTERNAL_EVENT_FINALIZER_KEYWORD;                          \
183       EventFinalizer& operator=(EventFinalizer&&) = delete;                   \
184     } finalizer;                                                              \
185   }
186 
187 #define PERFETTO_INTERNAL_SCOPED_TRACK_EVENT(category, name, ...) \
188   PERFETTO_INTERNAL_SCOPED_EVENT_FINALIZER(category)              \
189   PERFETTO_UID(scoped_event) {                                    \
190     [&]() {                                                       \
191       TRACE_EVENT_BEGIN(category, name, ##__VA_ARGS__);           \
192       return 0;                                                   \
193     }()                                                           \
194   }
195 
196 #if PERFETTO_ENABLE_LEGACY_TRACE_EVENTS
197 // Required for TRACE_EVENT_WITH_FLOW legacy macros, which pass the bind_id as
198 // id.
199 #define PERFETTO_INTERNAL_SCOPED_LEGACY_TRACK_EVENT_WITH_ID(               \
200     category, name, track, flags, thread_id, id, ...)                      \
201   PERFETTO_INTERNAL_SCOPED_EVENT_FINALIZER(category)                       \
202   PERFETTO_UID(scoped_event) {                                             \
203     [&]() {                                                                \
204       PERFETTO_INTERNAL_LEGACY_TRACK_EVENT_WITH_ID(                        \
205           category, name,                                                  \
206           ::perfetto::protos::pbzero::TrackEvent::TYPE_SLICE_BEGIN, track, \
207           'B', flags, thread_id, id, ##__VA_ARGS__);                       \
208       return 0;                                                            \
209     }()                                                                    \
210   }
211 #endif  // PERFETTO_ENABLE_LEGACY_TRACE_EVENTS
212 
213 #if PERFETTO_BUILDFLAG(PERFETTO_COMPILER_GCC)
214 // On GCC versions <9 there's a bug that prevents using captured constant
215 // variables in constexpr evaluation inside a lambda:
216 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82643
217 // TODO(khokhlov): Remove this fallback after Perfetto moves to a more recent
218 // GCC version.
219 #define PERFETTO_INTERNAL_CATEGORY_ENABLED(category)                           \
220   (::PERFETTO_TRACK_EVENT_NAMESPACE::internal::IsDynamicCategory(category)     \
221        ? PERFETTO_TRACK_EVENT_NAMESPACE::TrackEvent::IsDynamicCategoryEnabled( \
222              ::perfetto::DynamicCategory(category))                            \
223        : PERFETTO_TRACK_EVENT_NAMESPACE::TrackEvent::IsCategoryEnabled(        \
224              PERFETTO_GET_CATEGORY_INDEX(category)))
225 #else  // !PERFETTO_BUILDFLAG(PERFETTO_COMPILER_GCC)
226 #define PERFETTO_INTERNAL_CATEGORY_ENABLED(category)                     \
227   [&]() -> bool {                                                        \
228     using PERFETTO_TRACK_EVENT_NAMESPACE::TrackEvent;                    \
229     using ::PERFETTO_TRACK_EVENT_NAMESPACE::internal::IsDynamicCategory; \
230     constexpr auto PERFETTO_UID(index) =                                 \
231         PERFETTO_GET_CATEGORY_INDEX(category);                           \
232     constexpr auto PERFETTO_UID(dynamic) = IsDynamicCategory(category);  \
233     return PERFETTO_UID(dynamic)                                         \
234                ? TrackEvent::IsDynamicCategoryEnabled(                   \
235                      ::perfetto::DynamicCategory(category))              \
236                : TrackEvent::IsCategoryEnabled(PERFETTO_UID(index));     \
237   }()
238 #endif  // !PERFETTO_BUILDFLAG(PERFETTO_COMPILER_GCC)
239 
240 // Emits an empty trace packet into the trace to ensure that the service can
241 // safely read the last event from the trace buffer. This can be used to
242 // periodically "flush" the last event on threads that don't support explicit
243 // flushing of the shared memory buffer chunk when the tracing session stops
244 // (e.g. thread pool workers in Chromium).
245 //
246 // This workaround is only required because the tracing service cannot safely
247 // read the last trace packet from an incomplete SMB chunk (crbug.com/1021571
248 // and b/162206162) when scraping the SMB. Adding an empty trace packet ensures
249 // that all prior events can be scraped by the service.
250 #define PERFETTO_INTERNAL_ADD_EMPTY_EVENT()                                \
251   do {                                                                     \
252     PERFETTO_TRACK_EVENT_NAMESPACE::TrackEvent::Trace(                     \
253         [](PERFETTO_TRACK_EVENT_NAMESPACE::TrackEvent::TraceContext ctx) { \
254           ctx.AddEmptyTracePacket();                                       \
255         });                                                                \
256   } while (false)
257 
258 #endif  // INCLUDE_PERFETTO_TRACING_INTERNAL_TRACK_EVENT_MACROS_H_
259