xref: /aosp_15_r20/external/perfetto/include/perfetto/tracing/internal/track_event_macros.h (revision 6dbdd20afdafa5e3ca9b8809fa73465d530080dc)
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/thread_annotations.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(                                           \
129                 instances, category,                                           \
130                 ::perfetto::internal::DecayEventNameType(name),                \
131                 ##__VA_ARGS__);                                                \
132           });                                                                  \
133     } else {                                                                   \
134       tns::TrackEvent::CallIfCategoryEnabled(                                  \
135           PERFETTO_UID(kCatIndex_ADD_TO_PERFETTO_DEFINE_CATEGORIES_IF_FAILS_), \
136           [&](uint32_t instances) PERFETTO_NO_THREAD_SAFETY_ANALYSIS {         \
137             tns::TrackEvent::method(                                           \
138                 instances,                                                     \
139                 PERFETTO_UID(                                                  \
140                     kCatIndex_ADD_TO_PERFETTO_DEFINE_CATEGORIES_IF_FAILS_),    \
141                 ::perfetto::internal::DecayEventNameType(name),                \
142                 ##__VA_ARGS__);                                                \
143           });                                                                  \
144     }                                                                          \
145   } while (false)
146 
147 // C++17 doesn't like a move constructor being defined for the EventFinalizer
148 // class but C++11 and MSVC doesn't compile without it being defined so support
149 // both.
150 #if !PERFETTO_BUILDFLAG(PERFETTO_COMPILER_MSVC)
151 #define PERFETTO_INTERNAL_EVENT_FINALIZER_KEYWORD delete
152 #else
153 #define PERFETTO_INTERNAL_EVENT_FINALIZER_KEYWORD default
154 #endif
155 
156 #define PERFETTO_INTERNAL_SCOPED_EVENT_FINALIZER(category)                    \
157   struct PERFETTO_UID(ScopedEvent) {                                          \
158     struct EventFinalizer {                                                   \
159       /* The parameter is an implementation detail. It allows the          */ \
160       /* anonymous struct to use aggregate initialization to invoke the    */ \
161       /* lambda (which emits the BEGIN event and returns an integer)       */ \
162       /* with the proper reference capture for any                         */ \
163       /* TrackEventArgumentFunction in |__VA_ARGS__|. This is required so  */ \
164       /* that the scoped event is exactly ONE line and can't escape the    */ \
165       /* scope if used in a single line if statement.                      */ \
166       EventFinalizer(...) {}                                                  \
167       ~EventFinalizer() {                                                     \
168         TRACE_EVENT_END(category);                                            \
169       }                                                                       \
170                                                                               \
171       EventFinalizer(const EventFinalizer&) = delete;                         \
172       inline EventFinalizer& operator=(const EventFinalizer&) = delete;       \
173                                                                               \
174       EventFinalizer(EventFinalizer&&) =                                      \
175           PERFETTO_INTERNAL_EVENT_FINALIZER_KEYWORD;                          \
176       EventFinalizer& operator=(EventFinalizer&&) = delete;                   \
177     } finalizer;                                                              \
178   }
179 
180 #define PERFETTO_INTERNAL_SCOPED_TRACK_EVENT(category, name, ...) \
181   PERFETTO_INTERNAL_SCOPED_EVENT_FINALIZER(category)              \
182   PERFETTO_UID(scoped_event) {                                    \
183     [&]() {                                                       \
184       TRACE_EVENT_BEGIN(category, name, ##__VA_ARGS__);           \
185       return 0;                                                   \
186     }()                                                           \
187   }
188 
189 #if PERFETTO_ENABLE_LEGACY_TRACE_EVENTS
190 // Required for TRACE_EVENT_WITH_FLOW legacy macros, which pass the bind_id as
191 // id.
192 #define PERFETTO_INTERNAL_SCOPED_LEGACY_TRACK_EVENT_WITH_ID(               \
193     category, name, track, flags, thread_id, id, ...)                      \
194   PERFETTO_INTERNAL_SCOPED_EVENT_FINALIZER(category)                       \
195   PERFETTO_UID(scoped_event) {                                             \
196     [&]() {                                                                \
197       PERFETTO_INTERNAL_TRACK_EVENT_WITH_METHOD(                           \
198           TraceForCategoryLegacyWithId, category, name,                    \
199           ::perfetto::protos::pbzero::TrackEvent::TYPE_SLICE_BEGIN, track, \
200           'B', flags, thread_id, id, ##__VA_ARGS__);                       \
201       return 0;                                                            \
202     }()                                                                    \
203   }
204 #endif  // PERFETTO_ENABLE_LEGACY_TRACE_EVENTS
205 
206 #if PERFETTO_BUILDFLAG(PERFETTO_COMPILER_GCC) || \
207     PERFETTO_BUILDFLAG(PERFETTO_COMPILER_MSVC)
208 // On GCC versions <9 there's a bug that prevents using captured constant
209 // variables in constexpr evaluation inside a lambda:
210 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82643
211 // TODO(khokhlov): Remove this fallback after Perfetto moves to a more recent
212 // GCC version.
213 #define PERFETTO_INTERNAL_CATEGORY_ENABLED(category)                           \
214   (::PERFETTO_TRACK_EVENT_NAMESPACE::internal::IsDynamicCategory(category)     \
215        ? PERFETTO_TRACK_EVENT_NAMESPACE::TrackEvent::IsDynamicCategoryEnabled( \
216              ::perfetto::DynamicCategory(category))                            \
217        : PERFETTO_TRACK_EVENT_NAMESPACE::TrackEvent::IsCategoryEnabled(        \
218              PERFETTO_GET_CATEGORY_INDEX(category)))
219 #else  // !PERFETTO_BUILDFLAG(PERFETTO_COMPILER_GCC)
220 #define PERFETTO_INTERNAL_CATEGORY_ENABLED(category)                     \
221   [&]() -> bool {                                                        \
222     using PERFETTO_TRACK_EVENT_NAMESPACE::TrackEvent;                    \
223     using ::PERFETTO_TRACK_EVENT_NAMESPACE::internal::IsDynamicCategory; \
224     constexpr auto PERFETTO_UID(index) =                                 \
225         PERFETTO_GET_CATEGORY_INDEX(category);                           \
226     constexpr auto PERFETTO_UID(dynamic) = IsDynamicCategory(category);  \
227     return PERFETTO_UID(dynamic)                                         \
228                ? TrackEvent::IsDynamicCategoryEnabled(                   \
229                      ::perfetto::DynamicCategory(category))              \
230                : TrackEvent::IsCategoryEnabled(PERFETTO_UID(index));     \
231   }()
232 #endif  // !PERFETTO_BUILDFLAG(PERFETTO_COMPILER_GCC)
233 
234 // Emits an empty trace packet into the trace to ensure that the service can
235 // safely read the last event from the trace buffer. This can be used to
236 // periodically "flush" the last event on threads that don't support explicit
237 // flushing of the shared memory buffer chunk when the tracing session stops
238 // (e.g. thread pool workers in Chromium).
239 //
240 // This workaround is only required because the tracing service cannot safely
241 // read the last trace packet from an incomplete SMB chunk (crbug.com/1021571
242 // and b/162206162) when scraping the SMB. Adding an empty trace packet ensures
243 // that all prior events can be scraped by the service.
244 #define PERFETTO_INTERNAL_ADD_EMPTY_EVENT()                                \
245   do {                                                                     \
246     PERFETTO_TRACK_EVENT_NAMESPACE::TrackEvent::Trace(                     \
247         [](PERFETTO_TRACK_EVENT_NAMESPACE::TrackEvent::TraceContext ctx) { \
248           ctx.AddEmptyTracePacket();                                       \
249         });                                                                \
250   } while (false)
251 
252 #endif  // INCLUDE_PERFETTO_TRACING_INTERNAL_TRACK_EVENT_MACROS_H_
253