• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 // Trace events are for tracking application performance and resource usage.
6 // Macros are provided to track:
7 //    Begin and end of function calls
8 //    Counters
9 //
10 // Events are issued against categories. Whereas LOG's
11 // categories are statically defined, TRACE categories are created
12 // implicitly with a string. For example:
13 //   TRACE_EVENT_INSTANT("MY_SUBSYSTEM", "SomeImportantEvent")
14 //
15 // Events can be INSTANT, or can be pairs of BEGIN and END in the same scope:
16 //   TRACE_EVENT_BEGIN("MY_SUBSYSTEM", "SomethingCostly")
17 //   doSomethingCostly()
18 //   TRACE_EVENT_END("MY_SUBSYSTEM", "SomethingCostly")
19 // Note: our tools can't always determine the correct BEGIN/END pairs unless
20 // these are used in the same scope. Use ASYNC_BEGIN/ASYNC_END macros if you need them
21 // to be in separate scopes.
22 //
23 // A common use case is to trace entire function scopes. This
24 // issues a trace BEGIN and END automatically:
25 //   void doSomethingCostly() {
26 //     TRACE_EVENT("MY_SUBSYSTEM", "doSomethingCostly");
27 //     ...
28 //   }
29 //
30 // Additional parameters can be associated with an event:
31 //   void doSomethingCostly2(int howMuch) {
32 //     TRACE_EVENT("MY_SUBSYSTEM", "doSomethingCostly", "howMuch", howMuch);
33 //     ...
34 //   }
35 //
36 // The trace system will automatically add to this information the
37 // current process id, thread id, and a timestamp in microseconds.
38 //
39 // To trace an asynchronous procedure such as an IPC send/receive, use ASYNC_BEGIN and
40 // ASYNC_END:
41 //   [single threaded sender code]
42 //     static int send_count = 0;
43 //     ++send_count;
44 //     TRACE_EVENT_ASYNC_BEGIN("ipc", "message", send_count);
45 //     Send(new MyMessage(send_count));
46 //   [receive code]
47 //     void OnMyMessage(send_count) {
48 //       TRACE_EVENT_ASYNC_END("ipc", "message", send_count);
49 //     }
50 // The third parameter is a unique ID to match ASYNC_BEGIN/ASYNC_END pairs.
51 // ASYNC_BEGIN and ASYNC_END can occur on any thread of any traced process. Pointers can
52 // be used for the ID parameter, and they will be mangled internally so that
53 // the same pointer on two different processes will not match. For example:
54 //   class MyTracedClass {
55 //    public:
56 //     MyTracedClass() {
57 //       TRACE_EVENT_ASYNC_BEGIN("category", "MyTracedClass", this);
58 //     }
59 //     ~MyTracedClass() {
60 //       TRACE_EVENT_ASYNC_END("category", "MyTracedClass", this);
61 //     }
62 //   }
63 //
64 // Trace event also supports counters, which is a way to track a quantity
65 // as it varies over time. Counters are created with the following macro:
66 //   TRACE_COUNTER1("MY_SUBSYSTEM", "myCounter", g_myCounterValue);
67 //
68 // Counters are process-specific. The macro itself can be issued from any
69 // thread, however.
70 //
71 // Sometimes, you want to track two counters at once. You can do this with two
72 // counter macros:
73 //   TRACE_COUNTER1("MY_SUBSYSTEM", "myCounter0", g_myCounterValue[0]);
74 //   TRACE_COUNTER1("MY_SUBSYSTEM", "myCounter1", g_myCounterValue[1]);
75 // Or you can do it with a combined macro:
76 //   TRACE_COUNTER2("MY_SUBSYSTEM", "myCounter",
77 //       "bytesPinned", g_myCounterValue[0],
78 //       "bytesAllocated", g_myCounterValue[1]);
79 // This indicates to the tracing UI that these counters should be displayed
80 // in a single graph, as a summed area chart.
81 //
82 // Since counters are in a global namespace, you may want to disambiguate with a
83 // unique ID, by using the TRACE_COUNTER_ID* variations.
84 //
85 // By default, trace collection is compiled in, but turned off at runtime.
86 // Collecting trace data is the responsibility of the embedding
87 // application. In Chrome's case, navigating to about:tracing will turn on
88 // tracing and display data collected across all active processes.
89 //
90 //
91 // Memory scoping note:
92 // Tracing copies the pointers, not the string content, of the strings passed
93 // in for category, name, and arg_names. Thus, the following code will
94 // cause problems:
95 //     char* str = strdup("impprtantName");
96 //     TRACE_EVENT_INSTANT("SUBSYSTEM", str);  // BAD!
97 //     free(str);                   // Trace system now has dangling pointer
98 //
99 // To avoid this issue with the |name| and |arg_name| parameters, use the
100 // TRACE_EVENT_COPY_XXX overloads of the macros at additional runtime overhead.
101 // Notes: The category must always be in a long-lived char* (i.e. static const).
102 //        The |arg_values|, when used, are always deep copied with the _COPY
103 //        macros.
104 //
105 // When are string argument values copied:
106 // const char* arg_values are only referenced by default:
107 //     TRACE_EVENT("category", "name",
108 //                  "arg1", "literal string is only referenced");
109 // Use TRACE_STR_COPY to force copying of a const char*:
110 //     TRACE_EVENT("category", "name",
111 //                  "arg1", TRACE_STR_COPY("string will be copied"));
112 // std::string arg_values are always copied:
113 //     TRACE_EVENT("category", "name",
114 //                  "arg1", std::string("string will be copied"));
115 //
116 //
117 // Thread Safety:
118 // A thread safe singleton and mutex are used for thread safety. Category
119 // enabled flags are used to limit the performance impact when the system
120 // is not enabled.
121 //
122 // TRACE_EVENT macros first cache a pointer to a category. The categories are
123 // statically allocated and safe at all times, even after exit. Fetching a
124 // category is protected by the TraceLog::lock_. Multiple threads initializing
125 // the static variable is safe, as they will be serialized by the lock and
126 // multiple calls will return the same pointer to the category.
127 //
128 // Then the category_enabled flag is checked. This is a unsigned char, and
129 // not intended to be multithread safe. It optimizes access to addTraceEvent
130 // which is threadsafe internally via TraceLog::lock_. The enabled flag may
131 // cause some threads to incorrectly call or skip calling addTraceEvent near
132 // the time of the system being enabled or disabled. This is acceptable as
133 // we tolerate some data loss while the system is being enabled/disabled and
134 // because addTraceEvent is threadsafe internally and checks the enabled state
135 // again under lock.
136 //
137 // Without the use of these static category pointers and enabled flags all
138 // trace points would carry a significant performance cost of aquiring a lock
139 // and resolving the category.
140 
141 #ifndef COMMON_TRACE_EVENT_H_
142 #define COMMON_TRACE_EVENT_H_
143 
144 #include <string>
145 
146 #include "common/event_tracer.h"
147 
148 // By default, const char* argument values are assumed to have long-lived scope
149 // and will not be copied. Use this macro to force a const char* to be copied.
150 #define TRACE_STR_COPY(str) WebCore::TraceEvent::TraceStringWithCopy(str)
151 
152 // Records a pair of begin and end events called "name" for the current
153 // scope, optionally with associated arguments.
154 // Each argument must have a name and a value.
155 // If the category is not enabled, then this does nothing.
156 // - category and name strings must have application lifetime (statics or
157 //   literals). They may not include " chars.
158 #define TRACE_EVENT(platform, category, name, ...) \
159     INTERNAL_TRACE_EVENT_ADD_SCOPED(platform, category, name, ##__VA_ARGS__)
160 
161 // Deprecated, use `TRACE_EVENT` instead
162 #define TRACE_EVENT0(platform, category, name) TRACE_EVENT(platform, category, name)
163 #define TRACE_EVENT1(platform, category, name, arg1_name, arg1_val) \
164     TRACE_EVENT(platform, category, name, arg1_name, arg1_val)
165 #define TRACE_EVENT2(category, name, arg1_name, arg1_val, arg2_name, arg2_val) \
166     TRACE_EVENT(platform, category, name, arg1_name, arg1_val, arg2_name, arg2_val)
167 
168 // Records a single event called "name" immediately, optionally with associated arguments.
169 // Each argument must have a name and a value.
170 // If the category is not enabled, then this does nothing.
171 // - category and name strings must have application lifetime (statics or
172 //   literals). They may not include " chars.
173 #define TRACE_EVENT_INSTANT(platform, category, name, ...)                        \
174     INTERNAL_TRACE_EVENT_ADD(platform, TRACE_EVENT_PHASE_INSTANT, category, name, \
175                              TRACE_EVENT_FLAG_NONE, ##__VA_ARGS__)
176 #define TRACE_EVENT_COPY_INSTANT(platform, category, name, ...)                   \
177     INTERNAL_TRACE_EVENT_ADD(platform, TRACE_EVENT_PHASE_INSTANT, category, name, \
178                              TRACE_EVENT_FLAG_COPY, ##__VA_ARGS__)
179 
180 // Deprecated, use `TRACE_EVENT_INSTANT` instead
181 #define TRACE_EVENT_INSTANT0(platform, category, name) TRACE_EVENT_INSTANT(platform, category, name)
182 #define TRACE_EVENT_INSTANT1(platform, category, name, arg1_name, arg1_val) \
183     TRACE_EVENT_INSTANT(platform, category, name, arg1_name, arg1_val)
184 #define TRACE_EVENT_INSTANT2(platform, category, name, arg1_name, arg1_val, arg2_name, arg2_val) \
185     TRACE_EVENT_INSTANT(platform, category, name, arg1_name, arg1_val, arg2_name, arg2_val)
186 
187 // Deprecated, use `TRACE_EVENT_COPY_INSTANT` instead
188 #define TRACE_EVENT_COPY_INSTANT0(platform, category, name) \
189     TRACE_EVENT_COPY_INSTANT(platform, category, name)
190 #define TRACE_EVENT_COPY_INSTANT1(platform, category, name, arg1_name, arg1_val) \
191     TRACE_EVENT_COPY_INSTANT(platform, category, name, arg1_name, arg1_val)
192 #define TRACE_EVENT_COPY_INSTANT2(platform, category, name, arg1_name, arg1_val, arg2_name, \
193                                   arg2_val)                                                 \
194     TRACE_EVENT_COPY_INSTANT(platform, category, name, arg1_name, arg1_val, arg2_name, arg2_val)
195 
196 // Records a single BEGIN event called "name" immediately, optionally with associated arguments.
197 // Each argument must have a name and a value.
198 // If the category is not enabled, then this does nothing.
199 // - category and name strings must have application lifetime (statics or
200 //   literals). They may not include " chars.
201 #define TRACE_EVENT_BEGIN(platform, category, name, ...)                        \
202     INTERNAL_TRACE_EVENT_ADD(platform, TRACE_EVENT_PHASE_BEGIN, category, name, \
203                              TRACE_EVENT_FLAG_NONE, ##__VA_ARGS__)
204 #define TRACE_EVENT_COPY_BEGIN(platform, category, name, ...)                   \
205     INTERNAL_TRACE_EVENT_ADD(platform, TRACE_EVENT_PHASE_BEGIN, category, name, \
206                              TRACE_EVENT_FLAG_COPY, ##__VA_ARGS__)
207 
208 // Deprecated, use TRACE_EVENT_BEGIN
209 #define TRACE_EVENT_BEGIN0(platform, category, name) TRACE_EVENT_BEGIN(platform, category, name)
210 #define TRACE_EVENT_BEGIN1(platform, category, name, arg1_name, arg1_val) \
211     TRACE_EVENT_BEGIN(platform, category, name, arg1_name, arg1_val)
212 #define TRACE_EVENT_BEGIN2(platform, category, name, arg1_name, arg1_val, arg2_name, arg2_val) \
213     TRACE_EVENT_BEGIN(platform, category, name, arg1_name, arg1_val, arg2_name, arg2_val)
214 
215 // Deprecated, use TRACE_EVENT_COPY_BEGIN
216 #define TRACE_EVENT_COPY_BEGIN0(platform, category, name) \
217     TRACE_EVENT_COPY_BEGIN(platform, category, name)
218 #define TRACE_EVENT_COPY_BEGIN1(platform, category, name, arg1_name, arg1_val) \
219     TRACE_EVENT_COPY_BEGIN(platform, category, name, TRACE_EVENT_FLAG_COPY, arg1_name, arg1_val)
220 #define TRACE_EVENT_COPY_BEGIN2(platform, category, name, arg1_name, arg1_val, arg2_name,        \
221                                 arg2_val)                                                        \
222     TRACE_EVENT_COPY_BEGIN(platform, category, name, TRACE_EVENT_FLAG_COPY, arg1_name, arg1_val, \
223                            arg2_name, arg2_val)
224 
225 // Records a single END event for "name" immediately. If the category
226 // is not enabled, then this does nothing.
227 // - category and name strings must have application lifetime (statics or
228 //   literals). They may not include " chars.
229 #define TRACE_EVENT_END(platform, category, name, ...)                        \
230     INTERNAL_TRACE_EVENT_ADD(platform, TRACE_EVENT_PHASE_END, category, name, \
231                              TRACE_EVENT_FLAG_NONE, ##__VA_ARGS__)
232 #define TRACE_EVENT_COPY_END(platform, category, name, ...)                   \
233     INTERNAL_TRACE_EVENT_ADD(platform, TRACE_EVENT_PHASE_END, category, name, \
234                              TRACE_EVENT_FLAG_COPY, ##__VA_ARGS__)
235 
236 // Deprecated, use TRACE_EVENT_END
237 #define TRACE_EVENT_END0(platform, category, name) \
238     TRACE_EVENT_END(platform, TRACE_EVENT_PHASE_END, category, name)
239 #define TRACE_EVENT_END1(platform, category, name, arg1_name, arg1_val) \
240     TRACE_EVENT_END(platform, TRACE_EVENT_PHASE_END, category, name, arg1_name, arg1_val)
241 #define TRACE_EVENT_END2(platform, category, name, arg1_name, arg1_val, arg2_name, arg2_val) \
242     TRACE_EVENT_END(platform, TRACE_EVENT_PHASE_END, category, name, arg1_name, arg1_val,    \
243                     arg2_name, arg2_val)
244 
245 // Deprecated, use TRACE_EVENT_COPY_END
246 #define TRACE_EVENT_COPY_END0(platform, category, name) \
247     TRACE_EVENT_COPY_END(platform, TRACE_EVENT_PHASE_END, category, name)
248 #define TRACE_EVENT_COPY_END1(platform, category, name, arg1_name, arg1_val) \
249     TRACE_EVENT_COPY_END(platform, TRACE_EVENT_PHASE_END, category, name, arg1_name, arg1_val)
250 #define TRACE_EVENT_COPY_END2(platform, category, name, arg1_name, arg1_val, arg2_name, arg2_val) \
251     TRACE_EVENT_COPY_END(platform, TRACE_EVENT_PHASE_END, category, name, arg1_name, arg1_val,    \
252                          arg2_name, arg2_val)
253 
254 // Records the value of a counter called "name" immediately. Value
255 // must be representable as a 32 bit integer.
256 // - category and name strings must have application lifetime (statics or
257 //   literals). They may not include " chars.
258 #define TRACE_COUNTER1(platform, category, name, value)                           \
259     INTERNAL_TRACE_EVENT_ADD(platform, TRACE_EVENT_PHASE_COUNTER, category, name, \
260                              TRACE_EVENT_FLAG_NONE, "value", static_cast<int>(value))
261 #define TRACE_COPY_COUNTER1(platform, category, name, value)                      \
262     INTERNAL_TRACE_EVENT_ADD(platform, TRACE_EVENT_PHASE_COUNTER, category, name, \
263                              TRACE_EVENT_FLAG_COPY, "value", static_cast<int>(value))
264 
265 // Records the values of a multi-parted counter called "name" immediately.
266 // The UI will treat value1 and value2 as parts of a whole, displaying their
267 // values as a stacked-bar chart.
268 // - category and name strings must have application lifetime (statics or
269 //   literals). They may not include " chars.
270 #define TRACE_COUNTER2(platform, category, name, value1_name, value1_val, value2_name, value2_val) \
271     INTERNAL_TRACE_EVENT_ADD(platform, TRACE_EVENT_PHASE_COUNTER, category, name,                  \
272                              TRACE_EVENT_FLAG_NONE, value1_name, static_cast<int>(value1_val),     \
273                              value2_name, static_cast<int>(value2_val))
274 #define TRACE_COPY_COUNTER2(platform, category, name, value1_name, value1_val, value2_name,    \
275                             value2_val)                                                        \
276     INTERNAL_TRACE_EVENT_ADD(platform, TRACE_EVENT_PHASE_COUNTER, category, name,              \
277                              TRACE_EVENT_FLAG_COPY, value1_name, static_cast<int>(value1_val), \
278                              value2_name, static_cast<int>(value2_val))
279 
280 // Records the value of a counter called "name" immediately. Value
281 // must be representable as a 32 bit integer.
282 // - category and name strings must have application lifetime (statics or
283 //   literals). They may not include " chars.
284 // - |id| is used to disambiguate counters with the same name. It must either
285 //   be a pointer or an integer value up to 64 bits. If it's a pointer, the bits
286 //   will be xored with a hash of the process ID so that the same pointer on
287 //   two different processes will not collide.
288 #define TRACE_COUNTER_ID1(platform, category, name, id, value)                                \
289     INTERNAL_TRACE_EVENT_ADD_WITH_ID(platform, TRACE_EVENT_PHASE_COUNTER, category, name, id, \
290                                      TRACE_EVENT_FLAG_NONE, "value", static_cast<int>(value))
291 #define TRACE_COPY_COUNTER_ID1(platform, category, name, id, value)                           \
292     INTERNAL_TRACE_EVENT_ADD_WITH_ID(platform, TRACE_EVENT_PHASE_COUNTER, category, name, id, \
293                                      TRACE_EVENT_FLAG_COPY, "value", static_cast<int>(value))
294 
295 // Records the values of a multi-parted counter called "name" immediately.
296 // The UI will treat value1 and value2 as parts of a whole, displaying their
297 // values as a stacked-bar chart.
298 // - category and name strings must have application lifetime (statics or
299 //   literals). They may not include " chars.
300 // - |id| is used to disambiguate counters with the same name. It must either
301 //   be a pointer or an integer value up to 64 bits. If it's a pointer, the bits
302 //   will be xored with a hash of the process ID so that the same pointer on
303 //   two different processes will not collide.
304 #define TRACE_COUNTER_ID2(platform, category, name, id, value1_name, value1_val, value2_name, \
305                           value2_val)                                                         \
306     INTERNAL_TRACE_EVENT_ADD_WITH_ID(                                                         \
307         platform, TRACE_EVENT_PHASE_COUNTER, category, name, id, TRACE_EVENT_FLAG_NONE,       \
308         value1_name, static_cast<int>(value1_val), value2_name, static_cast<int>(value2_val))
309 #define TRACE_COPY_COUNTER_ID2(platform, category, name, id, value1_name, value1_val, value2_name, \
310                                value2_val)                                                         \
311     INTERNAL_TRACE_EVENT_ADD_WITH_ID(                                                              \
312         platform, TRACE_EVENT_PHASE_COUNTER, category, name, id, TRACE_EVENT_FLAG_COPY,            \
313         value1_name, static_cast<int>(value1_val), value2_name, static_cast<int>(value2_val))
314 
315 // Records a single ASYNC_BEGIN event called "name" immediately, with 0, 1 or 2
316 // associated arguments. If the category is not enabled, then this
317 // does nothing.
318 // - category and name strings must have application lifetime (statics or
319 //   literals). They may not include " chars.
320 // - |id| is used to match the ASYNC_BEGIN event with the ASYNC_END event. ASYNC
321 //   events are considered to match if their category, name and id values all
322 //   match. |id| must either be a pointer or an integer value up to 64 bits. If
323 //   it's a pointer, the bits will be xored with a hash of the process ID so
324 //   that the same pointer on two different processes will not collide.
325 // An asynchronous operation can consist of multiple phases. The first phase is
326 // defined by the ASYNC_BEGIN calls. Additional phases can be defined using the
327 // ASYNC_STEP_BEGIN macros. When the operation completes, call ASYNC_END.
328 // An async operation can span threads and processes, but all events in that
329 // operation must use the same |name| and |id|. Each event can have its own
330 // args.
331 #define TRACE_EVENT_ASYNC_BEGIN0(platform, category, name, id)                                    \
332     INTERNAL_TRACE_EVENT_ADD_WITH_ID(platform, TRACE_EVENT_PHASE_ASYNC_BEGIN, category, name, id, \
333                                      TRACE_EVENT_FLAG_NONE)
334 #define TRACE_EVENT_ASYNC_BEGIN1(platform, category, name, id, arg1_name, arg1_val)               \
335     INTERNAL_TRACE_EVENT_ADD_WITH_ID(platform, TRACE_EVENT_PHASE_ASYNC_BEGIN, category, name, id, \
336                                      TRACE_EVENT_FLAG_NONE, arg1_name, arg1_val)
337 #define TRACE_EVENT_ASYNC_BEGIN2(platform, category, name, id, arg1_name, arg1_val, arg2_name,    \
338                                  arg2_val)                                                        \
339     INTERNAL_TRACE_EVENT_ADD_WITH_ID(platform, TRACE_EVENT_PHASE_ASYNC_BEGIN, category, name, id, \
340                                      TRACE_EVENT_FLAG_NONE, arg1_name, arg1_val, arg2_name,       \
341                                      arg2_val)
342 #define TRACE_EVENT_COPY_ASYNC_BEGIN0(platform, category, name, id)                               \
343     INTERNAL_TRACE_EVENT_ADD_WITH_ID(platform, TRACE_EVENT_PHASE_ASYNC_BEGIN, category, name, id, \
344                                      TRACE_EVENT_FLAG_COPY)
345 #define TRACE_EVENT_COPY_ASYNC_BEGIN1(platform, category, name, id, arg1_name, arg1_val)          \
346     INTERNAL_TRACE_EVENT_ADD_WITH_ID(platform, TRACE_EVENT_PHASE_ASYNC_BEGIN, category, name, id, \
347                                      TRACE_EVENT_FLAG_COPY, arg1_name, arg1_val)
348 #define TRACE_EVENT_COPY_ASYNC_BEGIN2(platform, category, name, id, arg1_name, arg1_val,          \
349                                       arg2_name, arg2_val)                                        \
350     INTERNAL_TRACE_EVENT_ADD_WITH_ID(platform, TRACE_EVENT_PHASE_ASYNC_BEGIN, category, name, id, \
351                                      TRACE_EVENT_FLAG_COPY, arg1_name, arg1_val, arg2_name,       \
352                                      arg2_val)
353 
354 // Records a single ASYNC_STEP event for |step| immediately. If the category
355 // is not enabled, then this does nothing. The |name| and |id| must match the
356 // ASYNC_BEGIN event above. The |step| param identifies this step within the
357 // async event. This should be called at the beginning of the next phase of an
358 // asynchronous operation.
359 #define TRACE_EVENT_ASYNC_STEP0(platform, category, name, id, step)                              \
360     INTERNAL_TRACE_EVENT_ADD_WITH_ID(platform, TRACE_EVENT_PHASE_ASYNC_STEP, category, name, id, \
361                                      TRACE_EVENT_FLAG_NONE, "step", step)
362 #define TRACE_EVENT_ASYNC_STEP1(platform, category, name, id, step, arg1_name, arg1_val)         \
363     INTERNAL_TRACE_EVENT_ADD_WITH_ID(platform, TRACE_EVENT_PHASE_ASYNC_STEP, category, name, id, \
364                                      TRACE_EVENT_FLAG_NONE, "step", step, arg1_name, arg1_val)
365 #define TRACE_EVENT_COPY_ASYNC_STEP0(platform, category, name, id, step)                         \
366     INTERNAL_TRACE_EVENT_ADD_WITH_ID(platform, TRACE_EVENT_PHASE_ASYNC_STEP, category, name, id, \
367                                      TRACE_EVENT_FLAG_COPY, "step", step)
368 #define TRACE_EVENT_COPY_ASYNC_STEP1(platform, category, name, id, step, arg1_name, arg1_val)    \
369     INTERNAL_TRACE_EVENT_ADD_WITH_ID(platform, TRACE_EVENT_PHASE_ASYNC_STEP, category, name, id, \
370                                      TRACE_EVENT_FLAG_COPY, "step", step, arg1_name, arg1_val)
371 
372 // Records a single ASYNC_END event for "name" immediately. If the category
373 // is not enabled, then this does nothing.
374 #define TRACE_EVENT_ASYNC_END0(platform, category, name, id)                                    \
375     INTERNAL_TRACE_EVENT_ADD_WITH_ID(platform, TRACE_EVENT_PHASE_ASYNC_END, category, name, id, \
376                                      TRACE_EVENT_FLAG_NONE)
377 #define TRACE_EVENT_ASYNC_END1(platform, category, name, id, arg1_name, arg1_val)               \
378     INTERNAL_TRACE_EVENT_ADD_WITH_ID(platform, TRACE_EVENT_PHASE_ASYNC_END, category, name, id, \
379                                      TRACE_EVENT_FLAG_NONE, arg1_name, arg1_val)
380 #define TRACE_EVENT_ASYNC_END2(platform, category, name, id, arg1_name, arg1_val, arg2_name,    \
381                                arg2_val)                                                        \
382     INTERNAL_TRACE_EVENT_ADD_WITH_ID(platform, TRACE_EVENT_PHASE_ASYNC_END, category, name, id, \
383                                      TRACE_EVENT_FLAG_NONE, arg1_name, arg1_val, arg2_name,     \
384                                      arg2_val)
385 #define TRACE_EVENT_COPY_ASYNC_END0(platform, category, name, id)                               \
386     INTERNAL_TRACE_EVENT_ADD_WITH_ID(platform, TRACE_EVENT_PHASE_ASYNC_END, category, name, id, \
387                                      TRACE_EVENT_FLAG_COPY)
388 #define TRACE_EVENT_COPY_ASYNC_END1(platform, category, name, id, arg1_name, arg1_val)          \
389     INTERNAL_TRACE_EVENT_ADD_WITH_ID(platform, TRACE_EVENT_PHASE_ASYNC_END, category, name, id, \
390                                      TRACE_EVENT_FLAG_COPY, arg1_name, arg1_val)
391 #define TRACE_EVENT_COPY_ASYNC_END2(platform, category, name, id, arg1_name, arg1_val, arg2_name, \
392                                     arg2_val)                                                     \
393     INTERNAL_TRACE_EVENT_ADD_WITH_ID(platform, TRACE_EVENT_PHASE_ASYNC_END, category, name, id,   \
394                                      TRACE_EVENT_FLAG_COPY, arg1_name, arg1_val, arg2_name,       \
395                                      arg2_val)
396 
397 // Creates a scope of a sampling state with the given category and name (both must
398 // be constant strings). These states are intended for a sampling profiler.
399 // Implementation note: we store category and name together because we don't
400 // want the inconsistency/expense of storing two pointers.
401 // |thread_bucket| is [0..2] and is used to statically isolate samples in one
402 // thread from others.
403 //
404 // {  // The sampling state is set within this scope.
405 //    TRACE_EVENT_SAMPLING_STATE_SCOPE_FOR_BUCKET(0, "category", "name");
406 //    ...;
407 // }
408 #define TRACE_EVENT_SCOPED_SAMPLING_STATE_FOR_BUCKET(bucket_number, category, name) \
409     TraceEvent::SamplingStateScope<bucket_number> traceEventSamplingScope(category "\0" name);
410 
411 // Returns a current sampling state of the given bucket.
412 // The format of the returned string is "category\0name".
413 #define TRACE_EVENT_GET_SAMPLING_STATE_FOR_BUCKET(bucket_number) \
414     TraceEvent::SamplingStateScope<bucket_number>::current()
415 
416 // Sets a current sampling state of the given bucket.
417 // |category| and |name| have to be constant strings.
418 #define TRACE_EVENT_SET_SAMPLING_STATE_FOR_BUCKET(bucket_number, category, name) \
419     TraceEvent::SamplingStateScope<bucket_number>::set(category "\0" name)
420 
421 // Sets a current sampling state of the given bucket.
422 // |categoryAndName| doesn't need to be a constant string.
423 // The format of the string is "category\0name".
424 #define TRACE_EVENT_SET_NONCONST_SAMPLING_STATE_FOR_BUCKET(bucket_number, categoryAndName) \
425     TraceEvent::SamplingStateScope<bucket_number>::set(categoryAndName)
426 
427 // Syntactic sugars for the sampling tracing in the main thread.
428 #define TRACE_EVENT_SCOPED_SAMPLING_STATE(category, name) \
429     TRACE_EVENT_SCOPED_SAMPLING_STATE_FOR_BUCKET(0, category, name)
430 #define TRACE_EVENT_GET_SAMPLING_STATE() TRACE_EVENT_GET_SAMPLING_STATE_FOR_BUCKET(0)
431 #define TRACE_EVENT_SET_SAMPLING_STATE(category, name) \
432     TRACE_EVENT_SET_SAMPLING_STATE_FOR_BUCKET(0, category, name)
433 #define TRACE_EVENT_SET_NONCONST_SAMPLING_STATE(categoryAndName) \
434     TRACE_EVENT_SET_NONCONST_SAMPLING_STATE_FOR_BUCKET(0, categoryAndName)
435 
436 ////////////////////////////////////////////////////////////////////////////////
437 // Implementation specific tracing API definitions.
438 
439 // Get a pointer to the enabled state of the given trace category. Only
440 // long-lived literal strings should be given as the category name. The returned
441 // pointer can be held permanently in a local static for example. If the
442 // unsigned char is non-zero, tracing is enabled. If tracing is enabled,
443 // TRACE_EVENT_API_ADD_TRACE_EVENT can be called. It's OK if tracing is disabled
444 // between the load of the tracing state and the call to
445 // TRACE_EVENT_API_ADD_TRACE_EVENT, because this flag only provides an early out
446 // for best performance when tracing is disabled.
447 // const unsigned char*
448 //     TRACE_EVENT_API_GET_CATEGORY_ENABLED(const char* category_name)
449 #define TRACE_EVENT_API_GET_CATEGORY_ENABLED angle::GetTraceCategoryEnabledFlag
450 
451 // Add a trace event to the platform tracing system.
452 // void TRACE_EVENT_API_ADD_TRACE_EVENT(
453 //                    char phase,
454 //                    const unsigned char* category_enabled,
455 //                    const char* name,
456 //                    unsigned long long id,
457 //                    int num_args,
458 //                    const char** arg_names,
459 //                    const unsigned char* arg_types,
460 //                    const unsigned long long* arg_values,
461 //                    unsigned char flags)
462 #define TRACE_EVENT_API_ADD_TRACE_EVENT angle::AddTraceEvent
463 
464 ////////////////////////////////////////////////////////////////////////////////
465 
466 // Implementation detail: trace event macros create temporary variables
467 // to keep instrumentation overhead low. These macros give each temporary
468 // variable a unique name based on the line number to prevent name collissions.
469 #define INTERNAL_TRACE_EVENT_UID3(a, b) trace_event_unique_##a##b
470 #define INTERNAL_TRACE_EVENT_UID2(a, b) INTERNAL_TRACE_EVENT_UID3(a, b)
471 #define INTERNALTRACEEVENTUID(name_prefix) INTERNAL_TRACE_EVENT_UID2(name_prefix, __LINE__)
472 
473 // Implementation detail: internal macro to create static category.
474 #define INTERNAL_TRACE_EVENT_GET_CATEGORY_INFO(platform, category) \
475     static const unsigned char *INTERNALTRACEEVENTUID(catstatic) = \
476         TRACE_EVENT_API_GET_CATEGORY_ENABLED(platform, category);
477 
478 // Implementation detail: internal macro to create static category and add
479 // event if the category is enabled.
480 #define INTERNAL_TRACE_EVENT_ADD(platform, phase, category, name, flags, ...)                      \
481     do                                                                                             \
482     {                                                                                              \
483         INTERNAL_TRACE_EVENT_GET_CATEGORY_INFO(platform, category);                                \
484         if (*INTERNALTRACEEVENTUID(catstatic))                                                     \
485         {                                                                                          \
486             gl::TraceEvent::addTraceEvent(platform, phase, INTERNALTRACEEVENTUID(catstatic), name, \
487                                           gl::TraceEvent::noEventId, flags, ##__VA_ARGS__);        \
488         }                                                                                          \
489     } while (0)
490 
491 // Implementation detail: internal macro to create static category and add begin
492 // event if the category is enabled. Also adds the end event when the scope
493 // ends.
494 #define INTERNAL_TRACE_EVENT_ADD_SCOPED(platform, category, name, ...)                     \
495     INTERNAL_TRACE_EVENT_GET_CATEGORY_INFO(platform, category);                            \
496     gl::TraceEvent::TraceEndOnScopeClose INTERNALTRACEEVENTUID(profileScope);              \
497     do                                                                                     \
498     {                                                                                      \
499         if (*INTERNALTRACEEVENTUID(catstatic))                                             \
500         {                                                                                  \
501             gl::TraceEvent::addTraceEvent(                                                 \
502                 platform, TRACE_EVENT_PHASE_BEGIN, INTERNALTRACEEVENTUID(catstatic), name, \
503                 gl::TraceEvent::noEventId, TRACE_EVENT_FLAG_NONE, ##__VA_ARGS__);          \
504             INTERNALTRACEEVENTUID(profileScope)                                            \
505                 .initialize(platform, INTERNALTRACEEVENTUID(catstatic), name);             \
506         }                                                                                  \
507     } while (0)
508 
509 // Implementation detail: internal macro to create static category and add
510 // event if the category is enabled.
511 #define INTERNAL_TRACE_EVENT_ADD_WITH_ID(platform, phase, category, name, id, flags, ...)          \
512     do                                                                                             \
513     {                                                                                              \
514         INTERNAL_TRACE_EVENT_GET_CATEGORY_INFO(platform, category);                                \
515         if (*INTERNALTRACEEVENTUID(catstatic))                                                     \
516         {                                                                                          \
517             unsigned char traceEventFlags = flags | TRACE_EVENT_FLAG_HAS_ID;                       \
518             gl::TraceEvent::TraceID traceEventTraceID(id, &traceEventFlags);                       \
519             gl::TraceEvent::addTraceEvent(platform, phase, INTERNALTRACEEVENTUID(catstatic), name, \
520                                           traceEventTraceID.data(), traceEventFlags,               \
521                                           ##__VA_ARGS__);                                          \
522         }                                                                                          \
523     } while (0)
524 
525 // Notes regarding the following definitions:
526 // New values can be added and propagated to third party libraries, but existing
527 // definitions must never be changed, because third party libraries may use old
528 // definitions.
529 
530 // Phase indicates the nature of an event entry. E.g. part of a begin/end pair.
531 #define TRACE_EVENT_PHASE_BEGIN ('B')
532 #define TRACE_EVENT_PHASE_END ('E')
533 #define TRACE_EVENT_PHASE_INSTANT ('I')
534 #define TRACE_EVENT_PHASE_ASYNC_BEGIN ('S')
535 #define TRACE_EVENT_PHASE_ASYNC_STEP ('T')
536 #define TRACE_EVENT_PHASE_ASYNC_END ('F')
537 #define TRACE_EVENT_PHASE_METADATA ('M')
538 #define TRACE_EVENT_PHASE_COUNTER ('C')
539 #define TRACE_EVENT_PHASE_SAMPLE ('P')
540 
541 // Flags for changing the behavior of TRACE_EVENT_API_ADD_TRACE_EVENT.
542 #define TRACE_EVENT_FLAG_NONE (static_cast<unsigned char>(0))
543 #define TRACE_EVENT_FLAG_COPY (static_cast<unsigned char>(1 << 0))
544 #define TRACE_EVENT_FLAG_HAS_ID (static_cast<unsigned char>(1 << 1))
545 #define TRACE_EVENT_FLAG_MANGLE_ID (static_cast<unsigned char>(1 << 2))
546 
547 // Type values for identifying types in the TraceValue union.
548 #define TRACE_VALUE_TYPE_BOOL (static_cast<unsigned char>(1))
549 #define TRACE_VALUE_TYPE_UINT (static_cast<unsigned char>(2))
550 #define TRACE_VALUE_TYPE_INT (static_cast<unsigned char>(3))
551 #define TRACE_VALUE_TYPE_DOUBLE (static_cast<unsigned char>(4))
552 #define TRACE_VALUE_TYPE_POINTER (static_cast<unsigned char>(5))
553 #define TRACE_VALUE_TYPE_STRING (static_cast<unsigned char>(6))
554 #define TRACE_VALUE_TYPE_COPY_STRING (static_cast<unsigned char>(7))
555 
556 namespace gl
557 {
558 
559 namespace TraceEvent
560 {
561 
562 // Specify these values when the corresponding argument of addTraceEvent is not
563 // used.
564 const int zeroNumArgs              = 0;
565 const unsigned long long noEventId = 0;
566 
567 // TraceID encapsulates an ID that can either be an integer or pointer. Pointers
568 // are mangled with the Process ID so that they are unlikely to collide when the
569 // same pointer is used on different processes.
570 class TraceID
571 {
572   public:
TraceID(const void * id,unsigned char * flags)573     explicit TraceID(const void *id, unsigned char *flags)
574         : m_data(static_cast<unsigned long long>(reinterpret_cast<uintptr_t>(id)))
575     {
576         *flags |= TRACE_EVENT_FLAG_MANGLE_ID;
577     }
TraceID(unsigned long long id,unsigned char * flags)578     explicit TraceID(unsigned long long id, unsigned char *flags) : m_data(id) { (void)flags; }
TraceID(unsigned long id,unsigned char * flags)579     explicit TraceID(unsigned long id, unsigned char *flags) : m_data(id) { (void)flags; }
TraceID(unsigned int id,unsigned char * flags)580     explicit TraceID(unsigned int id, unsigned char *flags) : m_data(id) { (void)flags; }
TraceID(unsigned short id,unsigned char * flags)581     explicit TraceID(unsigned short id, unsigned char *flags) : m_data(id) { (void)flags; }
TraceID(unsigned char id,unsigned char * flags)582     explicit TraceID(unsigned char id, unsigned char *flags) : m_data(id) { (void)flags; }
TraceID(long long id,unsigned char * flags)583     explicit TraceID(long long id, unsigned char *flags)
584         : m_data(static_cast<unsigned long long>(id))
585     {
586         (void)flags;
587     }
TraceID(long id,unsigned char * flags)588     explicit TraceID(long id, unsigned char *flags) : m_data(static_cast<unsigned long long>(id))
589     {
590         (void)flags;
591     }
TraceID(int id,unsigned char * flags)592     explicit TraceID(int id, unsigned char *flags) : m_data(static_cast<unsigned long long>(id))
593     {
594         (void)flags;
595     }
TraceID(short id,unsigned char * flags)596     explicit TraceID(short id, unsigned char *flags) : m_data(static_cast<unsigned long long>(id))
597     {
598         (void)flags;
599     }
TraceID(signed char id,unsigned char * flags)600     explicit TraceID(signed char id, unsigned char *flags)
601         : m_data(static_cast<unsigned long long>(id))
602     {
603         (void)flags;
604     }
605 
data()606     unsigned long long data() const { return m_data; }
607 
608   private:
609     unsigned long long m_data;
610 };
611 
612 // Simple union to store various types as unsigned long long.
613 union TraceValueUnion
614 {
615     bool m_bool;
616     unsigned long long m_uint;
617     long long m_int;
618     double m_double;
619     const void *m_pointer;
620     const char *m_string;
621 };
622 
623 // Simple container for const char* that should be copied instead of retained.
624 class TraceStringWithCopy
625 {
626   public:
TraceStringWithCopy(const char * str)627     explicit TraceStringWithCopy(const char *str) : m_str(str) {}
628     operator const char *() const { return m_str; }
629 
630   private:
631     const char *m_str;
632 };
633 
634 // Define setTraceValue for each allowed type. It stores the type and
635 // value in the return arguments. This allows this API to avoid declaring any
636 // structures so that it is portable to third_party libraries.
637 #define INTERNAL_DECLARE_SET_TRACE_VALUE(actual_type, union_member, value_type_id) \
638     static inline void setTraceValue(actual_type arg, unsigned char *type,         \
639                                      unsigned long long *value)                    \
640     {                                                                              \
641         TraceValueUnion typeValue;                                                 \
642         typeValue.union_member = arg;                                              \
643         *type                  = value_type_id;                                    \
644         *value                 = typeValue.m_uint;                                 \
645     }
646 // Simpler form for int types that can be safely casted.
647 #define INTERNAL_DECLARE_SET_TRACE_VALUE_INT(actual_type, value_type_id)   \
648     static inline void setTraceValue(actual_type arg, unsigned char *type, \
649                                      unsigned long long *value)            \
650     {                                                                      \
651         *type  = value_type_id;                                            \
652         *value = static_cast<unsigned long long>(arg);                     \
653     }
654 
INTERNAL_DECLARE_SET_TRACE_VALUE_INT(unsigned long long,TRACE_VALUE_TYPE_UINT)655 INTERNAL_DECLARE_SET_TRACE_VALUE_INT(unsigned long long, TRACE_VALUE_TYPE_UINT)
656 INTERNAL_DECLARE_SET_TRACE_VALUE_INT(unsigned int, TRACE_VALUE_TYPE_UINT)
657 INTERNAL_DECLARE_SET_TRACE_VALUE_INT(unsigned short, TRACE_VALUE_TYPE_UINT)
658 INTERNAL_DECLARE_SET_TRACE_VALUE_INT(unsigned char, TRACE_VALUE_TYPE_UINT)
659 INTERNAL_DECLARE_SET_TRACE_VALUE_INT(long long, TRACE_VALUE_TYPE_INT)
660 INTERNAL_DECLARE_SET_TRACE_VALUE_INT(int, TRACE_VALUE_TYPE_INT)
661 INTERNAL_DECLARE_SET_TRACE_VALUE_INT(short, TRACE_VALUE_TYPE_INT)
662 INTERNAL_DECLARE_SET_TRACE_VALUE_INT(signed char, TRACE_VALUE_TYPE_INT)
663 INTERNAL_DECLARE_SET_TRACE_VALUE(bool, m_bool, TRACE_VALUE_TYPE_BOOL)
664 INTERNAL_DECLARE_SET_TRACE_VALUE(double, m_double, TRACE_VALUE_TYPE_DOUBLE)
665 INTERNAL_DECLARE_SET_TRACE_VALUE(const void *, m_pointer, TRACE_VALUE_TYPE_POINTER)
666 INTERNAL_DECLARE_SET_TRACE_VALUE(const char *, m_string, TRACE_VALUE_TYPE_STRING)
667 INTERNAL_DECLARE_SET_TRACE_VALUE(const TraceStringWithCopy &,
668                                  m_string,
669                                  TRACE_VALUE_TYPE_COPY_STRING)
670 
671 #undef INTERNAL_DECLARE_SET_TRACE_VALUE
672 #undef INTERNAL_DECLARE_SET_TRACE_VALUE_INT
673 
674 static inline void setTraceValue(const std::string &arg,
675                                  unsigned char *type,
676                                  unsigned long long *value)
677 {
678     TraceValueUnion typeValue;
679     typeValue.m_string = arg.data();
680     *type              = TRACE_VALUE_TYPE_COPY_STRING;
681     *value             = typeValue.m_uint;
682 }
683 
unpackArguments(const char ** names,unsigned char * types,unsigned long long * values)684 static inline void unpackArguments(const char **names,
685                                    unsigned char *types,
686                                    unsigned long long *values)
687 {}
688 
689 template <class ArgType, class... Args>
unpackArguments(const char ** names,unsigned char * types,unsigned long long * values,const char * argName,const ArgType & argVal,const Args...args)690 static inline void unpackArguments(const char **names,
691                                    unsigned char *types,
692                                    unsigned long long *values,
693                                    const char *argName,
694                                    const ArgType &argVal,
695                                    const Args... args)
696 {
697     *names = argName;
698     setTraceValue(argVal, types, values);
699     unpackArguments(++names, ++types, ++values, args...);
700 }
701 
702 // The addTraceEvent template function is defined here instead of in the
703 // macro, because the arg values could be temporary string objects. In order to
704 // store pointers to the internal c_str and pass through to the tracing API, the
705 // arg values must live throughout these procedures.
706 
707 template <class... Args>
addTraceEvent(angle::PlatformMethods * platform,char phase,const unsigned char * categoryEnabled,const char * name,unsigned long long id,unsigned char flags,const Args...args)708 static inline angle::TraceEventHandle addTraceEvent(angle::PlatformMethods *platform,
709                                                     char phase,
710                                                     const unsigned char *categoryEnabled,
711                                                     const char *name,
712                                                     unsigned long long id,
713                                                     unsigned char flags,
714                                                     const Args... args)
715 {
716     if constexpr (sizeof...(Args) == 0)
717     {
718         return TRACE_EVENT_API_ADD_TRACE_EVENT(platform, phase, categoryEnabled, name, id,
719                                                zeroNumArgs, 0, 0, 0, flags);
720     }
721     else
722     {
723         constexpr std::size_t numArgs = sizeof...(Args) / 2;
724         const char *argNames[numArgs];
725         unsigned char argTypes[numArgs];
726         unsigned long long argValues[numArgs];
727         unpackArguments(argNames, argTypes, argValues, args...);
728 
729         return TRACE_EVENT_API_ADD_TRACE_EVENT(platform, phase, categoryEnabled, name, id, numArgs,
730                                                argNames, argTypes, argValues, flags);
731     }
732 }
733 
734 // Used by TRACE_EVENTx macro. Do not use directly.
735 class TraceEndOnScopeClose
736 {
737   public:
738     // Note: members of m_data intentionally left uninitialized. See initialize.
TraceEndOnScopeClose()739     TraceEndOnScopeClose() : m_pdata(0) {}
~TraceEndOnScopeClose()740     ~TraceEndOnScopeClose()
741     {
742         if (m_pdata)
743             addEventIfEnabled();
744     }
745 
initialize(angle::PlatformMethods * platform,const unsigned char * categoryEnabled,const char * name)746     void initialize(angle::PlatformMethods *platform,
747                     const unsigned char *categoryEnabled,
748                     const char *name)
749     {
750         m_data.platform        = platform;
751         m_data.categoryEnabled = categoryEnabled;
752         m_data.name            = name;
753         m_pdata                = &m_data;
754     }
755 
756   private:
757     // Add the end event if the category is still enabled.
addEventIfEnabled()758     void addEventIfEnabled()
759     {
760         // Only called when m_pdata is non-null.
761         if (*m_pdata->categoryEnabled)
762         {
763             TRACE_EVENT_API_ADD_TRACE_EVENT(m_pdata->platform, TRACE_EVENT_PHASE_END,
764                                             m_pdata->categoryEnabled, m_pdata->name, noEventId,
765                                             zeroNumArgs, 0, 0, 0, TRACE_EVENT_FLAG_NONE);
766         }
767     }
768 
769     // This Data struct workaround is to avoid initializing all the members
770     // in Data during construction of this object, since this object is always
771     // constructed, even when tracing is disabled. If the members of Data were
772     // members of this class instead, compiler warnings occur about potential
773     // uninitialized accesses.
774     struct Data
775     {
776         angle::PlatformMethods *platform;
777         const unsigned char *categoryEnabled;
778         const char *name;
779     };
780     Data *m_pdata;
781     Data m_data;
782 };
783 
784 }  // namespace TraceEvent
785 
786 }  // namespace gl
787 
788 #endif
789