• 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(                                           \
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 // This internal macro is unused from the repo now, but some improper usage
148 // remain outside of the repo.
149 // TODO(b/294800182): Remove this.
150 #define PERFETTO_INTERNAL_TRACK_EVENT(...) \
151   PERFETTO_INTERNAL_TRACK_EVENT_WITH_METHOD(TraceForCategory, ##__VA_ARGS__)
152 
153 // C++17 doesn't like a move constructor being defined for the EventFinalizer
154 // class but C++11 and MSVC doesn't compile without it being defined so support
155 // both.
156 #if !PERFETTO_BUILDFLAG(PERFETTO_COMPILER_MSVC)
157 #define PERFETTO_INTERNAL_EVENT_FINALIZER_KEYWORD delete
158 #else
159 #define PERFETTO_INTERNAL_EVENT_FINALIZER_KEYWORD default
160 #endif
161 
162 #define PERFETTO_INTERNAL_SCOPED_EVENT_FINALIZER(category)                    \
163   struct PERFETTO_UID(ScopedEvent) {                                          \
164     struct EventFinalizer {                                                   \
165       /* The parameter is an implementation detail. It allows the          */ \
166       /* anonymous struct to use aggregate initialization to invoke the    */ \
167       /* lambda (which emits the BEGIN event and returns an integer)       */ \
168       /* with the proper reference capture for any                         */ \
169       /* TrackEventArgumentFunction in |__VA_ARGS__|. This is required so  */ \
170       /* that the scoped event is exactly ONE line and can't escape the    */ \
171       /* scope if used in a single line if statement.                      */ \
172       EventFinalizer(...) {}                                                  \
173       ~EventFinalizer() {                                                     \
174         TRACE_EVENT_END(category);                                            \
175       }                                                                       \
176                                                                               \
177       EventFinalizer(const EventFinalizer&) = delete;                         \
178       inline EventFinalizer& operator=(const EventFinalizer&) = delete;       \
179                                                                               \
180       EventFinalizer(EventFinalizer&&) =                                      \
181           PERFETTO_INTERNAL_EVENT_FINALIZER_KEYWORD;                          \
182       EventFinalizer& operator=(EventFinalizer&&) = delete;                   \
183     } finalizer;                                                              \
184   }
185 
186 #define PERFETTO_INTERNAL_SCOPED_TRACK_EVENT(category, name, ...) \
187   PERFETTO_INTERNAL_SCOPED_EVENT_FINALIZER(category)              \
188   PERFETTO_UID(scoped_event) {                                    \
189     [&]() {                                                       \
190       TRACE_EVENT_BEGIN(category, name, ##__VA_ARGS__);           \
191       return 0;                                                   \
192     }()                                                           \
193   }
194 
195 #if PERFETTO_ENABLE_LEGACY_TRACE_EVENTS
196 // Required for TRACE_EVENT_WITH_FLOW legacy macros, which pass the bind_id as
197 // id.
198 #define PERFETTO_INTERNAL_SCOPED_LEGACY_TRACK_EVENT_WITH_ID(               \
199     category, name, track, flags, thread_id, id, ...)                      \
200   PERFETTO_INTERNAL_SCOPED_EVENT_FINALIZER(category)                       \
201   PERFETTO_UID(scoped_event) {                                             \
202     [&]() {                                                                \
203       PERFETTO_INTERNAL_TRACK_EVENT_WITH_METHOD(                           \
204           TraceForCategoryLegacyWithId, category, name,                    \
205           ::perfetto::protos::pbzero::TrackEvent::TYPE_SLICE_BEGIN, track, \
206           'B', flags, thread_id, id, ##__VA_ARGS__);                       \
207       return 0;                                                            \
208     }()                                                                    \
209   }
210 #endif  // PERFETTO_ENABLE_LEGACY_TRACE_EVENTS
211 
212 #if PERFETTO_BUILDFLAG(PERFETTO_COMPILER_GCC) || \
213     PERFETTO_BUILDFLAG(PERFETTO_COMPILER_MSVC)
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