1 // Copyright (C) 2019 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 //
15 // This file is automatically generated by gen_amalgamated. Do not edit.
16
17 // gen_amalgamated begin header: include/perfetto/tracing.h
18 // gen_amalgamated begin header: include/perfetto/tracing/buffer_exhausted_policy.h
19 /*
20 * Copyright (C) 2019 The Android Open Source Project
21 *
22 * Licensed under the Apache License, Version 2.0 (the "License");
23 * you may not use this file except in compliance with the License.
24 * You may obtain a copy of the License at
25 *
26 * http://www.apache.org/licenses/LICENSE-2.0
27 *
28 * Unless required by applicable law or agreed to in writing, software
29 * distributed under the License is distributed on an "AS IS" BASIS,
30 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31 * See the License for the specific language governing permissions and
32 * limitations under the License.
33 */
34
35 #ifndef INCLUDE_PERFETTO_TRACING_BUFFER_EXHAUSTED_POLICY_H_
36 #define INCLUDE_PERFETTO_TRACING_BUFFER_EXHAUSTED_POLICY_H_
37
38 namespace perfetto {
39
40 // Determines how SharedMemoryArbiterImpl::GetNewChunk() behaves when no free
41 // chunks are available.
42 enum class BufferExhaustedPolicy {
43 // SharedMemoryArbiterImpl::GetNewChunk() will stall if no free SMB chunk is
44 // available and wait for the tracing service to free one. Note that this
45 // requires that messages the arbiter sends to the tracing service (from any
46 // TraceWriter thread) will be received by it, even if all TraceWriter threads
47 // are stalled.
48 kStall,
49
50 // SharedMemoryArbiterImpl::GetNewChunk() will return an invalid chunk if no
51 // free SMB chunk is available. In this case, the TraceWriter will fall back
52 // to a garbage chunk and drop written data until acquiring a future chunk
53 // succeeds again.
54 kDrop,
55
56 // TODO(eseckler): Switch to kDrop by default and change the Android code to
57 // explicitly request kStall instead.
58 kDefault = kStall
59 };
60
61 } // namespace perfetto
62
63 #endif // INCLUDE_PERFETTO_TRACING_BUFFER_EXHAUSTED_POLICY_H_
64 // gen_amalgamated begin header: include/perfetto/tracing/core/data_source_config.h
65 // gen_amalgamated begin header: include/perfetto/tracing/core/forward_decls.h
66 /*
67 * Copyright (C) 2019 The Android Open Source Project
68 *
69 * Licensed under the Apache License, Version 2.0 (the "License");
70 * you may not use this file except in compliance with the License.
71 * You may obtain a copy of the License at
72 *
73 * http://www.apache.org/licenses/LICENSE-2.0
74 *
75 * Unless required by applicable law or agreed to in writing, software
76 * distributed under the License is distributed on an "AS IS" BASIS,
77 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
78 * See the License for the specific language governing permissions and
79 * limitations under the License.
80 */
81
82 #ifndef INCLUDE_PERFETTO_TRACING_CORE_FORWARD_DECLS_H_
83 #define INCLUDE_PERFETTO_TRACING_CORE_FORWARD_DECLS_H_
84
85 // Forward declares classes that are generated at build-time from protos.
86 // First of all, why are we forward declaring at all?
87 // 1. Chromium diverges from the Google style guide on this, because forward
88 // declarations typically make build times faster, and that's a desirable
89 // property for a large and complex codebase.
90 // 2. Adding #include to build-time-generated headers from headers typically
91 // creates subtle build errors that are hard to spot in GN. This is because
92 // once a standard header (say foo.h) has an #include "protos/foo.gen.h",
93 // the build target that depends on foo.h needs to depend on the genrule
94 // that generates foo.gen.h. This is achievable using public_deps in GN but
95 // is not testable / enforceable, hence too easy to get wrong.
96
97 // Historically the classes below used to be generated from the corresponding
98 // .proto(s) at CL *check-in* time (!= build time) in the ::perfetto namespace.
99 // Nowadays we have code everywhere that assume the right class is
100 // ::perfetto::TraceConfig or the like. Back then other headers could just
101 // forward declared ::perfetto::TraceConfig. These days, the real class is
102 // ::perfetto::protos::gen::TraceConfig and core/trace_config.h aliases that as
103 // using ::perfetto::TraceConfig = ::perfetto::protos::gen::TraceConfig.
104 // In C++ one cannot forward declare a type alias (but only the aliased type).
105 // Hence this header, which should be used every time one wants to forward
106 // declare classes like TraceConfig.
107
108 // The overall plan is that, when one of the classes below is needed:
109 // The .h file includes this file.
110 // The .cc file includes perfetto/tracing/core/trace_config.h (or equiv). That
111 // header will pull the full declaration from trace_config.gen.h and will also
112 // setup the alias in the ::perfetto namespace.
113
114 namespace perfetto {
115 namespace protos {
116 namespace gen {
117
118 class ChromeConfig;
119 class CommitDataRequest;
120 class DataSourceConfig;
121 class DataSourceDescriptor;
122 class ObservableEvents;
123 class TraceConfig;
124 class TraceStats;
125 class TracingServiceCapabilities;
126 class TracingServiceState;
127
128 } // namespace gen
129 } // namespace protos
130
131 using ChromeConfig = ::perfetto::protos::gen::ChromeConfig;
132 using CommitDataRequest = ::perfetto::protos::gen::CommitDataRequest;
133 using DataSourceConfig = ::perfetto::protos::gen::DataSourceConfig;
134 using DataSourceDescriptor = ::perfetto::protos::gen::DataSourceDescriptor;
135 using ObservableEvents = ::perfetto::protos::gen::ObservableEvents;
136 using TraceConfig = ::perfetto::protos::gen::TraceConfig;
137 using TraceStats = ::perfetto::protos::gen::TraceStats;
138 using TracingServiceCapabilities =
139 ::perfetto::protos::gen::TracingServiceCapabilities;
140 using TracingServiceState = ::perfetto::protos::gen::TracingServiceState;
141
142 } // namespace perfetto
143
144 #endif // INCLUDE_PERFETTO_TRACING_CORE_FORWARD_DECLS_H_
145 // gen_amalgamated begin header: gen/protos/perfetto/config/data_source_config.gen.h
146 // gen_amalgamated begin header: include/perfetto/protozero/cpp_message_obj.h
147 // gen_amalgamated begin header: include/perfetto/base/export.h
148 // gen_amalgamated begin header: include/perfetto/base/build_config.h
149 // gen_amalgamated begin header: gen/build_config/perfetto_build_flags.h
150 /*
151 * Copyright (C) 2019 The Android Open Source Project
152 *
153 * Licensed under the Apache License, Version 2.0 (the "License");
154 * you may not use this file except in compliance with the License.
155 * You may obtain a copy of the License at
156 *
157 * http://www.apache.org/licenses/LICENSE-2.0
158 *
159 * Unless required by applicable law or agreed to in writing, software
160 * distributed under the License is distributed on an "AS IS" BASIS,
161 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
162 * See the License for the specific language governing permissions and
163 * limitations under the License.
164 */
165
166 // Generated by ../../gn/write_buildflag_header.py
167
168 // fix_include_guards: off
169 #ifndef GEN_BUILD_CONFIG_PERFETTO_BUILD_FLAGS_H_
170 #define GEN_BUILD_CONFIG_PERFETTO_BUILD_FLAGS_H_
171
172 // clang-format off
173 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_ANDROID_BUILD() (0)
174 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_CHROMIUM_BUILD() (0)
175 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_STANDALONE_BUILD() (0)
176 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_START_DAEMONS() (1)
177 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_IPC() (1)
178 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_WATCHDOG() (0)
179 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_COMPONENT_BUILD() (0)
180 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_FORCE_DLOG_ON() (0)
181 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_FORCE_DLOG_OFF() (0)
182 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_VERBOSE_LOGS() (1)
183 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_VERSION_GEN() (0)
184 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_TP_PERCENTILE() (0)
185 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_TP_LINENOISE() (0)
186 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_TP_HTTPD() (0)
187 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_TP_JSON() (1)
188 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_LOCAL_SYMBOLIZER() (0)
189 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_ZLIB() (1)
190
191 // clang-format on
192 #endif // GEN_BUILD_CONFIG_PERFETTO_BUILD_FLAGS_H_
193 /*
194 * Copyright (C) 2017 The Android Open Source Project
195 *
196 * Licensed under the Apache License, Version 2.0 (the "License");
197 * you may not use this file except in compliance with the License.
198 * You may obtain a copy of the License at
199 *
200 * http://www.apache.org/licenses/LICENSE-2.0
201 *
202 * Unless required by applicable law or agreed to in writing, software
203 * distributed under the License is distributed on an "AS IS" BASIS,
204 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
205 * See the License for the specific language governing permissions and
206 * limitations under the License.
207 */
208
209 #ifndef INCLUDE_PERFETTO_BASE_BUILD_CONFIG_H_
210 #define INCLUDE_PERFETTO_BASE_BUILD_CONFIG_H_
211
212 // Allows to define build flags that give a compiler error if the header that
213 // defined the flag is not included, instead of silently ignoring the #if block.
214 #define PERFETTO_BUILDFLAG_CAT_INDIRECT(a, b) a##b
215 #define PERFETTO_BUILDFLAG_CAT(a, b) PERFETTO_BUILDFLAG_CAT_INDIRECT(a, b)
216 #define PERFETTO_BUILDFLAG(flag) \
217 (PERFETTO_BUILDFLAG_CAT(PERFETTO_BUILDFLAG_DEFINE_, flag)())
218
219 #if defined(__ANDROID__)
220 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_ANDROID() 1
221 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_LINUX() 0
222 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_WIN() 0
223 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_APPLE() 0
224 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_MAC() 0
225 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_IOS() 0
226 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_WASM() 0
227 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_FUCHSIA() 0
228 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_NACL() 0
229 #elif defined(__APPLE__)
230 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_ANDROID() 0
231 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_APPLE() 1
232 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_LINUX() 0
233 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_WIN() 0
234 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_WASM() 0
235 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_FUCHSIA() 0
236 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_NACL() 0
237 // Include TARGET_OS_IPHONE when on __APPLE__ systems.
238 #include <TargetConditionals.h>
239 #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
240 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_MAC() 0
241 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_IOS() 1
242 #else
243 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_MAC() 1
244 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_IOS() 0
245 #endif
246 #elif defined(__linux__)
247 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_ANDROID() 0
248 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_LINUX() 1
249 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_WIN() 0
250 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_APPLE() 0
251 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_MAC() 0
252 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_IOS() 0
253 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_WASM() 0
254 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_FUCHSIA() 0
255 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_NACL() 0
256 #elif defined(_WIN32)
257 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_ANDROID() 0
258 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_LINUX() 0
259 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_WIN() 1
260 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_APPLE() 0
261 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_MAC() 0
262 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_IOS() 0
263 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_WASM() 0
264 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_FUCHSIA() 0
265 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_NACL() 0
266 #elif defined(__EMSCRIPTEN__)
267 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_ANDROID() 0
268 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_LINUX() 0
269 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_WIN() 0
270 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_APPLE() 0
271 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_MAC() 0
272 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_IOS() 0
273 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_WASM() 1
274 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_FUCHSIA() 0
275 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_NACL() 0
276 #elif defined(__Fuchsia__)
277 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_ANDROID() 0
278 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_APPLE() 0
279 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_MAC() 0
280 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_IOS() 0
281 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_LINUX() 0
282 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_WIN() 0
283 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_WASM() 0
284 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_FUCHSIA() 1
285 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_NACL() 0
286 #elif defined(__native_client__)
287 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_ANDROID() 0
288 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_LINUX() 0
289 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_WIN() 0
290 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_APPLE() 0
291 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_MAC() 0
292 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_IOS() 0
293 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_WASM() 0
294 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_FUCHSIA() 0
295 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_OS_NACL() 1
296 #else
297 #error OS not supported (see build_config.h)
298 #endif
299
300 #if defined(__clang__)
301 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_COMPILER_CLANG() 1
302 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_COMPILER_GCC() 0
303 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_COMPILER_MSVC() 0
304 #elif defined(__GNUC__) // Careful: Clang also defines this!
305 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_COMPILER_CLANG() 0
306 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_COMPILER_GCC() 1
307 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_COMPILER_MSVC() 0
308 #elif defined(_MSC_VER)
309 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_COMPILER_CLANG() 0
310 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_COMPILER_GCC() 0
311 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_COMPILER_MSVC() 1
312 #else
313 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_COMPILER_CLANG() 0
314 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_COMPILER_GCC() 0
315 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_COMPILER_MSVC() 0
316 #endif
317
318 #if defined(PERFETTO_BUILD_WITH_ANDROID_USERDEBUG)
319 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_ANDROID_USERDEBUG_BUILD() 1
320 #else
321 #define PERFETTO_BUILDFLAG_DEFINE_PERFETTO_ANDROID_USERDEBUG_BUILD() 0
322 #endif
323
324 // perfetto_build_flags.h contains the tweakable build flags defined via GN.
325 // - In GN builds (e.g., standalone, chromium, v8) this file is generated at
326 // build time via the gen_rule //gn/gen_buildflags.
327 // - In Android in-tree builds, this file is generated by tools/gen_android_bp
328 // and checked in into include/perfetto/base/build_configs/android_tree/. The
329 // default cflags add this path to the default include path.
330 // - Similarly, in bazel builds, this file is generated by tools/gen_bazel and
331 // checked in into include/perfetto/base/build_configs/bazel/.
332 // - In amaglamated builds, this file is generated by tools/gen_amalgamated and
333 // added to the amalgamated headers.
334 // gen_amalgamated expanded: #include "perfetto_build_flags.h" // no-include-violation-check
335
336 #endif // INCLUDE_PERFETTO_BASE_BUILD_CONFIG_H_
337 /*
338 * Copyright (C) 2018 The Android Open Source Project
339 *
340 * Licensed under the Apache License, Version 2.0 (the "License");
341 * you may not use this file except in compliance with the License.
342 * You may obtain a copy of the License at
343 *
344 * http://www.apache.org/licenses/LICENSE-2.0
345 *
346 * Unless required by applicable law or agreed to in writing, software
347 * distributed under the License is distributed on an "AS IS" BASIS,
348 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
349 * See the License for the specific language governing permissions and
350 * limitations under the License.
351 */
352
353 #ifndef INCLUDE_PERFETTO_BASE_EXPORT_H_
354 #define INCLUDE_PERFETTO_BASE_EXPORT_H_
355
356 // gen_amalgamated expanded: #include "perfetto/base/build_config.h"
357
358 #if PERFETTO_BUILDFLAG(PERFETTO_COMPONENT_BUILD)
359
360 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
361
362 #if defined(PERFETTO_IMPLEMENTATION)
363 #define PERFETTO_EXPORT __declspec(dllexport)
364 #else
365 #define PERFETTO_EXPORT __declspec(dllimport)
366 #endif
367
368 #else // PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
369
370 #if defined(PERFETTO_IMPLEMENTATION)
371 #define PERFETTO_EXPORT __attribute__((visibility("default")))
372 #else
373 #define PERFETTO_EXPORT
374 #endif
375
376 #endif // PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
377
378 #else // !PERFETTO_BUILDFLAG(PERFETTO_COMPONENT_BUILD)
379
380 #define PERFETTO_EXPORT
381
382 #endif // PERFETTO_BUILDFLAG(PERFETTO_COMPONENT_BUILD)
383
384 #endif // INCLUDE_PERFETTO_BASE_EXPORT_H_
385 /*
386 * Copyright (C) 2019 The Android Open Source Project
387 *
388 * Licensed under the Apache License, Version 2.0 (the "License");
389 * you may not use this file except in compliance with the License.
390 * You may obtain a copy of the License at
391 *
392 * http://www.apache.org/licenses/LICENSE-2.0
393 *
394 * Unless required by applicable law or agreed to in writing, software
395 * distributed under the License is distributed on an "AS IS" BASIS,
396 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
397 * See the License for the specific language governing permissions and
398 * limitations under the License.
399 */
400
401 #ifndef INCLUDE_PERFETTO_PROTOZERO_CPP_MESSAGE_OBJ_H_
402 #define INCLUDE_PERFETTO_PROTOZERO_CPP_MESSAGE_OBJ_H_
403
404 #include <stdint.h>
405
406 #include <string>
407 #include <vector>
408
409 // gen_amalgamated expanded: #include "perfetto/base/export.h"
410
411 namespace protozero {
412
413 // Base class for generated .gen.h classes, which are full C++ objects that
414 // support both ser and deserialization (but are not zero-copy).
415 // This is only used by the "cpp" targets not the "pbzero" ones.
416 class PERFETTO_EXPORT CppMessageObj {
417 public:
418 virtual ~CppMessageObj();
419 virtual std::string SerializeAsString() const = 0;
420 virtual std::vector<uint8_t> SerializeAsArray() const = 0;
421 virtual bool ParseFromArray(const void*, size_t) = 0;
422
ParseFromString(const std::string & str)423 bool ParseFromString(const std::string& str) {
424 return ParseFromArray(str.data(), str.size());
425 }
426 };
427
428 } // namespace protozero
429
430 #endif // INCLUDE_PERFETTO_PROTOZERO_CPP_MESSAGE_OBJ_H_
431 // gen_amalgamated begin header: include/perfetto/protozero/copyable_ptr.h
432 /*
433 * Copyright (C) 2019 The Android Open Source Project
434 *
435 * Licensed under the Apache License, Version 2.0 (the "License");
436 * you may not use this file except in compliance with the License.
437 * You may obtain a copy of the License at
438 *
439 * http://www.apache.org/licenses/LICENSE-2.0
440 *
441 * Unless required by applicable law or agreed to in writing, software
442 * distributed under the License is distributed on an "AS IS" BASIS,
443 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
444 * See the License for the specific language governing permissions and
445 * limitations under the License.
446 */
447
448 #ifndef INCLUDE_PERFETTO_PROTOZERO_COPYABLE_PTR_H_
449 #define INCLUDE_PERFETTO_PROTOZERO_COPYABLE_PTR_H_
450
451 #include <memory>
452
453 namespace protozero {
454
455 // This class is essentially a std::vector<T> of fixed size = 1.
456 // It's a pointer wrapper with deep copying and deep equality comparison.
457 // At all effects this wrapper behaves like the underlying T, with the exception
458 // of the heap indirection.
459 // Conversely to a std::unique_ptr, the pointer will be always valid, never
460 // null. The problem it solves is the following: when generating C++ classes
461 // from proto files, we want to keep each header hermetic (i.e. not #include
462 // headers of dependent types). As such we can't directly instantiate T
463 // field members but we can instead rely on pointers, so only the .cc file needs
464 // to see the actual definition of T. If the generated classes were move-only we
465 // could just use a unique_ptr there. But they aren't, hence this wrapper.
466 // Converesely to unique_ptr, this wrapper:
467 // - Default constructs the T instance in its constructor.
468 // - Implements deep comparison in operator== instead of pointer comparison.
469 template <typename T>
470 class CopyablePtr {
471 public:
CopyablePtr()472 CopyablePtr() : ptr_(new T()) {}
473 ~CopyablePtr() = default;
474
475 // Copy operators.
CopyablePtr(const CopyablePtr & other)476 CopyablePtr(const CopyablePtr& other) : ptr_(new T(*other.ptr_)) {}
477 CopyablePtr& operator=(const CopyablePtr& other) {
478 *ptr_ = *other.ptr_;
479 return *this;
480 }
481
482 // Move operators.
CopyablePtr(CopyablePtr && other)483 CopyablePtr(CopyablePtr&& other) noexcept : ptr_(std::move(other.ptr_)) {
484 other.ptr_.reset(new T());
485 }
486
487 CopyablePtr& operator=(CopyablePtr&& other) {
488 ptr_ = std::move(other.ptr_);
489 other.ptr_.reset(new T());
490 return *this;
491 }
492
get()493 T* get() { return ptr_.get(); }
get()494 const T* get() const { return ptr_.get(); }
495
496 T* operator->() { return ptr_.get(); }
497 const T* operator->() const { return ptr_.get(); }
498
499 T& operator*() { return *ptr_; }
500 const T& operator*() const { return *ptr_; }
501
502 friend bool operator==(const CopyablePtr& lhs, const CopyablePtr& rhs) {
503 return *lhs == *rhs;
504 }
505
506 friend bool operator!=(const CopyablePtr& lhs, const CopyablePtr& rhs) {
507 // In theory the underlying type might have a special operator!=
508 // implementation which is not just !(x == y). Respect that.
509 return *lhs != *rhs;
510 }
511
512 private:
513 std::unique_ptr<T> ptr_;
514 };
515
516 } // namespace protozero
517
518 #endif // INCLUDE_PERFETTO_PROTOZERO_COPYABLE_PTR_H_
519 // DO NOT EDIT. Autogenerated by Perfetto cppgen_plugin
520 #ifndef PERFETTO_PROTOS_PROTOS_PERFETTO_CONFIG_DATA_SOURCE_CONFIG_PROTO_CPP_H_
521 #define PERFETTO_PROTOS_PROTOS_PERFETTO_CONFIG_DATA_SOURCE_CONFIG_PROTO_CPP_H_
522
523 #include <stdint.h>
524 #include <bitset>
525 #include <vector>
526 #include <string>
527 #include <type_traits>
528
529 // gen_amalgamated expanded: #include "perfetto/protozero/cpp_message_obj.h"
530 // gen_amalgamated expanded: #include "perfetto/protozero/copyable_ptr.h"
531 // gen_amalgamated expanded: #include "perfetto/base/export.h"
532
533 namespace perfetto {
534 namespace protos {
535 namespace gen {
536 class DataSourceConfig;
537 class TestConfig;
538 class TestConfig_DummyFields;
539 class ChromeConfig;
540 } // namespace perfetto
541 } // namespace protos
542 } // namespace gen
543
544 namespace protozero {
545 class Message;
546 } // namespace protozero
547
548 namespace perfetto {
549 namespace protos {
550 namespace gen {
551
552 class PERFETTO_EXPORT DataSourceConfig : public ::protozero::CppMessageObj {
553 public:
554 enum FieldNumbers {
555 kNameFieldNumber = 1,
556 kTargetBufferFieldNumber = 2,
557 kTraceDurationMsFieldNumber = 3,
558 kStopTimeoutMsFieldNumber = 7,
559 kEnableExtraGuardrailsFieldNumber = 6,
560 kTracingSessionIdFieldNumber = 4,
561 kFtraceConfigFieldNumber = 100,
562 kInodeFileConfigFieldNumber = 102,
563 kProcessStatsConfigFieldNumber = 103,
564 kSysStatsConfigFieldNumber = 104,
565 kHeapprofdConfigFieldNumber = 105,
566 kJavaHprofConfigFieldNumber = 110,
567 kAndroidPowerConfigFieldNumber = 106,
568 kAndroidLogConfigFieldNumber = 107,
569 kGpuCounterConfigFieldNumber = 108,
570 kPackagesListConfigFieldNumber = 109,
571 kPerfEventConfigFieldNumber = 111,
572 kVulkanMemoryConfigFieldNumber = 112,
573 kTrackEventConfigFieldNumber = 113,
574 kAndroidPolledStateConfigFieldNumber = 114,
575 kChromeConfigFieldNumber = 101,
576 kLegacyConfigFieldNumber = 1000,
577 kForTestingFieldNumber = 1001,
578 };
579
580 DataSourceConfig();
581 ~DataSourceConfig() override;
582 DataSourceConfig(DataSourceConfig&&) noexcept;
583 DataSourceConfig& operator=(DataSourceConfig&&);
584 DataSourceConfig(const DataSourceConfig&);
585 DataSourceConfig& operator=(const DataSourceConfig&);
586 bool operator==(const DataSourceConfig&) const;
587 bool operator!=(const DataSourceConfig& other) const { return !(*this == other); }
588
589 bool ParseFromArray(const void*, size_t) override;
590 std::string SerializeAsString() const override;
591 std::vector<uint8_t> SerializeAsArray() const override;
592 void Serialize(::protozero::Message*) const;
593
has_name()594 bool has_name() const { return _has_field_[1]; }
name()595 const std::string& name() const { return name_; }
set_name(const std::string & value)596 void set_name(const std::string& value) { name_ = value; _has_field_.set(1); }
597
has_target_buffer()598 bool has_target_buffer() const { return _has_field_[2]; }
target_buffer()599 uint32_t target_buffer() const { return target_buffer_; }
set_target_buffer(uint32_t value)600 void set_target_buffer(uint32_t value) { target_buffer_ = value; _has_field_.set(2); }
601
has_trace_duration_ms()602 bool has_trace_duration_ms() const { return _has_field_[3]; }
trace_duration_ms()603 uint32_t trace_duration_ms() const { return trace_duration_ms_; }
set_trace_duration_ms(uint32_t value)604 void set_trace_duration_ms(uint32_t value) { trace_duration_ms_ = value; _has_field_.set(3); }
605
has_stop_timeout_ms()606 bool has_stop_timeout_ms() const { return _has_field_[7]; }
stop_timeout_ms()607 uint32_t stop_timeout_ms() const { return stop_timeout_ms_; }
set_stop_timeout_ms(uint32_t value)608 void set_stop_timeout_ms(uint32_t value) { stop_timeout_ms_ = value; _has_field_.set(7); }
609
has_enable_extra_guardrails()610 bool has_enable_extra_guardrails() const { return _has_field_[6]; }
enable_extra_guardrails()611 bool enable_extra_guardrails() const { return enable_extra_guardrails_; }
set_enable_extra_guardrails(bool value)612 void set_enable_extra_guardrails(bool value) { enable_extra_guardrails_ = value; _has_field_.set(6); }
613
has_tracing_session_id()614 bool has_tracing_session_id() const { return _has_field_[4]; }
tracing_session_id()615 uint64_t tracing_session_id() const { return tracing_session_id_; }
set_tracing_session_id(uint64_t value)616 void set_tracing_session_id(uint64_t value) { tracing_session_id_ = value; _has_field_.set(4); }
617
ftrace_config_raw()618 const std::string& ftrace_config_raw() const { return ftrace_config_; }
set_ftrace_config_raw(const std::string & raw)619 void set_ftrace_config_raw(const std::string& raw) { ftrace_config_ = raw; _has_field_.set(100); }
620
inode_file_config_raw()621 const std::string& inode_file_config_raw() const { return inode_file_config_; }
set_inode_file_config_raw(const std::string & raw)622 void set_inode_file_config_raw(const std::string& raw) { inode_file_config_ = raw; _has_field_.set(102); }
623
process_stats_config_raw()624 const std::string& process_stats_config_raw() const { return process_stats_config_; }
set_process_stats_config_raw(const std::string & raw)625 void set_process_stats_config_raw(const std::string& raw) { process_stats_config_ = raw; _has_field_.set(103); }
626
sys_stats_config_raw()627 const std::string& sys_stats_config_raw() const { return sys_stats_config_; }
set_sys_stats_config_raw(const std::string & raw)628 void set_sys_stats_config_raw(const std::string& raw) { sys_stats_config_ = raw; _has_field_.set(104); }
629
heapprofd_config_raw()630 const std::string& heapprofd_config_raw() const { return heapprofd_config_; }
set_heapprofd_config_raw(const std::string & raw)631 void set_heapprofd_config_raw(const std::string& raw) { heapprofd_config_ = raw; _has_field_.set(105); }
632
java_hprof_config_raw()633 const std::string& java_hprof_config_raw() const { return java_hprof_config_; }
set_java_hprof_config_raw(const std::string & raw)634 void set_java_hprof_config_raw(const std::string& raw) { java_hprof_config_ = raw; _has_field_.set(110); }
635
android_power_config_raw()636 const std::string& android_power_config_raw() const { return android_power_config_; }
set_android_power_config_raw(const std::string & raw)637 void set_android_power_config_raw(const std::string& raw) { android_power_config_ = raw; _has_field_.set(106); }
638
android_log_config_raw()639 const std::string& android_log_config_raw() const { return android_log_config_; }
set_android_log_config_raw(const std::string & raw)640 void set_android_log_config_raw(const std::string& raw) { android_log_config_ = raw; _has_field_.set(107); }
641
gpu_counter_config_raw()642 const std::string& gpu_counter_config_raw() const { return gpu_counter_config_; }
set_gpu_counter_config_raw(const std::string & raw)643 void set_gpu_counter_config_raw(const std::string& raw) { gpu_counter_config_ = raw; _has_field_.set(108); }
644
packages_list_config_raw()645 const std::string& packages_list_config_raw() const { return packages_list_config_; }
set_packages_list_config_raw(const std::string & raw)646 void set_packages_list_config_raw(const std::string& raw) { packages_list_config_ = raw; _has_field_.set(109); }
647
perf_event_config_raw()648 const std::string& perf_event_config_raw() const { return perf_event_config_; }
set_perf_event_config_raw(const std::string & raw)649 void set_perf_event_config_raw(const std::string& raw) { perf_event_config_ = raw; _has_field_.set(111); }
650
vulkan_memory_config_raw()651 const std::string& vulkan_memory_config_raw() const { return vulkan_memory_config_; }
set_vulkan_memory_config_raw(const std::string & raw)652 void set_vulkan_memory_config_raw(const std::string& raw) { vulkan_memory_config_ = raw; _has_field_.set(112); }
653
track_event_config_raw()654 const std::string& track_event_config_raw() const { return track_event_config_; }
set_track_event_config_raw(const std::string & raw)655 void set_track_event_config_raw(const std::string& raw) { track_event_config_ = raw; _has_field_.set(113); }
656
android_polled_state_config_raw()657 const std::string& android_polled_state_config_raw() const { return android_polled_state_config_; }
set_android_polled_state_config_raw(const std::string & raw)658 void set_android_polled_state_config_raw(const std::string& raw) { android_polled_state_config_ = raw; _has_field_.set(114); }
659
has_chrome_config()660 bool has_chrome_config() const { return _has_field_[101]; }
chrome_config()661 const ChromeConfig& chrome_config() const { return *chrome_config_; }
mutable_chrome_config()662 ChromeConfig* mutable_chrome_config() { _has_field_.set(101); return chrome_config_.get(); }
663
has_legacy_config()664 bool has_legacy_config() const { return _has_field_[1000]; }
legacy_config()665 const std::string& legacy_config() const { return legacy_config_; }
set_legacy_config(const std::string & value)666 void set_legacy_config(const std::string& value) { legacy_config_ = value; _has_field_.set(1000); }
667
has_for_testing()668 bool has_for_testing() const { return _has_field_[1001]; }
for_testing()669 const TestConfig& for_testing() const { return *for_testing_; }
mutable_for_testing()670 TestConfig* mutable_for_testing() { _has_field_.set(1001); return for_testing_.get(); }
671
672 private:
673 std::string name_{};
674 uint32_t target_buffer_{};
675 uint32_t trace_duration_ms_{};
676 uint32_t stop_timeout_ms_{};
677 bool enable_extra_guardrails_{};
678 uint64_t tracing_session_id_{};
679 std::string ftrace_config_; // [lazy=true]
680 std::string inode_file_config_; // [lazy=true]
681 std::string process_stats_config_; // [lazy=true]
682 std::string sys_stats_config_; // [lazy=true]
683 std::string heapprofd_config_; // [lazy=true]
684 std::string java_hprof_config_; // [lazy=true]
685 std::string android_power_config_; // [lazy=true]
686 std::string android_log_config_; // [lazy=true]
687 std::string gpu_counter_config_; // [lazy=true]
688 std::string packages_list_config_; // [lazy=true]
689 std::string perf_event_config_; // [lazy=true]
690 std::string vulkan_memory_config_; // [lazy=true]
691 std::string track_event_config_; // [lazy=true]
692 std::string android_polled_state_config_; // [lazy=true]
693 ::protozero::CopyablePtr<ChromeConfig> chrome_config_;
694 std::string legacy_config_{};
695 ::protozero::CopyablePtr<TestConfig> for_testing_;
696
697 // Allows to preserve unknown protobuf fields for compatibility
698 // with future versions of .proto files.
699 std::string unknown_fields_;
700
701 std::bitset<1002> _has_field_{};
702 };
703
704 } // namespace perfetto
705 } // namespace protos
706 } // namespace gen
707
708 #endif // PERFETTO_PROTOS_PROTOS_PERFETTO_CONFIG_DATA_SOURCE_CONFIG_PROTO_CPP_H_
709 /*
710 * Copyright (C) 2017 The Android Open Source Project
711 *
712 * Licensed under the Apache License, Version 2.0 (the "License");
713 * you may not use this file except in compliance with the License.
714 * You may obtain a copy of the License at
715 *
716 * http://www.apache.org/licenses/LICENSE-2.0
717 *
718 * Unless required by applicable law or agreed to in writing, software
719 * distributed under the License is distributed on an "AS IS" BASIS,
720 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
721 * See the License for the specific language governing permissions and
722 * limitations under the License.
723 */
724
725 #ifndef INCLUDE_PERFETTO_TRACING_CORE_DATA_SOURCE_CONFIG_H_
726 #define INCLUDE_PERFETTO_TRACING_CORE_DATA_SOURCE_CONFIG_H_
727
728 // Creates the aliases in the ::perfetto namespace, doing things like:
729 // using ::perfetto::Foo = ::perfetto::protos::gen::Foo.
730 // See comments in forward_decls.h for the historical reasons of this
731 // indirection layer.
732 // gen_amalgamated expanded: #include "perfetto/tracing/core/forward_decls.h"
733
734 // gen_amalgamated expanded: #include "protos/perfetto/config/data_source_config.gen.h"
735
736 #endif // INCLUDE_PERFETTO_TRACING_CORE_DATA_SOURCE_CONFIG_H_
737 // gen_amalgamated begin header: include/perfetto/tracing/core/data_source_descriptor.h
738 // gen_amalgamated begin header: gen/protos/perfetto/common/data_source_descriptor.gen.h
739 // DO NOT EDIT. Autogenerated by Perfetto cppgen_plugin
740 #ifndef PERFETTO_PROTOS_PROTOS_PERFETTO_COMMON_DATA_SOURCE_DESCRIPTOR_PROTO_CPP_H_
741 #define PERFETTO_PROTOS_PROTOS_PERFETTO_COMMON_DATA_SOURCE_DESCRIPTOR_PROTO_CPP_H_
742
743 #include <stdint.h>
744 #include <bitset>
745 #include <vector>
746 #include <string>
747 #include <type_traits>
748
749 // gen_amalgamated expanded: #include "perfetto/protozero/cpp_message_obj.h"
750 // gen_amalgamated expanded: #include "perfetto/protozero/copyable_ptr.h"
751 // gen_amalgamated expanded: #include "perfetto/base/export.h"
752
753 namespace perfetto {
754 namespace protos {
755 namespace gen {
756 class DataSourceDescriptor;
757 } // namespace perfetto
758 } // namespace protos
759 } // namespace gen
760
761 namespace protozero {
762 class Message;
763 } // namespace protozero
764
765 namespace perfetto {
766 namespace protos {
767 namespace gen {
768
769 class PERFETTO_EXPORT DataSourceDescriptor : public ::protozero::CppMessageObj {
770 public:
771 enum FieldNumbers {
772 kNameFieldNumber = 1,
773 kWillNotifyOnStopFieldNumber = 2,
774 kWillNotifyOnStartFieldNumber = 3,
775 kHandlesIncrementalStateClearFieldNumber = 4,
776 kGpuCounterDescriptorFieldNumber = 5,
777 kTrackEventDescriptorFieldNumber = 6,
778 };
779
780 DataSourceDescriptor();
781 ~DataSourceDescriptor() override;
782 DataSourceDescriptor(DataSourceDescriptor&&) noexcept;
783 DataSourceDescriptor& operator=(DataSourceDescriptor&&);
784 DataSourceDescriptor(const DataSourceDescriptor&);
785 DataSourceDescriptor& operator=(const DataSourceDescriptor&);
786 bool operator==(const DataSourceDescriptor&) const;
787 bool operator!=(const DataSourceDescriptor& other) const { return !(*this == other); }
788
789 bool ParseFromArray(const void*, size_t) override;
790 std::string SerializeAsString() const override;
791 std::vector<uint8_t> SerializeAsArray() const override;
792 void Serialize(::protozero::Message*) const;
793
has_name()794 bool has_name() const { return _has_field_[1]; }
name()795 const std::string& name() const { return name_; }
set_name(const std::string & value)796 void set_name(const std::string& value) { name_ = value; _has_field_.set(1); }
797
has_will_notify_on_stop()798 bool has_will_notify_on_stop() const { return _has_field_[2]; }
will_notify_on_stop()799 bool will_notify_on_stop() const { return will_notify_on_stop_; }
set_will_notify_on_stop(bool value)800 void set_will_notify_on_stop(bool value) { will_notify_on_stop_ = value; _has_field_.set(2); }
801
has_will_notify_on_start()802 bool has_will_notify_on_start() const { return _has_field_[3]; }
will_notify_on_start()803 bool will_notify_on_start() const { return will_notify_on_start_; }
set_will_notify_on_start(bool value)804 void set_will_notify_on_start(bool value) { will_notify_on_start_ = value; _has_field_.set(3); }
805
has_handles_incremental_state_clear()806 bool has_handles_incremental_state_clear() const { return _has_field_[4]; }
handles_incremental_state_clear()807 bool handles_incremental_state_clear() const { return handles_incremental_state_clear_; }
set_handles_incremental_state_clear(bool value)808 void set_handles_incremental_state_clear(bool value) { handles_incremental_state_clear_ = value; _has_field_.set(4); }
809
gpu_counter_descriptor_raw()810 const std::string& gpu_counter_descriptor_raw() const { return gpu_counter_descriptor_; }
set_gpu_counter_descriptor_raw(const std::string & raw)811 void set_gpu_counter_descriptor_raw(const std::string& raw) { gpu_counter_descriptor_ = raw; _has_field_.set(5); }
812
track_event_descriptor_raw()813 const std::string& track_event_descriptor_raw() const { return track_event_descriptor_; }
set_track_event_descriptor_raw(const std::string & raw)814 void set_track_event_descriptor_raw(const std::string& raw) { track_event_descriptor_ = raw; _has_field_.set(6); }
815
816 private:
817 std::string name_{};
818 bool will_notify_on_stop_{};
819 bool will_notify_on_start_{};
820 bool handles_incremental_state_clear_{};
821 std::string gpu_counter_descriptor_; // [lazy=true]
822 std::string track_event_descriptor_; // [lazy=true]
823
824 // Allows to preserve unknown protobuf fields for compatibility
825 // with future versions of .proto files.
826 std::string unknown_fields_;
827
828 std::bitset<7> _has_field_{};
829 };
830
831 } // namespace perfetto
832 } // namespace protos
833 } // namespace gen
834
835 #endif // PERFETTO_PROTOS_PROTOS_PERFETTO_COMMON_DATA_SOURCE_DESCRIPTOR_PROTO_CPP_H_
836 /*
837 * Copyright (C) 2017 The Android Open Source Project
838 *
839 * Licensed under the Apache License, Version 2.0 (the "License");
840 * you may not use this file except in compliance with the License.
841 * You may obtain a copy of the License at
842 *
843 * http://www.apache.org/licenses/LICENSE-2.0
844 *
845 * Unless required by applicable law or agreed to in writing, software
846 * distributed under the License is distributed on an "AS IS" BASIS,
847 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
848 * See the License for the specific language governing permissions and
849 * limitations under the License.
850 */
851
852 #ifndef INCLUDE_PERFETTO_TRACING_CORE_DATA_SOURCE_DESCRIPTOR_H_
853 #define INCLUDE_PERFETTO_TRACING_CORE_DATA_SOURCE_DESCRIPTOR_H_
854
855 // Creates the aliases in the ::perfetto namespace, doing things like:
856 // using ::perfetto::Foo = ::perfetto::protos::gen::Foo.
857 // See comments in forward_decls.h for the historical reasons of this
858 // indirection layer.
859 // gen_amalgamated expanded: #include "perfetto/tracing/core/forward_decls.h"
860
861 // gen_amalgamated expanded: #include "protos/perfetto/common/data_source_descriptor.gen.h"
862
863 #endif // INCLUDE_PERFETTO_TRACING_CORE_DATA_SOURCE_DESCRIPTOR_H_
864 // gen_amalgamated begin header: include/perfetto/tracing/core/trace_config.h
865 // gen_amalgamated begin header: gen/protos/perfetto/config/trace_config.gen.h
866 // DO NOT EDIT. Autogenerated by Perfetto cppgen_plugin
867 #ifndef PERFETTO_PROTOS_PROTOS_PERFETTO_CONFIG_TRACE_CONFIG_PROTO_CPP_H_
868 #define PERFETTO_PROTOS_PROTOS_PERFETTO_CONFIG_TRACE_CONFIG_PROTO_CPP_H_
869
870 #include <stdint.h>
871 #include <bitset>
872 #include <vector>
873 #include <string>
874 #include <type_traits>
875
876 // gen_amalgamated expanded: #include "perfetto/protozero/cpp_message_obj.h"
877 // gen_amalgamated expanded: #include "perfetto/protozero/copyable_ptr.h"
878 // gen_amalgamated expanded: #include "perfetto/base/export.h"
879
880 namespace perfetto {
881 namespace protos {
882 namespace gen {
883 class TraceConfig;
884 class TraceConfig_IncidentReportConfig;
885 class TraceConfig_IncrementalStateConfig;
886 class TraceConfig_TriggerConfig;
887 class TraceConfig_TriggerConfig_Trigger;
888 class TraceConfig_GuardrailOverrides;
889 class TraceConfig_StatsdMetadata;
890 class TraceConfig_ProducerConfig;
891 class TraceConfig_BuiltinDataSource;
892 class TraceConfig_DataSource;
893 class DataSourceConfig;
894 class TestConfig;
895 class TestConfig_DummyFields;
896 class ChromeConfig;
897 class TraceConfig_BufferConfig;
898 enum TraceConfig_LockdownModeOperation : int;
899 enum TraceConfig_CompressionType : int;
900 enum TraceConfig_TriggerConfig_TriggerMode : int;
901 enum BuiltinClock : int;
902 enum TraceConfig_BufferConfig_FillPolicy : int;
903 } // namespace perfetto
904 } // namespace protos
905 } // namespace gen
906
907 namespace protozero {
908 class Message;
909 } // namespace protozero
910
911 namespace perfetto {
912 namespace protos {
913 namespace gen {
914 enum TraceConfig_LockdownModeOperation : int {
915 TraceConfig_LockdownModeOperation_LOCKDOWN_UNCHANGED = 0,
916 TraceConfig_LockdownModeOperation_LOCKDOWN_CLEAR = 1,
917 TraceConfig_LockdownModeOperation_LOCKDOWN_SET = 2,
918 };
919 enum TraceConfig_CompressionType : int {
920 TraceConfig_CompressionType_COMPRESSION_TYPE_UNSPECIFIED = 0,
921 TraceConfig_CompressionType_COMPRESSION_TYPE_DEFLATE = 1,
922 };
923 enum TraceConfig_TriggerConfig_TriggerMode : int {
924 TraceConfig_TriggerConfig_TriggerMode_UNSPECIFIED = 0,
925 TraceConfig_TriggerConfig_TriggerMode_START_TRACING = 1,
926 TraceConfig_TriggerConfig_TriggerMode_STOP_TRACING = 2,
927 };
928 enum TraceConfig_BufferConfig_FillPolicy : int {
929 TraceConfig_BufferConfig_FillPolicy_UNSPECIFIED = 0,
930 TraceConfig_BufferConfig_FillPolicy_RING_BUFFER = 1,
931 TraceConfig_BufferConfig_FillPolicy_DISCARD = 2,
932 };
933
934 class PERFETTO_EXPORT TraceConfig : public ::protozero::CppMessageObj {
935 public:
936 using BufferConfig = TraceConfig_BufferConfig;
937 using DataSource = TraceConfig_DataSource;
938 using BuiltinDataSource = TraceConfig_BuiltinDataSource;
939 using ProducerConfig = TraceConfig_ProducerConfig;
940 using StatsdMetadata = TraceConfig_StatsdMetadata;
941 using GuardrailOverrides = TraceConfig_GuardrailOverrides;
942 using TriggerConfig = TraceConfig_TriggerConfig;
943 using IncrementalStateConfig = TraceConfig_IncrementalStateConfig;
944 using IncidentReportConfig = TraceConfig_IncidentReportConfig;
945 using LockdownModeOperation = TraceConfig_LockdownModeOperation;
946 static constexpr auto LOCKDOWN_UNCHANGED = TraceConfig_LockdownModeOperation_LOCKDOWN_UNCHANGED;
947 static constexpr auto LOCKDOWN_CLEAR = TraceConfig_LockdownModeOperation_LOCKDOWN_CLEAR;
948 static constexpr auto LOCKDOWN_SET = TraceConfig_LockdownModeOperation_LOCKDOWN_SET;
949 static constexpr auto LockdownModeOperation_MIN = TraceConfig_LockdownModeOperation_LOCKDOWN_UNCHANGED;
950 static constexpr auto LockdownModeOperation_MAX = TraceConfig_LockdownModeOperation_LOCKDOWN_SET;
951 using CompressionType = TraceConfig_CompressionType;
952 static constexpr auto COMPRESSION_TYPE_UNSPECIFIED = TraceConfig_CompressionType_COMPRESSION_TYPE_UNSPECIFIED;
953 static constexpr auto COMPRESSION_TYPE_DEFLATE = TraceConfig_CompressionType_COMPRESSION_TYPE_DEFLATE;
954 static constexpr auto CompressionType_MIN = TraceConfig_CompressionType_COMPRESSION_TYPE_UNSPECIFIED;
955 static constexpr auto CompressionType_MAX = TraceConfig_CompressionType_COMPRESSION_TYPE_DEFLATE;
956 enum FieldNumbers {
957 kBuffersFieldNumber = 1,
958 kDataSourcesFieldNumber = 2,
959 kBuiltinDataSourcesFieldNumber = 20,
960 kDurationMsFieldNumber = 3,
961 kEnableExtraGuardrailsFieldNumber = 4,
962 kLockdownModeFieldNumber = 5,
963 kProducersFieldNumber = 6,
964 kStatsdMetadataFieldNumber = 7,
965 kWriteIntoFileFieldNumber = 8,
966 kOutputPathFieldNumber = 29,
967 kFileWritePeriodMsFieldNumber = 9,
968 kMaxFileSizeBytesFieldNumber = 10,
969 kGuardrailOverridesFieldNumber = 11,
970 kDeferredStartFieldNumber = 12,
971 kFlushPeriodMsFieldNumber = 13,
972 kFlushTimeoutMsFieldNumber = 14,
973 kDataSourceStopTimeoutMsFieldNumber = 23,
974 kNotifyTraceurFieldNumber = 16,
975 kTriggerConfigFieldNumber = 17,
976 kActivateTriggersFieldNumber = 18,
977 kIncrementalStateConfigFieldNumber = 21,
978 kAllowUserBuildTracingFieldNumber = 19,
979 kUniqueSessionNameFieldNumber = 22,
980 kCompressionTypeFieldNumber = 24,
981 kIncidentReportConfigFieldNumber = 25,
982 kTraceUuidMsbFieldNumber = 27,
983 kTraceUuidLsbFieldNumber = 28,
984 };
985
986 TraceConfig();
987 ~TraceConfig() override;
988 TraceConfig(TraceConfig&&) noexcept;
989 TraceConfig& operator=(TraceConfig&&);
990 TraceConfig(const TraceConfig&);
991 TraceConfig& operator=(const TraceConfig&);
992 bool operator==(const TraceConfig&) const;
993 bool operator!=(const TraceConfig& other) const { return !(*this == other); }
994
995 bool ParseFromArray(const void*, size_t) override;
996 std::string SerializeAsString() const override;
997 std::vector<uint8_t> SerializeAsArray() const override;
998 void Serialize(::protozero::Message*) const;
999
buffers_size()1000 int buffers_size() const { return static_cast<int>(buffers_.size()); }
buffers()1001 const std::vector<TraceConfig_BufferConfig>& buffers() const { return buffers_; }
mutable_buffers()1002 std::vector<TraceConfig_BufferConfig>* mutable_buffers() { return &buffers_; }
clear_buffers()1003 void clear_buffers() { buffers_.clear(); }
add_buffers()1004 TraceConfig_BufferConfig* add_buffers() { buffers_.emplace_back(); return &buffers_.back(); }
1005
data_sources_size()1006 int data_sources_size() const { return static_cast<int>(data_sources_.size()); }
data_sources()1007 const std::vector<TraceConfig_DataSource>& data_sources() const { return data_sources_; }
mutable_data_sources()1008 std::vector<TraceConfig_DataSource>* mutable_data_sources() { return &data_sources_; }
clear_data_sources()1009 void clear_data_sources() { data_sources_.clear(); }
add_data_sources()1010 TraceConfig_DataSource* add_data_sources() { data_sources_.emplace_back(); return &data_sources_.back(); }
1011
has_builtin_data_sources()1012 bool has_builtin_data_sources() const { return _has_field_[20]; }
builtin_data_sources()1013 const TraceConfig_BuiltinDataSource& builtin_data_sources() const { return *builtin_data_sources_; }
mutable_builtin_data_sources()1014 TraceConfig_BuiltinDataSource* mutable_builtin_data_sources() { _has_field_.set(20); return builtin_data_sources_.get(); }
1015
has_duration_ms()1016 bool has_duration_ms() const { return _has_field_[3]; }
duration_ms()1017 uint32_t duration_ms() const { return duration_ms_; }
set_duration_ms(uint32_t value)1018 void set_duration_ms(uint32_t value) { duration_ms_ = value; _has_field_.set(3); }
1019
has_enable_extra_guardrails()1020 bool has_enable_extra_guardrails() const { return _has_field_[4]; }
enable_extra_guardrails()1021 bool enable_extra_guardrails() const { return enable_extra_guardrails_; }
set_enable_extra_guardrails(bool value)1022 void set_enable_extra_guardrails(bool value) { enable_extra_guardrails_ = value; _has_field_.set(4); }
1023
has_lockdown_mode()1024 bool has_lockdown_mode() const { return _has_field_[5]; }
lockdown_mode()1025 TraceConfig_LockdownModeOperation lockdown_mode() const { return lockdown_mode_; }
set_lockdown_mode(TraceConfig_LockdownModeOperation value)1026 void set_lockdown_mode(TraceConfig_LockdownModeOperation value) { lockdown_mode_ = value; _has_field_.set(5); }
1027
producers_size()1028 int producers_size() const { return static_cast<int>(producers_.size()); }
producers()1029 const std::vector<TraceConfig_ProducerConfig>& producers() const { return producers_; }
mutable_producers()1030 std::vector<TraceConfig_ProducerConfig>* mutable_producers() { return &producers_; }
clear_producers()1031 void clear_producers() { producers_.clear(); }
add_producers()1032 TraceConfig_ProducerConfig* add_producers() { producers_.emplace_back(); return &producers_.back(); }
1033
has_statsd_metadata()1034 bool has_statsd_metadata() const { return _has_field_[7]; }
statsd_metadata()1035 const TraceConfig_StatsdMetadata& statsd_metadata() const { return *statsd_metadata_; }
mutable_statsd_metadata()1036 TraceConfig_StatsdMetadata* mutable_statsd_metadata() { _has_field_.set(7); return statsd_metadata_.get(); }
1037
has_write_into_file()1038 bool has_write_into_file() const { return _has_field_[8]; }
write_into_file()1039 bool write_into_file() const { return write_into_file_; }
set_write_into_file(bool value)1040 void set_write_into_file(bool value) { write_into_file_ = value; _has_field_.set(8); }
1041
has_output_path()1042 bool has_output_path() const { return _has_field_[29]; }
output_path()1043 const std::string& output_path() const { return output_path_; }
set_output_path(const std::string & value)1044 void set_output_path(const std::string& value) { output_path_ = value; _has_field_.set(29); }
1045
has_file_write_period_ms()1046 bool has_file_write_period_ms() const { return _has_field_[9]; }
file_write_period_ms()1047 uint32_t file_write_period_ms() const { return file_write_period_ms_; }
set_file_write_period_ms(uint32_t value)1048 void set_file_write_period_ms(uint32_t value) { file_write_period_ms_ = value; _has_field_.set(9); }
1049
has_max_file_size_bytes()1050 bool has_max_file_size_bytes() const { return _has_field_[10]; }
max_file_size_bytes()1051 uint64_t max_file_size_bytes() const { return max_file_size_bytes_; }
set_max_file_size_bytes(uint64_t value)1052 void set_max_file_size_bytes(uint64_t value) { max_file_size_bytes_ = value; _has_field_.set(10); }
1053
has_guardrail_overrides()1054 bool has_guardrail_overrides() const { return _has_field_[11]; }
guardrail_overrides()1055 const TraceConfig_GuardrailOverrides& guardrail_overrides() const { return *guardrail_overrides_; }
mutable_guardrail_overrides()1056 TraceConfig_GuardrailOverrides* mutable_guardrail_overrides() { _has_field_.set(11); return guardrail_overrides_.get(); }
1057
has_deferred_start()1058 bool has_deferred_start() const { return _has_field_[12]; }
deferred_start()1059 bool deferred_start() const { return deferred_start_; }
set_deferred_start(bool value)1060 void set_deferred_start(bool value) { deferred_start_ = value; _has_field_.set(12); }
1061
has_flush_period_ms()1062 bool has_flush_period_ms() const { return _has_field_[13]; }
flush_period_ms()1063 uint32_t flush_period_ms() const { return flush_period_ms_; }
set_flush_period_ms(uint32_t value)1064 void set_flush_period_ms(uint32_t value) { flush_period_ms_ = value; _has_field_.set(13); }
1065
has_flush_timeout_ms()1066 bool has_flush_timeout_ms() const { return _has_field_[14]; }
flush_timeout_ms()1067 uint32_t flush_timeout_ms() const { return flush_timeout_ms_; }
set_flush_timeout_ms(uint32_t value)1068 void set_flush_timeout_ms(uint32_t value) { flush_timeout_ms_ = value; _has_field_.set(14); }
1069
has_data_source_stop_timeout_ms()1070 bool has_data_source_stop_timeout_ms() const { return _has_field_[23]; }
data_source_stop_timeout_ms()1071 uint32_t data_source_stop_timeout_ms() const { return data_source_stop_timeout_ms_; }
set_data_source_stop_timeout_ms(uint32_t value)1072 void set_data_source_stop_timeout_ms(uint32_t value) { data_source_stop_timeout_ms_ = value; _has_field_.set(23); }
1073
has_notify_traceur()1074 bool has_notify_traceur() const { return _has_field_[16]; }
notify_traceur()1075 bool notify_traceur() const { return notify_traceur_; }
set_notify_traceur(bool value)1076 void set_notify_traceur(bool value) { notify_traceur_ = value; _has_field_.set(16); }
1077
has_trigger_config()1078 bool has_trigger_config() const { return _has_field_[17]; }
trigger_config()1079 const TraceConfig_TriggerConfig& trigger_config() const { return *trigger_config_; }
mutable_trigger_config()1080 TraceConfig_TriggerConfig* mutable_trigger_config() { _has_field_.set(17); return trigger_config_.get(); }
1081
activate_triggers_size()1082 int activate_triggers_size() const { return static_cast<int>(activate_triggers_.size()); }
activate_triggers()1083 const std::vector<std::string>& activate_triggers() const { return activate_triggers_; }
mutable_activate_triggers()1084 std::vector<std::string>* mutable_activate_triggers() { return &activate_triggers_; }
clear_activate_triggers()1085 void clear_activate_triggers() { activate_triggers_.clear(); }
add_activate_triggers(std::string value)1086 void add_activate_triggers(std::string value) { activate_triggers_.emplace_back(value); }
add_activate_triggers()1087 std::string* add_activate_triggers() { activate_triggers_.emplace_back(); return &activate_triggers_.back(); }
1088
has_incremental_state_config()1089 bool has_incremental_state_config() const { return _has_field_[21]; }
incremental_state_config()1090 const TraceConfig_IncrementalStateConfig& incremental_state_config() const { return *incremental_state_config_; }
mutable_incremental_state_config()1091 TraceConfig_IncrementalStateConfig* mutable_incremental_state_config() { _has_field_.set(21); return incremental_state_config_.get(); }
1092
has_allow_user_build_tracing()1093 bool has_allow_user_build_tracing() const { return _has_field_[19]; }
allow_user_build_tracing()1094 bool allow_user_build_tracing() const { return allow_user_build_tracing_; }
set_allow_user_build_tracing(bool value)1095 void set_allow_user_build_tracing(bool value) { allow_user_build_tracing_ = value; _has_field_.set(19); }
1096
has_unique_session_name()1097 bool has_unique_session_name() const { return _has_field_[22]; }
unique_session_name()1098 const std::string& unique_session_name() const { return unique_session_name_; }
set_unique_session_name(const std::string & value)1099 void set_unique_session_name(const std::string& value) { unique_session_name_ = value; _has_field_.set(22); }
1100
has_compression_type()1101 bool has_compression_type() const { return _has_field_[24]; }
compression_type()1102 TraceConfig_CompressionType compression_type() const { return compression_type_; }
set_compression_type(TraceConfig_CompressionType value)1103 void set_compression_type(TraceConfig_CompressionType value) { compression_type_ = value; _has_field_.set(24); }
1104
has_incident_report_config()1105 bool has_incident_report_config() const { return _has_field_[25]; }
incident_report_config()1106 const TraceConfig_IncidentReportConfig& incident_report_config() const { return *incident_report_config_; }
mutable_incident_report_config()1107 TraceConfig_IncidentReportConfig* mutable_incident_report_config() { _has_field_.set(25); return incident_report_config_.get(); }
1108
has_trace_uuid_msb()1109 bool has_trace_uuid_msb() const { return _has_field_[27]; }
trace_uuid_msb()1110 int64_t trace_uuid_msb() const { return trace_uuid_msb_; }
set_trace_uuid_msb(int64_t value)1111 void set_trace_uuid_msb(int64_t value) { trace_uuid_msb_ = value; _has_field_.set(27); }
1112
has_trace_uuid_lsb()1113 bool has_trace_uuid_lsb() const { return _has_field_[28]; }
trace_uuid_lsb()1114 int64_t trace_uuid_lsb() const { return trace_uuid_lsb_; }
set_trace_uuid_lsb(int64_t value)1115 void set_trace_uuid_lsb(int64_t value) { trace_uuid_lsb_ = value; _has_field_.set(28); }
1116
1117 private:
1118 std::vector<TraceConfig_BufferConfig> buffers_;
1119 std::vector<TraceConfig_DataSource> data_sources_;
1120 ::protozero::CopyablePtr<TraceConfig_BuiltinDataSource> builtin_data_sources_;
1121 uint32_t duration_ms_{};
1122 bool enable_extra_guardrails_{};
1123 TraceConfig_LockdownModeOperation lockdown_mode_{};
1124 std::vector<TraceConfig_ProducerConfig> producers_;
1125 ::protozero::CopyablePtr<TraceConfig_StatsdMetadata> statsd_metadata_;
1126 bool write_into_file_{};
1127 std::string output_path_{};
1128 uint32_t file_write_period_ms_{};
1129 uint64_t max_file_size_bytes_{};
1130 ::protozero::CopyablePtr<TraceConfig_GuardrailOverrides> guardrail_overrides_;
1131 bool deferred_start_{};
1132 uint32_t flush_period_ms_{};
1133 uint32_t flush_timeout_ms_{};
1134 uint32_t data_source_stop_timeout_ms_{};
1135 bool notify_traceur_{};
1136 ::protozero::CopyablePtr<TraceConfig_TriggerConfig> trigger_config_;
1137 std::vector<std::string> activate_triggers_;
1138 ::protozero::CopyablePtr<TraceConfig_IncrementalStateConfig> incremental_state_config_;
1139 bool allow_user_build_tracing_{};
1140 std::string unique_session_name_{};
1141 TraceConfig_CompressionType compression_type_{};
1142 ::protozero::CopyablePtr<TraceConfig_IncidentReportConfig> incident_report_config_;
1143 int64_t trace_uuid_msb_{};
1144 int64_t trace_uuid_lsb_{};
1145
1146 // Allows to preserve unknown protobuf fields for compatibility
1147 // with future versions of .proto files.
1148 std::string unknown_fields_;
1149
1150 std::bitset<30> _has_field_{};
1151 };
1152
1153
1154 class PERFETTO_EXPORT TraceConfig_IncidentReportConfig : public ::protozero::CppMessageObj {
1155 public:
1156 enum FieldNumbers {
1157 kDestinationPackageFieldNumber = 1,
1158 kDestinationClassFieldNumber = 2,
1159 kPrivacyLevelFieldNumber = 3,
1160 kSkipDropboxFieldNumber = 4,
1161 };
1162
1163 TraceConfig_IncidentReportConfig();
1164 ~TraceConfig_IncidentReportConfig() override;
1165 TraceConfig_IncidentReportConfig(TraceConfig_IncidentReportConfig&&) noexcept;
1166 TraceConfig_IncidentReportConfig& operator=(TraceConfig_IncidentReportConfig&&);
1167 TraceConfig_IncidentReportConfig(const TraceConfig_IncidentReportConfig&);
1168 TraceConfig_IncidentReportConfig& operator=(const TraceConfig_IncidentReportConfig&);
1169 bool operator==(const TraceConfig_IncidentReportConfig&) const;
1170 bool operator!=(const TraceConfig_IncidentReportConfig& other) const { return !(*this == other); }
1171
1172 bool ParseFromArray(const void*, size_t) override;
1173 std::string SerializeAsString() const override;
1174 std::vector<uint8_t> SerializeAsArray() const override;
1175 void Serialize(::protozero::Message*) const;
1176
has_destination_package()1177 bool has_destination_package() const { return _has_field_[1]; }
destination_package()1178 const std::string& destination_package() const { return destination_package_; }
set_destination_package(const std::string & value)1179 void set_destination_package(const std::string& value) { destination_package_ = value; _has_field_.set(1); }
1180
has_destination_class()1181 bool has_destination_class() const { return _has_field_[2]; }
destination_class()1182 const std::string& destination_class() const { return destination_class_; }
set_destination_class(const std::string & value)1183 void set_destination_class(const std::string& value) { destination_class_ = value; _has_field_.set(2); }
1184
has_privacy_level()1185 bool has_privacy_level() const { return _has_field_[3]; }
privacy_level()1186 int32_t privacy_level() const { return privacy_level_; }
set_privacy_level(int32_t value)1187 void set_privacy_level(int32_t value) { privacy_level_ = value; _has_field_.set(3); }
1188
has_skip_dropbox()1189 bool has_skip_dropbox() const { return _has_field_[4]; }
skip_dropbox()1190 bool skip_dropbox() const { return skip_dropbox_; }
set_skip_dropbox(bool value)1191 void set_skip_dropbox(bool value) { skip_dropbox_ = value; _has_field_.set(4); }
1192
1193 private:
1194 std::string destination_package_{};
1195 std::string destination_class_{};
1196 int32_t privacy_level_{};
1197 bool skip_dropbox_{};
1198
1199 // Allows to preserve unknown protobuf fields for compatibility
1200 // with future versions of .proto files.
1201 std::string unknown_fields_;
1202
1203 std::bitset<5> _has_field_{};
1204 };
1205
1206
1207 class PERFETTO_EXPORT TraceConfig_IncrementalStateConfig : public ::protozero::CppMessageObj {
1208 public:
1209 enum FieldNumbers {
1210 kClearPeriodMsFieldNumber = 1,
1211 };
1212
1213 TraceConfig_IncrementalStateConfig();
1214 ~TraceConfig_IncrementalStateConfig() override;
1215 TraceConfig_IncrementalStateConfig(TraceConfig_IncrementalStateConfig&&) noexcept;
1216 TraceConfig_IncrementalStateConfig& operator=(TraceConfig_IncrementalStateConfig&&);
1217 TraceConfig_IncrementalStateConfig(const TraceConfig_IncrementalStateConfig&);
1218 TraceConfig_IncrementalStateConfig& operator=(const TraceConfig_IncrementalStateConfig&);
1219 bool operator==(const TraceConfig_IncrementalStateConfig&) const;
1220 bool operator!=(const TraceConfig_IncrementalStateConfig& other) const { return !(*this == other); }
1221
1222 bool ParseFromArray(const void*, size_t) override;
1223 std::string SerializeAsString() const override;
1224 std::vector<uint8_t> SerializeAsArray() const override;
1225 void Serialize(::protozero::Message*) const;
1226
has_clear_period_ms()1227 bool has_clear_period_ms() const { return _has_field_[1]; }
clear_period_ms()1228 uint32_t clear_period_ms() const { return clear_period_ms_; }
set_clear_period_ms(uint32_t value)1229 void set_clear_period_ms(uint32_t value) { clear_period_ms_ = value; _has_field_.set(1); }
1230
1231 private:
1232 uint32_t clear_period_ms_{};
1233
1234 // Allows to preserve unknown protobuf fields for compatibility
1235 // with future versions of .proto files.
1236 std::string unknown_fields_;
1237
1238 std::bitset<2> _has_field_{};
1239 };
1240
1241
1242 class PERFETTO_EXPORT TraceConfig_TriggerConfig : public ::protozero::CppMessageObj {
1243 public:
1244 using Trigger = TraceConfig_TriggerConfig_Trigger;
1245 using TriggerMode = TraceConfig_TriggerConfig_TriggerMode;
1246 static constexpr auto UNSPECIFIED = TraceConfig_TriggerConfig_TriggerMode_UNSPECIFIED;
1247 static constexpr auto START_TRACING = TraceConfig_TriggerConfig_TriggerMode_START_TRACING;
1248 static constexpr auto STOP_TRACING = TraceConfig_TriggerConfig_TriggerMode_STOP_TRACING;
1249 static constexpr auto TriggerMode_MIN = TraceConfig_TriggerConfig_TriggerMode_UNSPECIFIED;
1250 static constexpr auto TriggerMode_MAX = TraceConfig_TriggerConfig_TriggerMode_STOP_TRACING;
1251 enum FieldNumbers {
1252 kTriggerModeFieldNumber = 1,
1253 kTriggersFieldNumber = 2,
1254 kTriggerTimeoutMsFieldNumber = 3,
1255 };
1256
1257 TraceConfig_TriggerConfig();
1258 ~TraceConfig_TriggerConfig() override;
1259 TraceConfig_TriggerConfig(TraceConfig_TriggerConfig&&) noexcept;
1260 TraceConfig_TriggerConfig& operator=(TraceConfig_TriggerConfig&&);
1261 TraceConfig_TriggerConfig(const TraceConfig_TriggerConfig&);
1262 TraceConfig_TriggerConfig& operator=(const TraceConfig_TriggerConfig&);
1263 bool operator==(const TraceConfig_TriggerConfig&) const;
1264 bool operator!=(const TraceConfig_TriggerConfig& other) const { return !(*this == other); }
1265
1266 bool ParseFromArray(const void*, size_t) override;
1267 std::string SerializeAsString() const override;
1268 std::vector<uint8_t> SerializeAsArray() const override;
1269 void Serialize(::protozero::Message*) const;
1270
has_trigger_mode()1271 bool has_trigger_mode() const { return _has_field_[1]; }
trigger_mode()1272 TraceConfig_TriggerConfig_TriggerMode trigger_mode() const { return trigger_mode_; }
set_trigger_mode(TraceConfig_TriggerConfig_TriggerMode value)1273 void set_trigger_mode(TraceConfig_TriggerConfig_TriggerMode value) { trigger_mode_ = value; _has_field_.set(1); }
1274
triggers_size()1275 int triggers_size() const { return static_cast<int>(triggers_.size()); }
triggers()1276 const std::vector<TraceConfig_TriggerConfig_Trigger>& triggers() const { return triggers_; }
mutable_triggers()1277 std::vector<TraceConfig_TriggerConfig_Trigger>* mutable_triggers() { return &triggers_; }
clear_triggers()1278 void clear_triggers() { triggers_.clear(); }
add_triggers()1279 TraceConfig_TriggerConfig_Trigger* add_triggers() { triggers_.emplace_back(); return &triggers_.back(); }
1280
has_trigger_timeout_ms()1281 bool has_trigger_timeout_ms() const { return _has_field_[3]; }
trigger_timeout_ms()1282 uint32_t trigger_timeout_ms() const { return trigger_timeout_ms_; }
set_trigger_timeout_ms(uint32_t value)1283 void set_trigger_timeout_ms(uint32_t value) { trigger_timeout_ms_ = value; _has_field_.set(3); }
1284
1285 private:
1286 TraceConfig_TriggerConfig_TriggerMode trigger_mode_{};
1287 std::vector<TraceConfig_TriggerConfig_Trigger> triggers_;
1288 uint32_t trigger_timeout_ms_{};
1289
1290 // Allows to preserve unknown protobuf fields for compatibility
1291 // with future versions of .proto files.
1292 std::string unknown_fields_;
1293
1294 std::bitset<4> _has_field_{};
1295 };
1296
1297
1298 class PERFETTO_EXPORT TraceConfig_TriggerConfig_Trigger : public ::protozero::CppMessageObj {
1299 public:
1300 enum FieldNumbers {
1301 kNameFieldNumber = 1,
1302 kProducerNameRegexFieldNumber = 2,
1303 kStopDelayMsFieldNumber = 3,
1304 };
1305
1306 TraceConfig_TriggerConfig_Trigger();
1307 ~TraceConfig_TriggerConfig_Trigger() override;
1308 TraceConfig_TriggerConfig_Trigger(TraceConfig_TriggerConfig_Trigger&&) noexcept;
1309 TraceConfig_TriggerConfig_Trigger& operator=(TraceConfig_TriggerConfig_Trigger&&);
1310 TraceConfig_TriggerConfig_Trigger(const TraceConfig_TriggerConfig_Trigger&);
1311 TraceConfig_TriggerConfig_Trigger& operator=(const TraceConfig_TriggerConfig_Trigger&);
1312 bool operator==(const TraceConfig_TriggerConfig_Trigger&) const;
1313 bool operator!=(const TraceConfig_TriggerConfig_Trigger& other) const { return !(*this == other); }
1314
1315 bool ParseFromArray(const void*, size_t) override;
1316 std::string SerializeAsString() const override;
1317 std::vector<uint8_t> SerializeAsArray() const override;
1318 void Serialize(::protozero::Message*) const;
1319
has_name()1320 bool has_name() const { return _has_field_[1]; }
name()1321 const std::string& name() const { return name_; }
set_name(const std::string & value)1322 void set_name(const std::string& value) { name_ = value; _has_field_.set(1); }
1323
has_producer_name_regex()1324 bool has_producer_name_regex() const { return _has_field_[2]; }
producer_name_regex()1325 const std::string& producer_name_regex() const { return producer_name_regex_; }
set_producer_name_regex(const std::string & value)1326 void set_producer_name_regex(const std::string& value) { producer_name_regex_ = value; _has_field_.set(2); }
1327
has_stop_delay_ms()1328 bool has_stop_delay_ms() const { return _has_field_[3]; }
stop_delay_ms()1329 uint32_t stop_delay_ms() const { return stop_delay_ms_; }
set_stop_delay_ms(uint32_t value)1330 void set_stop_delay_ms(uint32_t value) { stop_delay_ms_ = value; _has_field_.set(3); }
1331
1332 private:
1333 std::string name_{};
1334 std::string producer_name_regex_{};
1335 uint32_t stop_delay_ms_{};
1336
1337 // Allows to preserve unknown protobuf fields for compatibility
1338 // with future versions of .proto files.
1339 std::string unknown_fields_;
1340
1341 std::bitset<4> _has_field_{};
1342 };
1343
1344
1345 class PERFETTO_EXPORT TraceConfig_GuardrailOverrides : public ::protozero::CppMessageObj {
1346 public:
1347 enum FieldNumbers {
1348 kMaxUploadPerDayBytesFieldNumber = 1,
1349 };
1350
1351 TraceConfig_GuardrailOverrides();
1352 ~TraceConfig_GuardrailOverrides() override;
1353 TraceConfig_GuardrailOverrides(TraceConfig_GuardrailOverrides&&) noexcept;
1354 TraceConfig_GuardrailOverrides& operator=(TraceConfig_GuardrailOverrides&&);
1355 TraceConfig_GuardrailOverrides(const TraceConfig_GuardrailOverrides&);
1356 TraceConfig_GuardrailOverrides& operator=(const TraceConfig_GuardrailOverrides&);
1357 bool operator==(const TraceConfig_GuardrailOverrides&) const;
1358 bool operator!=(const TraceConfig_GuardrailOverrides& other) const { return !(*this == other); }
1359
1360 bool ParseFromArray(const void*, size_t) override;
1361 std::string SerializeAsString() const override;
1362 std::vector<uint8_t> SerializeAsArray() const override;
1363 void Serialize(::protozero::Message*) const;
1364
has_max_upload_per_day_bytes()1365 bool has_max_upload_per_day_bytes() const { return _has_field_[1]; }
max_upload_per_day_bytes()1366 uint64_t max_upload_per_day_bytes() const { return max_upload_per_day_bytes_; }
set_max_upload_per_day_bytes(uint64_t value)1367 void set_max_upload_per_day_bytes(uint64_t value) { max_upload_per_day_bytes_ = value; _has_field_.set(1); }
1368
1369 private:
1370 uint64_t max_upload_per_day_bytes_{};
1371
1372 // Allows to preserve unknown protobuf fields for compatibility
1373 // with future versions of .proto files.
1374 std::string unknown_fields_;
1375
1376 std::bitset<2> _has_field_{};
1377 };
1378
1379
1380 class PERFETTO_EXPORT TraceConfig_StatsdMetadata : public ::protozero::CppMessageObj {
1381 public:
1382 enum FieldNumbers {
1383 kTriggeringAlertIdFieldNumber = 1,
1384 kTriggeringConfigUidFieldNumber = 2,
1385 kTriggeringConfigIdFieldNumber = 3,
1386 kTriggeringSubscriptionIdFieldNumber = 4,
1387 };
1388
1389 TraceConfig_StatsdMetadata();
1390 ~TraceConfig_StatsdMetadata() override;
1391 TraceConfig_StatsdMetadata(TraceConfig_StatsdMetadata&&) noexcept;
1392 TraceConfig_StatsdMetadata& operator=(TraceConfig_StatsdMetadata&&);
1393 TraceConfig_StatsdMetadata(const TraceConfig_StatsdMetadata&);
1394 TraceConfig_StatsdMetadata& operator=(const TraceConfig_StatsdMetadata&);
1395 bool operator==(const TraceConfig_StatsdMetadata&) const;
1396 bool operator!=(const TraceConfig_StatsdMetadata& other) const { return !(*this == other); }
1397
1398 bool ParseFromArray(const void*, size_t) override;
1399 std::string SerializeAsString() const override;
1400 std::vector<uint8_t> SerializeAsArray() const override;
1401 void Serialize(::protozero::Message*) const;
1402
has_triggering_alert_id()1403 bool has_triggering_alert_id() const { return _has_field_[1]; }
triggering_alert_id()1404 int64_t triggering_alert_id() const { return triggering_alert_id_; }
set_triggering_alert_id(int64_t value)1405 void set_triggering_alert_id(int64_t value) { triggering_alert_id_ = value; _has_field_.set(1); }
1406
has_triggering_config_uid()1407 bool has_triggering_config_uid() const { return _has_field_[2]; }
triggering_config_uid()1408 int32_t triggering_config_uid() const { return triggering_config_uid_; }
set_triggering_config_uid(int32_t value)1409 void set_triggering_config_uid(int32_t value) { triggering_config_uid_ = value; _has_field_.set(2); }
1410
has_triggering_config_id()1411 bool has_triggering_config_id() const { return _has_field_[3]; }
triggering_config_id()1412 int64_t triggering_config_id() const { return triggering_config_id_; }
set_triggering_config_id(int64_t value)1413 void set_triggering_config_id(int64_t value) { triggering_config_id_ = value; _has_field_.set(3); }
1414
has_triggering_subscription_id()1415 bool has_triggering_subscription_id() const { return _has_field_[4]; }
triggering_subscription_id()1416 int64_t triggering_subscription_id() const { return triggering_subscription_id_; }
set_triggering_subscription_id(int64_t value)1417 void set_triggering_subscription_id(int64_t value) { triggering_subscription_id_ = value; _has_field_.set(4); }
1418
1419 private:
1420 int64_t triggering_alert_id_{};
1421 int32_t triggering_config_uid_{};
1422 int64_t triggering_config_id_{};
1423 int64_t triggering_subscription_id_{};
1424
1425 // Allows to preserve unknown protobuf fields for compatibility
1426 // with future versions of .proto files.
1427 std::string unknown_fields_;
1428
1429 std::bitset<5> _has_field_{};
1430 };
1431
1432
1433 class PERFETTO_EXPORT TraceConfig_ProducerConfig : public ::protozero::CppMessageObj {
1434 public:
1435 enum FieldNumbers {
1436 kProducerNameFieldNumber = 1,
1437 kShmSizeKbFieldNumber = 2,
1438 kPageSizeKbFieldNumber = 3,
1439 };
1440
1441 TraceConfig_ProducerConfig();
1442 ~TraceConfig_ProducerConfig() override;
1443 TraceConfig_ProducerConfig(TraceConfig_ProducerConfig&&) noexcept;
1444 TraceConfig_ProducerConfig& operator=(TraceConfig_ProducerConfig&&);
1445 TraceConfig_ProducerConfig(const TraceConfig_ProducerConfig&);
1446 TraceConfig_ProducerConfig& operator=(const TraceConfig_ProducerConfig&);
1447 bool operator==(const TraceConfig_ProducerConfig&) const;
1448 bool operator!=(const TraceConfig_ProducerConfig& other) const { return !(*this == other); }
1449
1450 bool ParseFromArray(const void*, size_t) override;
1451 std::string SerializeAsString() const override;
1452 std::vector<uint8_t> SerializeAsArray() const override;
1453 void Serialize(::protozero::Message*) const;
1454
has_producer_name()1455 bool has_producer_name() const { return _has_field_[1]; }
producer_name()1456 const std::string& producer_name() const { return producer_name_; }
set_producer_name(const std::string & value)1457 void set_producer_name(const std::string& value) { producer_name_ = value; _has_field_.set(1); }
1458
has_shm_size_kb()1459 bool has_shm_size_kb() const { return _has_field_[2]; }
shm_size_kb()1460 uint32_t shm_size_kb() const { return shm_size_kb_; }
set_shm_size_kb(uint32_t value)1461 void set_shm_size_kb(uint32_t value) { shm_size_kb_ = value; _has_field_.set(2); }
1462
has_page_size_kb()1463 bool has_page_size_kb() const { return _has_field_[3]; }
page_size_kb()1464 uint32_t page_size_kb() const { return page_size_kb_; }
set_page_size_kb(uint32_t value)1465 void set_page_size_kb(uint32_t value) { page_size_kb_ = value; _has_field_.set(3); }
1466
1467 private:
1468 std::string producer_name_{};
1469 uint32_t shm_size_kb_{};
1470 uint32_t page_size_kb_{};
1471
1472 // Allows to preserve unknown protobuf fields for compatibility
1473 // with future versions of .proto files.
1474 std::string unknown_fields_;
1475
1476 std::bitset<4> _has_field_{};
1477 };
1478
1479
1480 class PERFETTO_EXPORT TraceConfig_BuiltinDataSource : public ::protozero::CppMessageObj {
1481 public:
1482 enum FieldNumbers {
1483 kDisableClockSnapshottingFieldNumber = 1,
1484 kDisableTraceConfigFieldNumber = 2,
1485 kDisableSystemInfoFieldNumber = 3,
1486 kDisableServiceEventsFieldNumber = 4,
1487 kPrimaryTraceClockFieldNumber = 5,
1488 kSnapshotIntervalMsFieldNumber = 6,
1489 };
1490
1491 TraceConfig_BuiltinDataSource();
1492 ~TraceConfig_BuiltinDataSource() override;
1493 TraceConfig_BuiltinDataSource(TraceConfig_BuiltinDataSource&&) noexcept;
1494 TraceConfig_BuiltinDataSource& operator=(TraceConfig_BuiltinDataSource&&);
1495 TraceConfig_BuiltinDataSource(const TraceConfig_BuiltinDataSource&);
1496 TraceConfig_BuiltinDataSource& operator=(const TraceConfig_BuiltinDataSource&);
1497 bool operator==(const TraceConfig_BuiltinDataSource&) const;
1498 bool operator!=(const TraceConfig_BuiltinDataSource& other) const { return !(*this == other); }
1499
1500 bool ParseFromArray(const void*, size_t) override;
1501 std::string SerializeAsString() const override;
1502 std::vector<uint8_t> SerializeAsArray() const override;
1503 void Serialize(::protozero::Message*) const;
1504
has_disable_clock_snapshotting()1505 bool has_disable_clock_snapshotting() const { return _has_field_[1]; }
disable_clock_snapshotting()1506 bool disable_clock_snapshotting() const { return disable_clock_snapshotting_; }
set_disable_clock_snapshotting(bool value)1507 void set_disable_clock_snapshotting(bool value) { disable_clock_snapshotting_ = value; _has_field_.set(1); }
1508
has_disable_trace_config()1509 bool has_disable_trace_config() const { return _has_field_[2]; }
disable_trace_config()1510 bool disable_trace_config() const { return disable_trace_config_; }
set_disable_trace_config(bool value)1511 void set_disable_trace_config(bool value) { disable_trace_config_ = value; _has_field_.set(2); }
1512
has_disable_system_info()1513 bool has_disable_system_info() const { return _has_field_[3]; }
disable_system_info()1514 bool disable_system_info() const { return disable_system_info_; }
set_disable_system_info(bool value)1515 void set_disable_system_info(bool value) { disable_system_info_ = value; _has_field_.set(3); }
1516
has_disable_service_events()1517 bool has_disable_service_events() const { return _has_field_[4]; }
disable_service_events()1518 bool disable_service_events() const { return disable_service_events_; }
set_disable_service_events(bool value)1519 void set_disable_service_events(bool value) { disable_service_events_ = value; _has_field_.set(4); }
1520
has_primary_trace_clock()1521 bool has_primary_trace_clock() const { return _has_field_[5]; }
primary_trace_clock()1522 BuiltinClock primary_trace_clock() const { return primary_trace_clock_; }
set_primary_trace_clock(BuiltinClock value)1523 void set_primary_trace_clock(BuiltinClock value) { primary_trace_clock_ = value; _has_field_.set(5); }
1524
has_snapshot_interval_ms()1525 bool has_snapshot_interval_ms() const { return _has_field_[6]; }
snapshot_interval_ms()1526 uint32_t snapshot_interval_ms() const { return snapshot_interval_ms_; }
set_snapshot_interval_ms(uint32_t value)1527 void set_snapshot_interval_ms(uint32_t value) { snapshot_interval_ms_ = value; _has_field_.set(6); }
1528
1529 private:
1530 bool disable_clock_snapshotting_{};
1531 bool disable_trace_config_{};
1532 bool disable_system_info_{};
1533 bool disable_service_events_{};
1534 BuiltinClock primary_trace_clock_{};
1535 uint32_t snapshot_interval_ms_{};
1536
1537 // Allows to preserve unknown protobuf fields for compatibility
1538 // with future versions of .proto files.
1539 std::string unknown_fields_;
1540
1541 std::bitset<7> _has_field_{};
1542 };
1543
1544
1545 class PERFETTO_EXPORT TraceConfig_DataSource : public ::protozero::CppMessageObj {
1546 public:
1547 enum FieldNumbers {
1548 kConfigFieldNumber = 1,
1549 kProducerNameFilterFieldNumber = 2,
1550 kProducerNameRegexFilterFieldNumber = 3,
1551 };
1552
1553 TraceConfig_DataSource();
1554 ~TraceConfig_DataSource() override;
1555 TraceConfig_DataSource(TraceConfig_DataSource&&) noexcept;
1556 TraceConfig_DataSource& operator=(TraceConfig_DataSource&&);
1557 TraceConfig_DataSource(const TraceConfig_DataSource&);
1558 TraceConfig_DataSource& operator=(const TraceConfig_DataSource&);
1559 bool operator==(const TraceConfig_DataSource&) const;
1560 bool operator!=(const TraceConfig_DataSource& other) const { return !(*this == other); }
1561
1562 bool ParseFromArray(const void*, size_t) override;
1563 std::string SerializeAsString() const override;
1564 std::vector<uint8_t> SerializeAsArray() const override;
1565 void Serialize(::protozero::Message*) const;
1566
has_config()1567 bool has_config() const { return _has_field_[1]; }
config()1568 const DataSourceConfig& config() const { return *config_; }
mutable_config()1569 DataSourceConfig* mutable_config() { _has_field_.set(1); return config_.get(); }
1570
producer_name_filter_size()1571 int producer_name_filter_size() const { return static_cast<int>(producer_name_filter_.size()); }
producer_name_filter()1572 const std::vector<std::string>& producer_name_filter() const { return producer_name_filter_; }
mutable_producer_name_filter()1573 std::vector<std::string>* mutable_producer_name_filter() { return &producer_name_filter_; }
clear_producer_name_filter()1574 void clear_producer_name_filter() { producer_name_filter_.clear(); }
add_producer_name_filter(std::string value)1575 void add_producer_name_filter(std::string value) { producer_name_filter_.emplace_back(value); }
add_producer_name_filter()1576 std::string* add_producer_name_filter() { producer_name_filter_.emplace_back(); return &producer_name_filter_.back(); }
1577
producer_name_regex_filter_size()1578 int producer_name_regex_filter_size() const { return static_cast<int>(producer_name_regex_filter_.size()); }
producer_name_regex_filter()1579 const std::vector<std::string>& producer_name_regex_filter() const { return producer_name_regex_filter_; }
mutable_producer_name_regex_filter()1580 std::vector<std::string>* mutable_producer_name_regex_filter() { return &producer_name_regex_filter_; }
clear_producer_name_regex_filter()1581 void clear_producer_name_regex_filter() { producer_name_regex_filter_.clear(); }
add_producer_name_regex_filter(std::string value)1582 void add_producer_name_regex_filter(std::string value) { producer_name_regex_filter_.emplace_back(value); }
add_producer_name_regex_filter()1583 std::string* add_producer_name_regex_filter() { producer_name_regex_filter_.emplace_back(); return &producer_name_regex_filter_.back(); }
1584
1585 private:
1586 ::protozero::CopyablePtr<DataSourceConfig> config_;
1587 std::vector<std::string> producer_name_filter_;
1588 std::vector<std::string> producer_name_regex_filter_;
1589
1590 // Allows to preserve unknown protobuf fields for compatibility
1591 // with future versions of .proto files.
1592 std::string unknown_fields_;
1593
1594 std::bitset<4> _has_field_{};
1595 };
1596
1597
1598 class PERFETTO_EXPORT TraceConfig_BufferConfig : public ::protozero::CppMessageObj {
1599 public:
1600 using FillPolicy = TraceConfig_BufferConfig_FillPolicy;
1601 static constexpr auto UNSPECIFIED = TraceConfig_BufferConfig_FillPolicy_UNSPECIFIED;
1602 static constexpr auto RING_BUFFER = TraceConfig_BufferConfig_FillPolicy_RING_BUFFER;
1603 static constexpr auto DISCARD = TraceConfig_BufferConfig_FillPolicy_DISCARD;
1604 static constexpr auto FillPolicy_MIN = TraceConfig_BufferConfig_FillPolicy_UNSPECIFIED;
1605 static constexpr auto FillPolicy_MAX = TraceConfig_BufferConfig_FillPolicy_DISCARD;
1606 enum FieldNumbers {
1607 kSizeKbFieldNumber = 1,
1608 kFillPolicyFieldNumber = 4,
1609 };
1610
1611 TraceConfig_BufferConfig();
1612 ~TraceConfig_BufferConfig() override;
1613 TraceConfig_BufferConfig(TraceConfig_BufferConfig&&) noexcept;
1614 TraceConfig_BufferConfig& operator=(TraceConfig_BufferConfig&&);
1615 TraceConfig_BufferConfig(const TraceConfig_BufferConfig&);
1616 TraceConfig_BufferConfig& operator=(const TraceConfig_BufferConfig&);
1617 bool operator==(const TraceConfig_BufferConfig&) const;
1618 bool operator!=(const TraceConfig_BufferConfig& other) const { return !(*this == other); }
1619
1620 bool ParseFromArray(const void*, size_t) override;
1621 std::string SerializeAsString() const override;
1622 std::vector<uint8_t> SerializeAsArray() const override;
1623 void Serialize(::protozero::Message*) const;
1624
has_size_kb()1625 bool has_size_kb() const { return _has_field_[1]; }
size_kb()1626 uint32_t size_kb() const { return size_kb_; }
set_size_kb(uint32_t value)1627 void set_size_kb(uint32_t value) { size_kb_ = value; _has_field_.set(1); }
1628
has_fill_policy()1629 bool has_fill_policy() const { return _has_field_[4]; }
fill_policy()1630 TraceConfig_BufferConfig_FillPolicy fill_policy() const { return fill_policy_; }
set_fill_policy(TraceConfig_BufferConfig_FillPolicy value)1631 void set_fill_policy(TraceConfig_BufferConfig_FillPolicy value) { fill_policy_ = value; _has_field_.set(4); }
1632
1633 private:
1634 uint32_t size_kb_{};
1635 TraceConfig_BufferConfig_FillPolicy fill_policy_{};
1636
1637 // Allows to preserve unknown protobuf fields for compatibility
1638 // with future versions of .proto files.
1639 std::string unknown_fields_;
1640
1641 std::bitset<5> _has_field_{};
1642 };
1643
1644 } // namespace perfetto
1645 } // namespace protos
1646 } // namespace gen
1647
1648 #endif // PERFETTO_PROTOS_PROTOS_PERFETTO_CONFIG_TRACE_CONFIG_PROTO_CPP_H_
1649 /*
1650 * Copyright (C) 2017 The Android Open Source Project
1651 *
1652 * Licensed under the Apache License, Version 2.0 (the "License");
1653 * you may not use this file except in compliance with the License.
1654 * You may obtain a copy of the License at
1655 *
1656 * http://www.apache.org/licenses/LICENSE-2.0
1657 *
1658 * Unless required by applicable law or agreed to in writing, software
1659 * distributed under the License is distributed on an "AS IS" BASIS,
1660 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1661 * See the License for the specific language governing permissions and
1662 * limitations under the License.
1663 */
1664
1665 #ifndef INCLUDE_PERFETTO_TRACING_CORE_TRACE_CONFIG_H_
1666 #define INCLUDE_PERFETTO_TRACING_CORE_TRACE_CONFIG_H_
1667
1668 // Creates the aliases in the ::perfetto namespace, doing things like:
1669 // using ::perfetto::Foo = ::perfetto::protos::gen::Foo.
1670 // See comments in forward_decls.h for the historical reasons of this
1671 // indirection layer.
1672 // gen_amalgamated expanded: #include "perfetto/tracing/core/forward_decls.h"
1673
1674 // gen_amalgamated expanded: #include "protos/perfetto/config/trace_config.gen.h"
1675
1676 #endif // INCLUDE_PERFETTO_TRACING_CORE_TRACE_CONFIG_H_
1677 // gen_amalgamated begin header: include/perfetto/tracing/data_source.h
1678 // gen_amalgamated begin header: include/perfetto/base/compiler.h
1679 /*
1680 * Copyright (C) 2019 The Android Open Source Project
1681 *
1682 * Licensed under the Apache License, Version 2.0 (the "License");
1683 * you may not use this file except in compliance with the License.
1684 * You may obtain a copy of the License at
1685 *
1686 * http://www.apache.org/licenses/LICENSE-2.0
1687 *
1688 * Unless required by applicable law or agreed to in writing, software
1689 * distributed under the License is distributed on an "AS IS" BASIS,
1690 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1691 * See the License for the specific language governing permissions and
1692 * limitations under the License.
1693 */
1694
1695 #ifndef INCLUDE_PERFETTO_BASE_COMPILER_H_
1696 #define INCLUDE_PERFETTO_BASE_COMPILER_H_
1697
1698 #include <type_traits>
1699
1700 // gen_amalgamated expanded: #include "perfetto/base/build_config.h"
1701
1702 #define PERFETTO_LIKELY(_x) __builtin_expect(!!(_x), 1)
1703 #define PERFETTO_UNLIKELY(_x) __builtin_expect(!!(_x), 0)
1704
1705 #if defined(__GNUC__) || defined(__clang__)
1706 #define PERFETTO_WARN_UNUSED_RESULT __attribute__((warn_unused_result))
1707 #else
1708 #define PERFETTO_WARN_UNUSED_RESULT
1709 #endif
1710
1711 #if defined(__clang__)
1712 #define PERFETTO_ALWAYS_INLINE __attribute__((__always_inline__))
1713 #define PERFETTO_NO_INLINE __attribute__((__noinline__))
1714 #else
1715 // GCC is too pedantic and often fails with the error:
1716 // "always_inline function might not be inlinable"
1717 #define PERFETTO_ALWAYS_INLINE
1718 #define PERFETTO_NO_INLINE
1719 #endif
1720
1721 #if defined(__GNUC__) || defined(__clang__)
1722 #define PERFETTO_DEBUG_FUNCTION_IDENTIFIER() __PRETTY_FUNCTION__
1723 #elif defined(_MSC_VER)
1724 #define PERFETTO_DEBUG_FUNCTION_IDENTIFIER() __FUNCSIG__
1725 #else
1726 #define PERFETTO_DEBUG_FUNCTION_IDENTIFIER() \
1727 static_assert(false, "Not implemented for this compiler")
1728 #endif
1729
1730 #if defined(__GNUC__) || defined(__clang__)
1731 #define PERFETTO_PRINTF_FORMAT(x, y) \
1732 __attribute__((__format__(__printf__, x, y)))
1733 #else
1734 #define PERFETTO_PRINTF_FORMAT(x, y)
1735 #endif
1736
1737 #if PERFETTO_BUILDFLAG(PERFETTO_OS_IOS)
1738 // TODO(b/158814068): For iOS builds, thread_local is only supported since iOS
1739 // 8. We'd have to use pthread for thread local data instead here. For now, just
1740 // define it to nothing since we don't support running perfetto or the client
1741 // lib on iOS right now.
1742 #define PERFETTO_THREAD_LOCAL
1743 #else
1744 #define PERFETTO_THREAD_LOCAL thread_local
1745 #endif
1746
1747 #if defined(__clang__)
1748 #if __has_feature(address_sanitizer) || defined(__SANITIZE_ADDRESS__)
1749 extern "C" void __asan_poison_memory_region(void const volatile*, size_t);
1750 extern "C" void __asan_unpoison_memory_region(void const volatile*, size_t);
1751 #define PERFETTO_ASAN_POISON(a, s) __asan_poison_memory_region((a), (s))
1752 #define PERFETTO_ASAN_UNPOISON(a, s) __asan_unpoison_memory_region((a), (s))
1753 #else
1754 #define PERFETTO_ASAN_POISON(addr, size)
1755 #define PERFETTO_ASAN_UNPOISON(addr, size)
1756 #endif // __has_feature(address_sanitizer)
1757 #else
1758 #define PERFETTO_ASAN_POISON(addr, size)
1759 #define PERFETTO_ASAN_UNPOISON(addr, size)
1760 #endif // __clang__
1761
1762 namespace perfetto {
1763 namespace base {
1764
1765 template <typename... T>
ignore_result(const T &...)1766 inline void ignore_result(const T&...) {}
1767
1768 } // namespace base
1769 } // namespace perfetto
1770
1771 #endif // INCLUDE_PERFETTO_BASE_COMPILER_H_
1772 // gen_amalgamated begin header: include/perfetto/protozero/message.h
1773 // gen_amalgamated begin header: include/perfetto/base/logging.h
1774 /*
1775 * Copyright (C) 2017 The Android Open Source Project
1776 *
1777 * Licensed under the Apache License, Version 2.0 (the "License");
1778 * you may not use this file except in compliance with the License.
1779 * You may obtain a copy of the License at
1780 *
1781 * http://www.apache.org/licenses/LICENSE-2.0
1782 *
1783 * Unless required by applicable law or agreed to in writing, software
1784 * distributed under the License is distributed on an "AS IS" BASIS,
1785 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1786 * See the License for the specific language governing permissions and
1787 * limitations under the License.
1788 */
1789
1790 #ifndef INCLUDE_PERFETTO_BASE_LOGGING_H_
1791 #define INCLUDE_PERFETTO_BASE_LOGGING_H_
1792
1793 #include <errno.h>
1794 #include <string.h> // For strerror.
1795
1796 // gen_amalgamated expanded: #include "perfetto/base/build_config.h"
1797 // gen_amalgamated expanded: #include "perfetto/base/compiler.h"
1798 // gen_amalgamated expanded: #include "perfetto/base/export.h"
1799
1800 // Ignore GCC warning about a missing argument for a variadic macro parameter.
1801 #pragma GCC system_header
1802
1803 // TODO(primiano): move this to base/build_config.h, turn into
1804 // PERFETTO_BUILDFLAG(DCHECK_IS_ON) and update call sites to use that instead.
1805 #if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
1806 #define PERFETTO_DCHECK_IS_ON() 0
1807 #else
1808 #define PERFETTO_DCHECK_IS_ON() 1
1809 #endif
1810
1811 #if PERFETTO_BUILDFLAG(PERFETTO_FORCE_DLOG_ON)
1812 #define PERFETTO_DLOG_IS_ON() 1
1813 #elif PERFETTO_BUILDFLAG(PERFETTO_FORCE_DLOG_OFF)
1814 #define PERFETTO_DLOG_IS_ON() 0
1815 #else
1816 #define PERFETTO_DLOG_IS_ON() PERFETTO_DCHECK_IS_ON()
1817 #endif
1818
1819 #if defined(PERFETTO_ANDROID_ASYNC_SAFE_LOG)
1820 #if !PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) || \
1821 !PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)
1822 #error "Async-safe logging is limited to Android tree builds"
1823 #endif
1824 // For binaries which need a very lightweight logging implementation.
1825 // Note that this header is incompatible with android/log.h.
1826 #include <async_safe/log.h>
1827 #elif PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
1828 // Normal android logging.
1829 #include <android/log.h>
1830 #endif
1831
1832 namespace perfetto {
1833 namespace base {
1834
1835 // Constexpr functions to extract basename(__FILE__), e.g.: ../foo/f.c -> f.c .
StrEnd(const char * s)1836 constexpr const char* StrEnd(const char* s) {
1837 return *s ? StrEnd(s + 1) : s;
1838 }
1839
BasenameRecursive(const char * s,const char * begin,const char * end)1840 constexpr const char* BasenameRecursive(const char* s,
1841 const char* begin,
1842 const char* end) {
1843 return (*s == '/' && s < end)
1844 ? (s + 1)
1845 : ((s > begin) ? BasenameRecursive(s - 1, begin, end) : s);
1846 }
1847
Basename(const char * str)1848 constexpr const char* Basename(const char* str) {
1849 return BasenameRecursive(StrEnd(str), str, StrEnd(str));
1850 }
1851
1852 enum LogLev { kLogDebug = 0, kLogInfo, kLogImportant, kLogError };
1853
1854 PERFETTO_EXPORT void LogMessage(LogLev,
1855 const char* fname,
1856 int line,
1857 const char* fmt,
1858 ...) PERFETTO_PRINTF_FORMAT(4, 5);
1859
1860 #if defined(PERFETTO_ANDROID_ASYNC_SAFE_LOG)
1861 #define PERFETTO_XLOG(level, fmt, ...) \
1862 do { \
1863 async_safe_format_log((ANDROID_LOG_DEBUG + level), "perfetto", \
1864 "%s:%d " fmt, ::perfetto::base::Basename(__FILE__), \
1865 __LINE__, ##__VA_ARGS__); \
1866 } while (0)
1867 #elif defined(PERFETTO_DISABLE_LOG)
1868 #define PERFETTO_XLOG(...) ::perfetto::base::ignore_result(__VA_ARGS__)
1869 #else
1870 #define PERFETTO_XLOG(level, fmt, ...) \
1871 ::perfetto::base::LogMessage(level, ::perfetto::base::Basename(__FILE__), \
1872 __LINE__, fmt, ##__VA_ARGS__)
1873 #endif
1874
1875 #define PERFETTO_IMMEDIATE_CRASH() \
1876 do { \
1877 __builtin_trap(); \
1878 __builtin_unreachable(); \
1879 } while (0)
1880
1881 #if PERFETTO_BUILDFLAG(PERFETTO_VERBOSE_LOGS)
1882 #define PERFETTO_LOG(fmt, ...) \
1883 PERFETTO_XLOG(::perfetto::base::kLogInfo, fmt, ##__VA_ARGS__)
1884 #else // PERFETTO_BUILDFLAG(PERFETTO_VERBOSE_LOGS)
1885 #define PERFETTO_LOG(...) ::perfetto::base::ignore_result(__VA_ARGS__)
1886 #endif // PERFETTO_BUILDFLAG(PERFETTO_VERBOSE_LOGS)
1887
1888 #define PERFETTO_ILOG(fmt, ...) \
1889 PERFETTO_XLOG(::perfetto::base::kLogImportant, fmt, ##__VA_ARGS__)
1890 #define PERFETTO_ELOG(fmt, ...) \
1891 PERFETTO_XLOG(::perfetto::base::kLogError, fmt, ##__VA_ARGS__)
1892 #define PERFETTO_FATAL(fmt, ...) \
1893 do { \
1894 PERFETTO_PLOG(fmt, ##__VA_ARGS__); \
1895 PERFETTO_IMMEDIATE_CRASH(); \
1896 } while (0)
1897
1898 #define PERFETTO_PLOG(x, ...) \
1899 PERFETTO_ELOG(x " (errno: %d, %s)", ##__VA_ARGS__, errno, strerror(errno))
1900
1901 #define PERFETTO_CHECK(x) \
1902 do { \
1903 if (PERFETTO_UNLIKELY(!(x))) { \
1904 PERFETTO_PLOG("%s", "PERFETTO_CHECK(" #x ")"); \
1905 PERFETTO_IMMEDIATE_CRASH(); \
1906 } \
1907 } while (0)
1908
1909 #if PERFETTO_DLOG_IS_ON()
1910
1911 #define PERFETTO_DLOG(fmt, ...) \
1912 PERFETTO_XLOG(::perfetto::base::kLogDebug, fmt, ##__VA_ARGS__)
1913
1914 #define PERFETTO_DPLOG(x, ...) \
1915 PERFETTO_DLOG(x " (errno: %d, %s)", ##__VA_ARGS__, errno, strerror(errno))
1916
1917 #else // PERFETTO_DLOG_IS_ON()
1918
1919 #define PERFETTO_DLOG(...) ::perfetto::base::ignore_result(__VA_ARGS__)
1920 #define PERFETTO_DPLOG(...) ::perfetto::base::ignore_result(__VA_ARGS__)
1921
1922 #endif // PERFETTO_DLOG_IS_ON()
1923
1924 #if PERFETTO_DCHECK_IS_ON()
1925
1926 #define PERFETTO_DCHECK(x) PERFETTO_CHECK(x)
1927 #define PERFETTO_DFATAL(...) PERFETTO_FATAL(__VA_ARGS__)
1928 #define PERFETTO_DFATAL_OR_ELOG(...) PERFETTO_DFATAL(__VA_ARGS__)
1929
1930 #else // PERFETTO_DCHECK_IS_ON()
1931
1932 #define PERFETTO_DCHECK(x) \
1933 do { \
1934 } while (false && (x))
1935
1936 #define PERFETTO_DFATAL(...) ::perfetto::base::ignore_result(__VA_ARGS__)
1937 #define PERFETTO_DFATAL_OR_ELOG(...) PERFETTO_ELOG(__VA_ARGS__)
1938
1939 #endif // PERFETTO_DCHECK_IS_ON()
1940
1941 } // namespace base
1942 } // namespace perfetto
1943
1944 #endif // INCLUDE_PERFETTO_BASE_LOGGING_H_
1945 // gen_amalgamated begin header: include/perfetto/protozero/contiguous_memory_range.h
1946 /*
1947 * Copyright (C) 2017 The Android Open Source Project
1948 *
1949 * Licensed under the Apache License, Version 2.0 (the "License");
1950 * you may not use this file except in compliance with the License.
1951 * You may obtain a copy of the License at
1952 *
1953 * http://www.apache.org/licenses/LICENSE-2.0
1954 *
1955 * Unless required by applicable law or agreed to in writing, software
1956 * distributed under the License is distributed on an "AS IS" BASIS,
1957 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1958 * See the License for the specific language governing permissions and
1959 * limitations under the License.
1960 */
1961
1962 #ifndef INCLUDE_PERFETTO_PROTOZERO_CONTIGUOUS_MEMORY_RANGE_H_
1963 #define INCLUDE_PERFETTO_PROTOZERO_CONTIGUOUS_MEMORY_RANGE_H_
1964
1965 #include <assert.h>
1966 #include <stddef.h>
1967 #include <stdint.h>
1968
1969 namespace protozero {
1970
1971 // Keep this struct trivially constructible (no ctors, no default initializers).
1972 struct ContiguousMemoryRange {
1973 uint8_t* begin;
1974 uint8_t* end; // STL style: one byte past the end of the buffer.
1975
is_validContiguousMemoryRange1976 inline bool is_valid() const { return begin != nullptr; }
resetContiguousMemoryRange1977 inline void reset() { begin = nullptr; }
sizeContiguousMemoryRange1978 inline size_t size() const { return static_cast<size_t>(end - begin); }
1979 };
1980
1981 } // namespace protozero
1982
1983 #endif // INCLUDE_PERFETTO_PROTOZERO_CONTIGUOUS_MEMORY_RANGE_H_
1984 // gen_amalgamated begin header: include/perfetto/protozero/proto_utils.h
1985 /*
1986 * Copyright (C) 2017 The Android Open Source Project
1987 *
1988 * Licensed under the Apache License, Version 2.0 (the "License");
1989 * you may not use this file except in compliance with the License.
1990 * You may obtain a copy of the License at
1991 *
1992 * http://www.apache.org/licenses/LICENSE-2.0
1993 *
1994 * Unless required by applicable law or agreed to in writing, software
1995 * distributed under the License is distributed on an "AS IS" BASIS,
1996 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1997 * See the License for the specific language governing permissions and
1998 * limitations under the License.
1999 */
2000
2001 #ifndef INCLUDE_PERFETTO_PROTOZERO_PROTO_UTILS_H_
2002 #define INCLUDE_PERFETTO_PROTOZERO_PROTO_UTILS_H_
2003
2004 #include <inttypes.h>
2005 #include <stddef.h>
2006
2007 #include <type_traits>
2008
2009 // gen_amalgamated expanded: #include "perfetto/base/logging.h"
2010
2011 namespace protozero {
2012 namespace proto_utils {
2013
2014 // See https://developers.google.com/protocol-buffers/docs/encoding wire types.
2015 // This is a type encoded into the proto that provides just enough info to
2016 // find the length of the following value.
2017 enum class ProtoWireType : uint32_t {
2018 kVarInt = 0,
2019 kFixed64 = 1,
2020 kLengthDelimited = 2,
2021 kFixed32 = 5,
2022 };
2023
2024 // This is the type defined in the proto for each field. This information
2025 // is used to decide the translation strategy when writing the trace.
2026 enum class ProtoSchemaType {
2027 kUnknown = 0,
2028 kDouble,
2029 kFloat,
2030 kInt64,
2031 kUint64,
2032 kInt32,
2033 kFixed64,
2034 kFixed32,
2035 kBool,
2036 kString,
2037 kGroup, // Deprecated (proto2 only)
2038 kMessage,
2039 kBytes,
2040 kUint32,
2041 kEnum,
2042 kSfixed32,
2043 kSfixed64,
2044 kSint32,
2045 kSint64,
2046 };
2047
ProtoSchemaToString(ProtoSchemaType v)2048 inline const char* ProtoSchemaToString(ProtoSchemaType v) {
2049 switch (v) {
2050 case ProtoSchemaType::kUnknown:
2051 return "unknown";
2052 case ProtoSchemaType::kDouble:
2053 return "double";
2054 case ProtoSchemaType::kFloat:
2055 return "float";
2056 case ProtoSchemaType::kInt64:
2057 return "int64";
2058 case ProtoSchemaType::kUint64:
2059 return "uint64";
2060 case ProtoSchemaType::kInt32:
2061 return "int32";
2062 case ProtoSchemaType::kFixed64:
2063 return "fixed64";
2064 case ProtoSchemaType::kFixed32:
2065 return "fixed32";
2066 case ProtoSchemaType::kBool:
2067 return "bool";
2068 case ProtoSchemaType::kString:
2069 return "string";
2070 case ProtoSchemaType::kGroup:
2071 return "group";
2072 case ProtoSchemaType::kMessage:
2073 return "message";
2074 case ProtoSchemaType::kBytes:
2075 return "bytes";
2076 case ProtoSchemaType::kUint32:
2077 return "uint32";
2078 case ProtoSchemaType::kEnum:
2079 return "enum";
2080 case ProtoSchemaType::kSfixed32:
2081 return "sfixed32";
2082 case ProtoSchemaType::kSfixed64:
2083 return "sfixed64";
2084 case ProtoSchemaType::kSint32:
2085 return "sint32";
2086 case ProtoSchemaType::kSint64:
2087 return "sint64";
2088 }
2089 // For gcc:
2090 PERFETTO_DCHECK(false);
2091 return "";
2092 }
2093
2094 // Maximum message size supported: 256 MiB (4 x 7-bit due to varint encoding).
2095 constexpr size_t kMessageLengthFieldSize = 4;
2096 constexpr size_t kMaxMessageLength = (1u << (kMessageLengthFieldSize * 7)) - 1;
2097
2098 // Field tag is encoded as 32-bit varint (5 bytes at most).
2099 // Largest value of simple (not length-delimited) field is 64-bit varint
2100 // (10 bytes at most). 15 bytes buffer is enough to store a simple field.
2101 constexpr size_t kMaxTagEncodedSize = 5;
2102 constexpr size_t kMaxSimpleFieldEncodedSize = kMaxTagEncodedSize + 10;
2103
2104 // Proto types: (int|uint|sint)(32|64), bool, enum.
MakeTagVarInt(uint32_t field_id)2105 constexpr uint32_t MakeTagVarInt(uint32_t field_id) {
2106 return (field_id << 3) | static_cast<uint32_t>(ProtoWireType::kVarInt);
2107 }
2108
2109 // Proto types: fixed64, sfixed64, fixed32, sfixed32, double, float.
2110 template <typename T>
MakeTagFixed(uint32_t field_id)2111 constexpr uint32_t MakeTagFixed(uint32_t field_id) {
2112 static_assert(sizeof(T) == 8 || sizeof(T) == 4, "Value must be 4 or 8 bytes");
2113 return (field_id << 3) |
2114 static_cast<uint32_t>((sizeof(T) == 8 ? ProtoWireType::kFixed64
2115 : ProtoWireType::kFixed32));
2116 }
2117
2118 // Proto types: string, bytes, embedded messages.
MakeTagLengthDelimited(uint32_t field_id)2119 constexpr uint32_t MakeTagLengthDelimited(uint32_t field_id) {
2120 return (field_id << 3) |
2121 static_cast<uint32_t>(ProtoWireType::kLengthDelimited);
2122 }
2123
2124 // Proto types: sint64, sint32.
2125 template <typename T>
ZigZagEncode(T value)2126 inline typename std::make_unsigned<T>::type ZigZagEncode(T value) {
2127 using UnsignedType = typename std::make_unsigned<T>::type;
2128
2129 // Right-shift of negative values is implementation specific.
2130 // Assert the implementation does what we expect, which is that shifting any
2131 // positive value by sizeof(T) * 8 - 1 gives an all 0 bitmap, and a negative
2132 // value gives and all 1 bitmap.
2133 constexpr uint64_t kUnsignedZero = 0u;
2134 constexpr int64_t kNegativeOne = -1;
2135 constexpr int64_t kPositiveOne = 1;
2136 static_assert(static_cast<uint64_t>(kNegativeOne >> 63) == ~kUnsignedZero,
2137 "implementation does not support assumed rightshift");
2138 static_assert(static_cast<uint64_t>(kPositiveOne >> 63) == kUnsignedZero,
2139 "implementation does not support assumed rightshift");
2140
2141 return (static_cast<UnsignedType>(value) << 1) ^
2142 static_cast<UnsignedType>(value >> (sizeof(T) * 8 - 1));
2143 }
2144
2145 // Proto types: sint64, sint32.
2146 template <typename T>
ZigZagDecode(T value)2147 inline typename std::make_signed<T>::type ZigZagDecode(T value) {
2148 using UnsignedType = typename std::make_unsigned<T>::type;
2149 auto u_value = static_cast<UnsignedType>(value);
2150 return static_cast<typename std::make_signed<T>::type>(
2151 ((u_value >> 1) ^ -(u_value & 1)));
2152 }
2153
2154 template <typename T>
WriteVarInt(T value,uint8_t * target)2155 inline uint8_t* WriteVarInt(T value, uint8_t* target) {
2156 // If value is <= 0 we must first sign extend to int64_t (see [1]).
2157 // Finally we always cast to an unsigned value to to avoid arithmetic
2158 // (sign expanding) shifts in the while loop.
2159 // [1]: "If you use int32 or int64 as the type for a negative number, the
2160 // resulting varint is always ten bytes long".
2161 // - developers.google.com/protocol-buffers/docs/encoding
2162 // So for each input type we do the following casts:
2163 // uintX_t -> uintX_t -> uintX_t
2164 // int8_t -> int64_t -> uint64_t
2165 // int16_t -> int64_t -> uint64_t
2166 // int32_t -> int64_t -> uint64_t
2167 // int64_t -> int64_t -> uint64_t
2168 using MaybeExtendedType =
2169 typename std::conditional<std::is_unsigned<T>::value, T, int64_t>::type;
2170 using UnsignedType = typename std::make_unsigned<MaybeExtendedType>::type;
2171
2172 MaybeExtendedType extended_value = static_cast<MaybeExtendedType>(value);
2173 UnsignedType unsigned_value = static_cast<UnsignedType>(extended_value);
2174
2175 while (unsigned_value >= 0x80) {
2176 *target++ = static_cast<uint8_t>(unsigned_value) | 0x80;
2177 unsigned_value >>= 7;
2178 }
2179 *target = static_cast<uint8_t>(unsigned_value);
2180 return target + 1;
2181 }
2182
2183 // Writes a fixed-size redundant encoding of the given |value|. This is
2184 // used to backfill fixed-size reservations for the length field using a
2185 // non-canonical varint encoding (e.g. \x81\x80\x80\x00 instead of \x01).
2186 // See https://github.com/google/protobuf/issues/1530.
2187 // In particular, this is used for nested messages. The size of a nested message
2188 // is not known until all its field have been written. |kMessageLengthFieldSize|
2189 // bytes are reserved to encode the size field and backfilled at the end.
WriteRedundantVarInt(uint32_t value,uint8_t * buf)2190 inline void WriteRedundantVarInt(uint32_t value, uint8_t* buf) {
2191 for (size_t i = 0; i < kMessageLengthFieldSize; ++i) {
2192 const uint8_t msb = (i < kMessageLengthFieldSize - 1) ? 0x80 : 0;
2193 buf[i] = static_cast<uint8_t>(value) | msb;
2194 value >>= 7;
2195 }
2196 }
2197
2198 template <uint32_t field_id>
StaticAssertSingleBytePreamble()2199 void StaticAssertSingleBytePreamble() {
2200 static_assert(field_id < 16,
2201 "Proto field id too big to fit in a single byte preamble");
2202 }
2203
2204 // Parses a VarInt from the encoded buffer [start, end). |end| is STL-style and
2205 // points one byte past the end of buffer.
2206 // The parsed int value is stored in the output arg |value|. Returns a pointer
2207 // to the next unconsumed byte (so start < retval <= end) or |start| if the
2208 // VarInt could not be fully parsed because there was not enough space in the
2209 // buffer.
ParseVarInt(const uint8_t * start,const uint8_t * end,uint64_t * out_value)2210 inline const uint8_t* ParseVarInt(const uint8_t* start,
2211 const uint8_t* end,
2212 uint64_t* out_value) {
2213 const uint8_t* pos = start;
2214 uint64_t value = 0;
2215 for (uint32_t shift = 0; pos < end && shift < 64u; shift += 7) {
2216 // Cache *pos into |cur_byte| to prevent that the compiler dereferences the
2217 // pointer twice (here and in the if() below) due to char* aliasing rules.
2218 uint8_t cur_byte = *pos++;
2219 value |= static_cast<uint64_t>(cur_byte & 0x7f) << shift;
2220 if ((cur_byte & 0x80) == 0) {
2221 // In valid cases we get here.
2222 *out_value = value;
2223 return pos;
2224 }
2225 }
2226 *out_value = 0;
2227 return start;
2228 }
2229
2230 } // namespace proto_utils
2231 } // namespace protozero
2232
2233 #endif // INCLUDE_PERFETTO_PROTOZERO_PROTO_UTILS_H_
2234 // gen_amalgamated begin header: include/perfetto/protozero/scattered_stream_writer.h
2235 /*
2236 * Copyright (C) 2017 The Android Open Source Project
2237 *
2238 * Licensed under the Apache License, Version 2.0 (the "License");
2239 * you may not use this file except in compliance with the License.
2240 * You may obtain a copy of the License at
2241 *
2242 * http://www.apache.org/licenses/LICENSE-2.0
2243 *
2244 * Unless required by applicable law or agreed to in writing, software
2245 * distributed under the License is distributed on an "AS IS" BASIS,
2246 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2247 * See the License for the specific language governing permissions and
2248 * limitations under the License.
2249 */
2250
2251 #ifndef INCLUDE_PERFETTO_PROTOZERO_SCATTERED_STREAM_WRITER_H_
2252 #define INCLUDE_PERFETTO_PROTOZERO_SCATTERED_STREAM_WRITER_H_
2253
2254 #include <assert.h>
2255 #include <stddef.h>
2256 #include <stdint.h>
2257 #include <string.h>
2258
2259 // gen_amalgamated expanded: #include "perfetto/base/compiler.h"
2260 // gen_amalgamated expanded: #include "perfetto/base/export.h"
2261 // gen_amalgamated expanded: #include "perfetto/protozero/contiguous_memory_range.h"
2262
2263 namespace protozero {
2264
2265 // This class deals with the following problem: append-only proto messages want
2266 // to write a stream of bytes, without caring about the implementation of the
2267 // underlying buffer (which concretely will be either the trace ring buffer
2268 // or a heap-allocated buffer). The main deal is: proto messages don't know in
2269 // advance what their size will be.
2270 // Due to the tracing buffer being split into fixed-size chunks, on some
2271 // occasions, these writes need to be spread over two (or more) non-contiguous
2272 // chunks of memory. Similarly, when the buffer is backed by the heap, we want
2273 // to avoid realloc() calls, as they might cause a full copy of the contents
2274 // of the buffer.
2275 // The purpose of this class is to abstract away the non-contiguous write logic.
2276 // This class knows how to deal with writes as long as they fall in the same
2277 // ContiguousMemoryRange and defers the chunk-chaining logic to the Delegate.
2278 class PERFETTO_EXPORT ScatteredStreamWriter {
2279 public:
2280 class PERFETTO_EXPORT Delegate {
2281 public:
2282 virtual ~Delegate();
2283 virtual ContiguousMemoryRange GetNewBuffer() = 0;
2284 };
2285
2286 explicit ScatteredStreamWriter(Delegate* delegate);
2287 ~ScatteredStreamWriter();
2288
WriteByte(uint8_t value)2289 inline void WriteByte(uint8_t value) {
2290 if (write_ptr_ >= cur_range_.end)
2291 Extend();
2292 *write_ptr_++ = value;
2293 }
2294
2295 // Assumes that the caller checked that there is enough headroom.
2296 // TODO(primiano): perf optimization, this is a tracing hot path. The
2297 // compiler can make strong optimization on memcpy if the size arg is a
2298 // constexpr. Make a templated variant of this for fixed-size writes.
2299 // TODO(primiano): restrict / noalias might also help.
WriteBytesUnsafe(const uint8_t * src,size_t size)2300 inline void WriteBytesUnsafe(const uint8_t* src, size_t size) {
2301 uint8_t* const end = write_ptr_ + size;
2302 assert(end <= cur_range_.end);
2303 memcpy(write_ptr_, src, size);
2304 write_ptr_ = end;
2305 }
2306
WriteBytes(const uint8_t * src,size_t size)2307 inline void WriteBytes(const uint8_t* src, size_t size) {
2308 uint8_t* const end = write_ptr_ + size;
2309 if (PERFETTO_LIKELY(end <= cur_range_.end))
2310 return WriteBytesUnsafe(src, size);
2311 WriteBytesSlowPath(src, size);
2312 }
2313
2314 void WriteBytesSlowPath(const uint8_t* src, size_t size);
2315
2316 // Reserves a fixed amount of bytes to be backfilled later. The reserved range
2317 // is guaranteed to be contiguous and not span across chunks. |size| has to be
2318 // <= than the size of a new buffer returned by the Delegate::GetNewBuffer().
2319 uint8_t* ReserveBytes(size_t size);
2320
2321 // Fast (but unsafe) version of the above. The caller must have previously
2322 // checked that there are at least |size| contiguous bytes available.
2323 // Returns only the start pointer of the reservation.
ReserveBytesUnsafe(size_t size)2324 uint8_t* ReserveBytesUnsafe(size_t size) {
2325 uint8_t* begin = write_ptr_;
2326 write_ptr_ += size;
2327 assert(write_ptr_ <= cur_range_.end);
2328 return begin;
2329 }
2330
2331 // Resets the buffer boundaries and the write pointer to the given |range|.
2332 // Subsequent WriteByte(s) will write into |range|.
2333 void Reset(ContiguousMemoryRange range);
2334
2335 // Number of contiguous free bytes in |cur_range_| that can be written without
2336 // requesting a new buffer.
bytes_available()2337 size_t bytes_available() const {
2338 return static_cast<size_t>(cur_range_.end - write_ptr_);
2339 }
2340
write_ptr()2341 uint8_t* write_ptr() const { return write_ptr_; }
2342
written()2343 uint64_t written() const {
2344 return written_previously_ +
2345 static_cast<uint64_t>(write_ptr_ - cur_range_.begin);
2346 }
2347
2348 private:
2349 ScatteredStreamWriter(const ScatteredStreamWriter&) = delete;
2350 ScatteredStreamWriter& operator=(const ScatteredStreamWriter&) = delete;
2351
2352 void Extend();
2353
2354 Delegate* const delegate_;
2355 ContiguousMemoryRange cur_range_;
2356 uint8_t* write_ptr_;
2357 uint64_t written_previously_ = 0;
2358 };
2359
2360 } // namespace protozero
2361
2362 #endif // INCLUDE_PERFETTO_PROTOZERO_SCATTERED_STREAM_WRITER_H_
2363 /*
2364 * Copyright (C) 2017 The Android Open Source Project
2365 *
2366 * Licensed under the Apache License, Version 2.0 (the "License");
2367 * you may not use this file except in compliance with the License.
2368 * You may obtain a copy of the License at
2369 *
2370 * http://www.apache.org/licenses/LICENSE-2.0
2371 *
2372 * Unless required by applicable law or agreed to in writing, software
2373 * distributed under the License is distributed on an "AS IS" BASIS,
2374 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2375 * See the License for the specific language governing permissions and
2376 * limitations under the License.
2377 */
2378
2379 #ifndef INCLUDE_PERFETTO_PROTOZERO_MESSAGE_H_
2380 #define INCLUDE_PERFETTO_PROTOZERO_MESSAGE_H_
2381
2382 #include <assert.h>
2383 #include <stdint.h>
2384 #include <string.h>
2385
2386 #include <string>
2387 #include <type_traits>
2388
2389 // gen_amalgamated expanded: #include "perfetto/base/export.h"
2390 // gen_amalgamated expanded: #include "perfetto/base/logging.h"
2391 // gen_amalgamated expanded: #include "perfetto/protozero/contiguous_memory_range.h"
2392 // gen_amalgamated expanded: #include "perfetto/protozero/proto_utils.h"
2393 // gen_amalgamated expanded: #include "perfetto/protozero/scattered_stream_writer.h"
2394
2395 namespace perfetto {
2396 namespace shm_fuzz {
2397 class FakeProducer;
2398 } // namespace shm_fuzz
2399 } // namespace perfetto
2400
2401 namespace protozero {
2402
2403 class MessageArena;
2404 class MessageHandleBase;
2405
2406 // Base class extended by the proto C++ stubs generated by the ProtoZero
2407 // compiler. This class provides the minimal runtime required to support
2408 // append-only operations and is designed for performance. None of the methods
2409 // require any dynamic memory allocation, unless more than 16 nested messages
2410 // are created via BeginNestedMessage() calls.
2411 class PERFETTO_EXPORT Message {
2412 public:
2413 friend class MessageHandleBase;
2414
2415 // The ctor is deliberately a no-op to avoid forwarding args from all
2416 // subclasses. The real initialization is performed by Reset().
2417 // Nested messages are allocated via placement new by MessageArena and
2418 // implictly destroyed when the RootMessage's arena goes away. This is
2419 // fine as long as all the fields are PODs, which is checked by the
2420 // static_assert()s in the Reset() method.
2421 Message() = default;
2422
2423 // Clears up the state, allowing the message to be reused as a fresh one.
2424 void Reset(ScatteredStreamWriter*, MessageArena*);
2425
2426 // Commits all the changes to the buffer (backfills the size field of this and
2427 // all nested messages) and seals the message. Returns the size of the message
2428 // (and all nested sub-messages), without taking into account any chunking.
2429 // Finalize is idempotent and can be called several times w/o side effects.
2430 uint32_t Finalize();
2431
2432 // Optional. If is_valid() == true, the corresponding memory region (its
2433 // length == proto_utils::kMessageLengthFieldSize) is backfilled with the size
2434 // of this message (minus |size_already_written| below). This is the mechanism
2435 // used by messages to backfill their corresponding size field in the parent
2436 // message.
size_field()2437 uint8_t* size_field() const { return size_field_; }
set_size_field(uint8_t * size_field)2438 void set_size_field(uint8_t* size_field) { size_field_ = size_field; }
2439
2440 // This is to deal with case of backfilling the size of a root (non-nested)
2441 // message which is split into multiple chunks. Upon finalization only the
2442 // partial size that lies in the last chunk has to be backfilled.
inc_size_already_written(uint32_t sz)2443 void inc_size_already_written(uint32_t sz) { size_already_written_ += sz; }
2444
nested_message()2445 Message* nested_message() { return nested_message_; }
2446
is_finalized()2447 bool is_finalized() const { return finalized_; }
2448
2449 #if PERFETTO_DCHECK_IS_ON()
set_handle(MessageHandleBase * handle)2450 void set_handle(MessageHandleBase* handle) { handle_ = handle; }
2451 #endif
2452
2453 // Proto types: uint64, uint32, int64, int32, bool, enum.
2454 template <typename T>
AppendVarInt(uint32_t field_id,T value)2455 void AppendVarInt(uint32_t field_id, T value) {
2456 if (nested_message_)
2457 EndNestedMessage();
2458
2459 uint8_t buffer[proto_utils::kMaxSimpleFieldEncodedSize];
2460 uint8_t* pos = buffer;
2461
2462 pos = proto_utils::WriteVarInt(proto_utils::MakeTagVarInt(field_id), pos);
2463 // WriteVarInt encodes signed values in two's complement form.
2464 pos = proto_utils::WriteVarInt(value, pos);
2465 WriteToStream(buffer, pos);
2466 }
2467
2468 // Proto types: sint64, sint32.
2469 template <typename T>
AppendSignedVarInt(uint32_t field_id,T value)2470 void AppendSignedVarInt(uint32_t field_id, T value) {
2471 AppendVarInt(field_id, proto_utils::ZigZagEncode(value));
2472 }
2473
2474 // Proto types: bool, enum (small).
2475 // Faster version of AppendVarInt for tiny numbers.
AppendTinyVarInt(uint32_t field_id,int32_t value)2476 void AppendTinyVarInt(uint32_t field_id, int32_t value) {
2477 PERFETTO_DCHECK(0 <= value && value < 0x80);
2478 if (nested_message_)
2479 EndNestedMessage();
2480
2481 uint8_t buffer[proto_utils::kMaxSimpleFieldEncodedSize];
2482 uint8_t* pos = buffer;
2483 // MakeTagVarInt gets super optimized here for constexpr.
2484 pos = proto_utils::WriteVarInt(proto_utils::MakeTagVarInt(field_id), pos);
2485 *pos++ = static_cast<uint8_t>(value);
2486 WriteToStream(buffer, pos);
2487 }
2488
2489 // Proto types: fixed64, sfixed64, fixed32, sfixed32, double, float.
2490 template <typename T>
AppendFixed(uint32_t field_id,T value)2491 void AppendFixed(uint32_t field_id, T value) {
2492 if (nested_message_)
2493 EndNestedMessage();
2494
2495 uint8_t buffer[proto_utils::kMaxSimpleFieldEncodedSize];
2496 uint8_t* pos = buffer;
2497
2498 pos = proto_utils::WriteVarInt(proto_utils::MakeTagFixed<T>(field_id), pos);
2499 memcpy(pos, &value, sizeof(T));
2500 pos += sizeof(T);
2501 // TODO: Optimize memcpy performance, see http://crbug.com/624311 .
2502 WriteToStream(buffer, pos);
2503 }
2504
2505 void AppendString(uint32_t field_id, const char* str);
2506
AppendString(uint32_t field_id,const std::string & str)2507 void AppendString(uint32_t field_id, const std::string& str) {
2508 AppendBytes(field_id, str.data(), str.size());
2509 }
2510
2511 void AppendBytes(uint32_t field_id, const void* value, size_t size);
2512
2513 // Append raw bytes for a field, using the supplied |ranges| to
2514 // copy from |num_ranges| individual buffers.
2515 size_t AppendScatteredBytes(uint32_t field_id,
2516 ContiguousMemoryRange* ranges,
2517 size_t num_ranges);
2518
2519 // Begins a nested message. The returned object is owned by the MessageArena
2520 // of the root message. The nested message ends either when Finalize() is
2521 // called or when any other Append* method is called in the parent class.
2522 // The template argument T is supposed to be a stub class auto generated from
2523 // a .proto, hence a subclass of Message.
2524 template <class T>
BeginNestedMessage(uint32_t field_id)2525 T* BeginNestedMessage(uint32_t field_id) {
2526 // This is to prevent subclasses (which should be autogenerated, though), to
2527 // introduce extra state fields (which wouldn't be initialized by Reset()).
2528 static_assert(std::is_base_of<Message, T>::value,
2529 "T must be a subclass of Message");
2530 static_assert(sizeof(T) == sizeof(Message),
2531 "Message subclasses cannot introduce extra state.");
2532 return static_cast<T*>(BeginNestedMessageInternal(field_id));
2533 }
2534
stream_writer_for_testing()2535 ScatteredStreamWriter* stream_writer_for_testing() { return stream_writer_; }
2536
2537 // Appends some raw bytes to the message. The use-case for this is preserving
2538 // unknown fields in the decode -> re-encode path of xxx.gen.cc classes
2539 // generated by the cppgen_plugin.cc.
2540 // The caller needs to guarantee that the appended data is properly
2541 // proto-encoded and each field has a proto preamble.
AppendRawProtoBytes(const void * data,size_t size)2542 void AppendRawProtoBytes(const void* data, size_t size) {
2543 const uint8_t* src = reinterpret_cast<const uint8_t*>(data);
2544 WriteToStream(src, src + size);
2545 }
2546
2547 private:
2548 Message(const Message&) = delete;
2549 Message& operator=(const Message&) = delete;
2550
2551 Message* BeginNestedMessageInternal(uint32_t field_id);
2552
2553 // Called by Finalize and Append* methods.
2554 void EndNestedMessage();
2555
WriteToStream(const uint8_t * src_begin,const uint8_t * src_end)2556 void WriteToStream(const uint8_t* src_begin, const uint8_t* src_end) {
2557 PERFETTO_DCHECK(!finalized_);
2558 PERFETTO_DCHECK(src_begin <= src_end);
2559 const uint32_t size = static_cast<uint32_t>(src_end - src_begin);
2560 stream_writer_->WriteBytes(src_begin, size);
2561 size_ += size;
2562 }
2563
2564 // Only POD fields are allowed. This class's dtor is never called.
2565 // See the comment on the static_assert in the corresponding .cc file.
2566
2567 // The stream writer interface used for the serialization.
2568 ScatteredStreamWriter* stream_writer_;
2569
2570 // The storage used to allocate nested Message objects.
2571 // This is owned by RootMessage<T>.
2572 MessageArena* arena_;
2573
2574 // Pointer to the last child message created through BeginNestedMessage(), if
2575 // any, nullptr otherwise. There is no need to keep track of more than one
2576 // message per nesting level as the proto-zero API contract mandates that
2577 // nested fields can be filled only in a stacked fashion. In other words,
2578 // nested messages are finalized and sealed when any other field is set in the
2579 // parent message (or the parent message itself is finalized) and cannot be
2580 // accessed anymore afterwards.
2581 Message* nested_message_;
2582
2583 // [optional] Pointer to a non-aligned pre-reserved var-int slot of
2584 // kMessageLengthFieldSize bytes. When set, the Finalize() method will write
2585 // the size of proto-encoded message in the pointed memory region.
2586 uint8_t* size_field_;
2587
2588 // Keeps track of the size of the current message.
2589 uint32_t size_;
2590
2591 // See comment for inc_size_already_written().
2592 uint32_t size_already_written_;
2593
2594 // When true, no more changes to the message are allowed. This is to DCHECK
2595 // attempts of writing to a message which has been Finalize()-d.
2596 bool finalized_;
2597
2598 #if PERFETTO_DCHECK_IS_ON()
2599 // Current generation of message. Incremented on Reset.
2600 // Used to detect stale handles.
2601 uint32_t generation_;
2602
2603 MessageHandleBase* handle_;
2604 #endif
2605 };
2606
2607 } // namespace protozero
2608
2609 #endif // INCLUDE_PERFETTO_PROTOZERO_MESSAGE_H_
2610 // gen_amalgamated begin header: include/perfetto/protozero/message_handle.h
2611 /*
2612 * Copyright (C) 2017 The Android Open Source Project
2613 *
2614 * Licensed under the Apache License, Version 2.0 (the "License");
2615 * you may not use this file except in compliance with the License.
2616 * You may obtain a copy of the License at
2617 *
2618 * http://www.apache.org/licenses/LICENSE-2.0
2619 *
2620 * Unless required by applicable law or agreed to in writing, software
2621 * distributed under the License is distributed on an "AS IS" BASIS,
2622 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2623 * See the License for the specific language governing permissions and
2624 * limitations under the License.
2625 */
2626
2627 #ifndef INCLUDE_PERFETTO_PROTOZERO_MESSAGE_HANDLE_H_
2628 #define INCLUDE_PERFETTO_PROTOZERO_MESSAGE_HANDLE_H_
2629
2630 #include <functional>
2631
2632 // gen_amalgamated expanded: #include "perfetto/base/export.h"
2633 // gen_amalgamated expanded: #include "perfetto/protozero/message.h"
2634
2635 namespace protozero {
2636
2637 class Message;
2638
2639 // MessageHandle allows to decouple the lifetime of a proto message
2640 // from the underlying storage. It gives the following guarantees:
2641 // - The underlying message is finalized (if still alive) if the handle goes
2642 // out of scope.
2643 // - In Debug / DCHECK_ALWAYS_ON builds, the handle becomes null once the
2644 // message is finalized. This is to enforce the append-only API. For instance
2645 // when adding two repeated messages, the addition of the 2nd one forces
2646 // the finalization of the first.
2647 // Think about this as a WeakPtr<Message> which calls
2648 // Message::Finalize() when going out of scope.
2649
2650 class PERFETTO_EXPORT MessageHandleBase {
2651 public:
2652 ~MessageHandleBase();
2653
2654 // Move-only type.
2655 MessageHandleBase(MessageHandleBase&&) noexcept;
2656 MessageHandleBase& operator=(MessageHandleBase&&);
2657 explicit operator bool() const {
2658 #if PERFETTO_DCHECK_IS_ON()
2659 PERFETTO_DCHECK(!message_ || generation_ == message_->generation_);
2660 #endif
2661 return !!message_;
2662 }
2663
2664 protected:
2665 explicit MessageHandleBase(Message* = nullptr);
2666 Message* operator->() const {
2667 #if PERFETTO_DCHECK_IS_ON()
2668 PERFETTO_DCHECK(!message_ || generation_ == message_->generation_);
2669 #endif
2670 return message_;
2671 }
2672 Message& operator*() const { return *(operator->()); }
2673
2674 private:
2675 friend class Message;
2676 MessageHandleBase(const MessageHandleBase&) = delete;
2677 MessageHandleBase& operator=(const MessageHandleBase&) = delete;
2678
reset_message()2679 void reset_message() {
2680 // This is called by Message::Finalize().
2681 PERFETTO_DCHECK(message_->is_finalized());
2682 message_ = nullptr;
2683 }
2684
2685 void Move(MessageHandleBase&&);
2686
FinalizeMessage()2687 void FinalizeMessage() { message_->Finalize(); }
2688
2689 Message* message_;
2690 #if PERFETTO_DCHECK_IS_ON()
2691 uint32_t generation_;
2692 #endif
2693 };
2694
2695 template <typename T>
2696 class MessageHandle : public MessageHandleBase {
2697 public:
MessageHandle()2698 MessageHandle() : MessageHandle(nullptr) {}
MessageHandle(T * message)2699 explicit MessageHandle(T* message) : MessageHandleBase(message) {}
2700
2701 explicit operator bool() const { return MessageHandleBase::operator bool(); }
2702
2703 T& operator*() const {
2704 return static_cast<T&>(MessageHandleBase::operator*());
2705 }
2706
2707 T* operator->() const {
2708 return static_cast<T*>(MessageHandleBase::operator->());
2709 }
2710
get()2711 T* get() const { return static_cast<T*>(MessageHandleBase::operator->()); }
2712 };
2713
2714 } // namespace protozero
2715
2716 #endif // INCLUDE_PERFETTO_PROTOZERO_MESSAGE_HANDLE_H_
2717 // gen_amalgamated begin header: include/perfetto/tracing/internal/basic_types.h
2718 /*
2719 * Copyright (C) 2019 The Android Open Source Project
2720 *
2721 * Licensed under the Apache License, Version 2.0 (the "License");
2722 * you may not use this file except in compliance with the License.
2723 * You may obtain a copy of the License at
2724 *
2725 * http://www.apache.org/licenses/LICENSE-2.0
2726 *
2727 * Unless required by applicable law or agreed to in writing, software
2728 * distributed under the License is distributed on an "AS IS" BASIS,
2729 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2730 * See the License for the specific language governing permissions and
2731 * limitations under the License.
2732 */
2733
2734 #ifndef INCLUDE_PERFETTO_TRACING_INTERNAL_BASIC_TYPES_H_
2735 #define INCLUDE_PERFETTO_TRACING_INTERNAL_BASIC_TYPES_H_
2736
2737 #include <stddef.h>
2738 #include <stdint.h>
2739
2740 namespace perfetto {
2741 namespace internal {
2742
2743 // A static_assert in tracing_muxer_impl.cc guarantees that this stays in sync
2744 // with the definition in tracing/core/basic_types.h
2745 using BufferId = uint16_t;
2746
2747 // This is a direct index in the TracingMuxer::backends_ vector.
2748 // Backends are only added and never removed.
2749 using TracingBackendId = size_t;
2750
2751 // Max numbers of data sources that can be registered in a process.
2752 constexpr size_t kMaxDataSources = 32;
2753
2754 // Max instances for each data source type. This typically matches the
2755 // "max number of concurrent tracing sessions". However remember that a data
2756 // source can be instantiated more than once within one tracing session by
2757 // creating two entries for it in the trace config.
2758 constexpr size_t kMaxDataSourceInstances = 8;
2759
2760 } // namespace internal
2761 } // namespace perfetto
2762
2763 #endif // INCLUDE_PERFETTO_TRACING_INTERNAL_BASIC_TYPES_H_
2764 // gen_amalgamated begin header: include/perfetto/tracing/internal/data_source_internal.h
2765 // gen_amalgamated begin header: include/perfetto/tracing/trace_writer_base.h
2766 /*
2767 * Copyright (C) 2019 The Android Open Source Project
2768 *
2769 * Licensed under the Apache License, Version 2.0 (the "License");
2770 * you may not use this file except in compliance with the License.
2771 * You may obtain a copy of the License at
2772 *
2773 * http://www.apache.org/licenses/LICENSE-2.0
2774 *
2775 * Unless required by applicable law or agreed to in writing, software
2776 * distributed under the License is distributed on an "AS IS" BASIS,
2777 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2778 * See the License for the specific language governing permissions and
2779 * limitations under the License.
2780 */
2781
2782 #ifndef INCLUDE_PERFETTO_TRACING_TRACE_WRITER_BASE_H_
2783 #define INCLUDE_PERFETTO_TRACING_TRACE_WRITER_BASE_H_
2784
2785 // gen_amalgamated expanded: #include "perfetto/protozero/message_handle.h"
2786
2787 namespace perfetto {
2788
2789 namespace protos {
2790 namespace pbzero {
2791 class TracePacket;
2792 } // namespace pbzero
2793 } // namespace protos
2794
2795 // The bare-minimum subset of the TraceWriter interface that is exposed as a
2796 // fully public API.
2797 // See comments in /include/perfetto/ext/tracing/core/trace_writer.h.
2798 class TraceWriterBase {
2799 public:
2800 virtual ~TraceWriterBase();
2801
2802 virtual protozero::MessageHandle<protos::pbzero::TracePacket>
2803 NewTracePacket() = 0;
2804
2805 virtual void Flush(std::function<void()> callback = {}) = 0;
2806 virtual uint64_t written() const = 0;
2807 };
2808
2809 } // namespace perfetto
2810
2811 #endif // INCLUDE_PERFETTO_TRACING_TRACE_WRITER_BASE_H_
2812 /*
2813 * Copyright (C) 2019 The Android Open Source Project
2814 *
2815 * Licensed under the Apache License, Version 2.0 (the "License");
2816 * you may not use this file except in compliance with the License.
2817 * You may obtain a copy of the License at
2818 *
2819 * http://www.apache.org/licenses/LICENSE-2.0
2820 *
2821 * Unless required by applicable law or agreed to in writing, software
2822 * distributed under the License is distributed on an "AS IS" BASIS,
2823 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2824 * See the License for the specific language governing permissions and
2825 * limitations under the License.
2826 */
2827
2828 #ifndef INCLUDE_PERFETTO_TRACING_INTERNAL_DATA_SOURCE_INTERNAL_H_
2829 #define INCLUDE_PERFETTO_TRACING_INTERNAL_DATA_SOURCE_INTERNAL_H_
2830
2831 #include <stddef.h>
2832 #include <stdint.h>
2833
2834 #include <array>
2835 #include <atomic>
2836 #include <functional>
2837 #include <memory>
2838 #include <mutex>
2839
2840 // No perfetto headers (other than tracing/api and protozero) should be here.
2841 // gen_amalgamated expanded: #include "perfetto/tracing/buffer_exhausted_policy.h"
2842 // gen_amalgamated expanded: #include "perfetto/tracing/internal/basic_types.h"
2843 // gen_amalgamated expanded: #include "perfetto/tracing/trace_writer_base.h"
2844
2845 namespace perfetto {
2846
2847 class DataSourceBase;
2848 class TraceWriterBase;
2849
2850 namespace internal {
2851
2852 class TracingTLS;
2853
2854 // This maintains the internal state of a data source instance that is used only
2855 // to implement the tracing mechanics and is not exposed to the API client.
2856 // There is one of these object per DataSource instance (up to
2857 // kMaxDataSourceInstances).
2858 struct DataSourceState {
2859 // This boolean flag determines whether the DataSource::Trace() method should
2860 // do something or be a no-op. This flag doesn't give the full guarantee
2861 // that tracing data will be visible in the trace, it just makes it so that
2862 // the client attemps writing trace data and interacting with the service.
2863 // For instance, when a tracing session ends the service will reject data
2864 // commits that arrive too late even if the producer hasn't received the stop
2865 // IPC message.
2866 // This flag is set right before calling OnStart() and cleared right before
2867 // calling OnStop(), unless using HandleStopAsynchronously() (see comments
2868 // in data_source.h).
2869 // Keep this flag as the first field. This allows the compiler to directly
2870 // dereference the DataSourceState* pointer in the trace fast-path without
2871 // doing extra pointr arithmetic.
2872 bool trace_lambda_enabled = false;
2873
2874 // The central buffer id that all TraceWriter(s) created by this data source
2875 // must target.
2876 BufferId buffer_id = 0;
2877
2878 // The index within TracingMuxerImpl.backends_. Practically it allows to
2879 // lookup the Producer object, and hence the IPC channel, for this data
2880 // source.
2881 TracingBackendId backend_id = 0;
2882
2883 // The instance id as assigned by the tracing service. Note that because a
2884 // process can be connected to >1 services, this ID is not globally unique but
2885 // is only unique within the scope of its backend.
2886 // Only the tuple (backend_id, data_source_instance_id) is globally unique.
2887 uint64_t data_source_instance_id = 0;
2888
2889 // A hash of the trace config used by this instance. This is used to
2890 // de-duplicate instances for data sources with identical names (e.g., track
2891 // event).
2892 uint64_t config_hash = 0;
2893
2894 // This lock is not held to implement Trace() and it's used only if the trace
2895 // code wants to access its own data source state.
2896 // This is to prevent that accessing the data source on an arbitrary embedder
2897 // thread races with the internal IPC thread destroying the data source
2898 // because of a end-of-tracing notification from the service.
2899 std::recursive_mutex lock;
2900 std::unique_ptr<DataSourceBase> data_source;
2901 };
2902
2903 // This is to allow lazy-initialization and avoid static initializers and
2904 // at-exit destructors. All the entries are initialized via placement-new when
2905 // DataSource::Register() is called, see TracingMuxerImpl::RegisterDataSource().
2906 struct DataSourceStateStorage {
2907 alignas(DataSourceState) char storage[sizeof(DataSourceState)]{};
2908 };
2909
2910 // Per-DataSource-type global state.
2911 struct DataSourceStaticState {
2912 // Unique index of the data source, assigned at registration time.
2913 uint32_t index = kMaxDataSources;
2914
2915 // A bitmap that tells about the validity of each |instances| entry. When the
2916 // i-th bit of the bitmap it's set, instances[i] is valid.
2917 std::atomic<uint32_t> valid_instances{};
2918 std::array<DataSourceStateStorage, kMaxDataSourceInstances> instances{};
2919
2920 // Can be used with a cached |valid_instances| bitmap.
TryGetCachedDataSourceStaticState2921 DataSourceState* TryGetCached(uint32_t cached_bitmap, size_t n) {
2922 return cached_bitmap & (1 << n)
2923 ? reinterpret_cast<DataSourceState*>(&instances[n])
2924 : nullptr;
2925 }
2926
TryGetDataSourceStaticState2927 DataSourceState* TryGet(size_t n) {
2928 return TryGetCached(valid_instances.load(std::memory_order_acquire), n);
2929 }
2930
CompilerAssertsDataSourceStaticState2931 void CompilerAsserts() {
2932 static_assert(sizeof(valid_instances.load()) * 8 >= kMaxDataSourceInstances,
2933 "kMaxDataSourceInstances too high");
2934 }
2935 };
2936
2937 // Per-DataSource-instance thread-local state.
2938 struct DataSourceInstanceThreadLocalState {
2939 using IncrementalStatePointer = std::unique_ptr<void, void (*)(void*)>;
2940
ResetDataSourceInstanceThreadLocalState2941 void Reset() {
2942 trace_writer.reset();
2943 incremental_state.reset();
2944 backend_id = 0;
2945 buffer_id = 0;
2946 }
2947
2948 std::unique_ptr<TraceWriterBase> trace_writer;
2949 IncrementalStatePointer incremental_state = {nullptr, [](void*) {}};
2950 TracingBackendId backend_id;
2951 BufferId buffer_id;
2952 };
2953
2954 // Per-DataSource-type thread-local state.
2955 struct DataSourceThreadLocalState {
2956 DataSourceStaticState* static_state = nullptr;
2957
2958 // Pointer to the parent tls object that holds us. Used to retrieve the
2959 // generation, which is per-global-TLS and not per data-source.
2960 TracingTLS* root_tls = nullptr;
2961
2962 // One entry per each data source instance.
2963 std::array<DataSourceInstanceThreadLocalState, kMaxDataSourceInstances>
2964 per_instance{};
2965 };
2966
2967 } // namespace internal
2968 } // namespace perfetto
2969
2970 #endif // INCLUDE_PERFETTO_TRACING_INTERNAL_DATA_SOURCE_INTERNAL_H_
2971 // gen_amalgamated begin header: include/perfetto/tracing/internal/tracing_muxer.h
2972 // gen_amalgamated begin header: include/perfetto/tracing/internal/tracing_tls.h
2973 // gen_amalgamated begin header: include/perfetto/tracing/platform.h
2974 /*
2975 * Copyright (C) 2019 The Android Open Source Project
2976 *
2977 * Licensed under the Apache License, Version 2.0 (the "License");
2978 * you may not use this file except in compliance with the License.
2979 * You may obtain a copy of the License at
2980 *
2981 * http://www.apache.org/licenses/LICENSE-2.0
2982 *
2983 * Unless required by applicable law or agreed to in writing, software
2984 * distributed under the License is distributed on an "AS IS" BASIS,
2985 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2986 * See the License for the specific language governing permissions and
2987 * limitations under the License.
2988 */
2989
2990 #ifndef INCLUDE_PERFETTO_TRACING_PLATFORM_H_
2991 #define INCLUDE_PERFETTO_TRACING_PLATFORM_H_
2992
2993 #include <stddef.h>
2994 #include <stdint.h>
2995
2996 #include <functional>
2997 #include <memory>
2998
2999 // gen_amalgamated expanded: #include "perfetto/base/export.h"
3000
3001 namespace perfetto {
3002
3003 namespace base {
3004 class TaskRunner;
3005 } // namespace base
3006
3007 // This abstract class is used to abstract dependencies on platform-specific
3008 // primitives that cannot be implemented by the perfetto codebase and must be
3009 // provided or overridden by the embedder.
3010 // This is, for instance, for cases where we want to use some particular
3011 // base:: class in Chrome and provide instead POSIX fallbacks for other
3012 // embedders.
3013
3014 // Base class for thread-local objects. This is to get a basic object vtable and
3015 // delegate destruction to the embedder. See Platform::CreateThreadLocalObject.
3016 class PERFETTO_EXPORT PlatformThreadLocalObject {
3017 public:
3018 // Implemented by perfetto internal code. The embedder must call this when
3019 // implementing GetOrCreateThreadLocalObject() to create an instance for the
3020 // first time on each thread.
3021 static std::unique_ptr<PlatformThreadLocalObject> CreateInstance();
3022 virtual ~PlatformThreadLocalObject();
3023 };
3024
3025 class PERFETTO_EXPORT Platform {
3026 public:
3027 // Embedders can use this unless they have custom needs (e.g. Chrome wanting
3028 // to use its own base class for TLS).
3029 static Platform* GetDefaultPlatform();
3030
3031 virtual ~Platform();
3032
3033 // Creates a thread-local object. The embedder must:
3034 // - Create an instance per-thread calling ThreadLocalObject::CreateInstance.
3035 // - Own the lifetime of the returned object as long as the thread is alive.
3036 // - Destroy it when the thread exits.
3037 // Perfetto requires only one thread-local object overall (obviously, one
3038 // instance per-thread) from the embedder.
3039 using ThreadLocalObject = ::perfetto::PlatformThreadLocalObject;
3040 virtual ThreadLocalObject* GetOrCreateThreadLocalObject() = 0;
3041
3042 // Creates a sequenced task runner. The easiest implementation is to create
3043 // a new thread (e.g. use base::ThreadTaskRunner) but this can also be
3044 // implemented in some more clever way (e.g. using chromiums's scheduler).
3045 struct CreateTaskRunnerArgs {};
3046 virtual std::unique_ptr<base::TaskRunner> CreateTaskRunner(
3047 const CreateTaskRunnerArgs&) = 0;
3048
3049 // Used to derive the producer name. Mostly relevant when using the
3050 // kSystemBackend mode. It can be an arbitrary string when using the
3051 // in-process mode.
3052 virtual std::string GetCurrentProcessName() = 0;
3053 };
3054
3055 } // namespace perfetto
3056
3057 #endif // INCLUDE_PERFETTO_TRACING_PLATFORM_H_
3058 /*
3059 * Copyright (C) 2019 The Android Open Source Project
3060 *
3061 * Licensed under the Apache License, Version 2.0 (the "License");
3062 * you may not use this file except in compliance with the License.
3063 * You may obtain a copy of the License at
3064 *
3065 * http://www.apache.org/licenses/LICENSE-2.0
3066 *
3067 * Unless required by applicable law or agreed to in writing, software
3068 * distributed under the License is distributed on an "AS IS" BASIS,
3069 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3070 * See the License for the specific language governing permissions and
3071 * limitations under the License.
3072 */
3073
3074 #ifndef INCLUDE_PERFETTO_TRACING_INTERNAL_TRACING_TLS_H_
3075 #define INCLUDE_PERFETTO_TRACING_INTERNAL_TRACING_TLS_H_
3076
3077 #include <array>
3078 #include <memory>
3079
3080 // gen_amalgamated expanded: #include "perfetto/tracing/internal/basic_types.h"
3081 // gen_amalgamated expanded: #include "perfetto/tracing/internal/data_source_internal.h"
3082 // gen_amalgamated expanded: #include "perfetto/tracing/platform.h"
3083
3084 namespace perfetto {
3085
3086 class TraceWriterBase;
3087
3088 namespace internal {
3089
3090 // Organization of the thread-local storage
3091 // ----------------------------------------
3092 // First of all, remember the cardinality of the problem: at any point in time
3093 // there are M data sources registered (i.e. number of subclasses of DataSource)
3094 // and up to N concurrent instances for each data source, so up to M * N total
3095 // data source instances around.
3096 // Each data source instance can be accessed by T threads (no upper bound).
3097 // We can safely put hard limits both to M and N (i.e. say that we support at
3098 // most 32 data source types per process and up to 8 concurrent instances).
3099 //
3100 // We want to make it so from the Platform viewpoint, we use only one global
3101 // TLS object, so T instances in total, one per thread, regardless of M and N.
3102 // This allows to deal with at-thread-exit destruction only in one place, rather
3103 // than N, M or M * N.
3104 //
3105 // Visually:
3106 // [ Thread 1 ] [ Thread 2 ] [ Thread T ]
3107 // +---------------+ +---------------+ +---------------+
3108 // Data source Foo | | | | | |
3109 // Instance 1 | TLS | | TLS | | TLS |
3110 // Instance 2 | Object | | Object | | Object |
3111 // Instance 3 | | | | | |
3112 // | | | | | |
3113 // Data source Bar | | | | | |
3114 // Instance 1 | | | | | |
3115 // Instance 2 | | | | | |
3116 // +---------------+ +---------------+ +---------------+
3117 //
3118 // Each TLS Object is organized as an array of M DataSourceThreadLocalState.
3119 // Each DSTLS itself is an array of up to N per-instance objects.
3120 // The only per-instance object for now is the TraceWriter.
3121 // So for each data source, for each instance, for each thread we keep one
3122 // TraceWriter.
3123 // The lookup is O(1): Given the TLS object, the TraceWriter is just tls[M][N].
3124 class TracingTLS : public Platform::ThreadLocalObject {
3125 public:
3126 ~TracingTLS() override;
3127
3128 // This is checked against TraceMuxerImpl's global generation counter to
3129 // handle destruction of TraceWriter(s) that belong to data sources that
3130 // have been stopped. When the two numbers diverge, a scan of all the
3131 // thread-local TraceWriter(s) is issued.
3132 uint32_t generation = 0;
3133
3134 // By default all data source instances have independent thread-local state
3135 // (see above).
3136 std::array<DataSourceThreadLocalState, kMaxDataSources> data_sources_tls{};
3137
3138 // Track event data sources, however, share the same thread-local state in
3139 // order to be able to share trace writers and interning state across all
3140 // track event categories.
3141 DataSourceThreadLocalState track_event_tls{};
3142 };
3143
3144 } // namespace internal
3145 } // namespace perfetto
3146
3147 #endif // INCLUDE_PERFETTO_TRACING_INTERNAL_TRACING_TLS_H_
3148 /*
3149 * Copyright (C) 2019 The Android Open Source Project
3150 *
3151 * Licensed under the Apache License, Version 2.0 (the "License");
3152 * you may not use this file except in compliance with the License.
3153 * You may obtain a copy of the License at
3154 *
3155 * http://www.apache.org/licenses/LICENSE-2.0
3156 *
3157 * Unless required by applicable law or agreed to in writing, software
3158 * distributed under the License is distributed on an "AS IS" BASIS,
3159 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3160 * See the License for the specific language governing permissions and
3161 * limitations under the License.
3162 */
3163
3164 #ifndef INCLUDE_PERFETTO_TRACING_INTERNAL_TRACING_MUXER_H_
3165 #define INCLUDE_PERFETTO_TRACING_INTERNAL_TRACING_MUXER_H_
3166
3167 #include <atomic>
3168 #include <memory>
3169
3170 // gen_amalgamated expanded: #include "perfetto/base/export.h"
3171 // gen_amalgamated expanded: #include "perfetto/tracing/core/forward_decls.h"
3172 // gen_amalgamated expanded: #include "perfetto/tracing/internal/basic_types.h"
3173 // gen_amalgamated expanded: #include "perfetto/tracing/internal/tracing_tls.h"
3174 // gen_amalgamated expanded: #include "perfetto/tracing/platform.h"
3175 namespace perfetto {
3176
3177 class DataSourceBase;
3178 class TraceWriterBase;
3179 struct TracingInitArgs;
3180 class TracingSession;
3181
3182 namespace internal {
3183
3184 struct DataSourceStaticState;
3185
3186 // This class acts as a bridge between the public API methods and the
3187 // TracingBackend(s). It exposes a simplified view of the world to the API
3188 // methods, so that they don't have to care about the multiplicity of backends.
3189 // It handles all the bookkeeping to map data source instances and trace writers
3190 // to the various backends.
3191 // See tracing_muxer_impl.h for the full picture. This class contains only the
3192 // fewer fields and methods that need to be exposed to public/ headers. Fields
3193 // and methods that are required to implement them should go into
3194 // src/tracing/internal/tracing_muxer_impl.h instead: that one can pull in
3195 // perfetto headers outside of public, this one cannot.
3196 class PERFETTO_EXPORT TracingMuxer {
3197 public:
Get()3198 static TracingMuxer* Get() { return instance_; }
3199
3200 virtual ~TracingMuxer();
3201
GetOrCreateTracingTLS()3202 TracingTLS* GetOrCreateTracingTLS() {
3203 return static_cast<TracingTLS*>(platform_->GetOrCreateThreadLocalObject());
3204 }
3205
3206 // This method can fail and return false if trying to register more than
3207 // kMaxDataSources types.
3208 using DataSourceFactory = std::function<std::unique_ptr<DataSourceBase>()>;
3209 virtual bool RegisterDataSource(const DataSourceDescriptor&,
3210 DataSourceFactory,
3211 DataSourceStaticState*) = 0;
3212
3213 // It identifies the right backend and forwards the call to it.
3214 // The returned TraceWriter must be used within the same sequence (for most
3215 // projects this means "same thread"). Alternatively the client needs to take
3216 // care of using synchronization primitives to prevent concurrent accesses.
3217 virtual std::unique_ptr<TraceWriterBase> CreateTraceWriter(
3218 DataSourceState*,
3219 BufferExhaustedPolicy buffer_exhausted_policy) = 0;
3220
3221 virtual void DestroyStoppedTraceWritersForCurrentThread() = 0;
3222
generation(std::memory_order ord)3223 uint32_t generation(std::memory_order ord) { return generation_.load(ord); }
3224
3225 protected:
TracingMuxer(Platform * platform)3226 explicit TracingMuxer(Platform* platform) : platform_(platform) {}
3227
3228 static TracingMuxer* instance_;
3229 Platform* const platform_ = nullptr;
3230
3231 // Incremented every time a data source is destroyed. See tracing_tls.h.
3232 std::atomic<uint32_t> generation_{};
3233 };
3234
3235 } // namespace internal
3236 } // namespace perfetto
3237
3238 #endif // INCLUDE_PERFETTO_TRACING_INTERNAL_TRACING_MUXER_H_
3239 // gen_amalgamated begin header: include/perfetto/tracing/locked_handle.h
3240 /*
3241 * Copyright (C) 2019 The Android Open Source Project
3242 *
3243 * Licensed under the Apache License, Version 2.0 (the "License");
3244 * you may not use this file except in compliance with the License.
3245 * You may obtain a copy of the License at
3246 *
3247 * http://www.apache.org/licenses/LICENSE-2.0
3248 *
3249 * Unless required by applicable law or agreed to in writing, software
3250 * distributed under the License is distributed on an "AS IS" BASIS,
3251 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3252 * See the License for the specific language governing permissions and
3253 * limitations under the License.
3254 */
3255
3256 #ifndef INCLUDE_PERFETTO_TRACING_LOCKED_HANDLE_H_
3257 #define INCLUDE_PERFETTO_TRACING_LOCKED_HANDLE_H_
3258
3259 #include <mutex>
3260
3261 namespace perfetto {
3262
3263 // This is used for GetDataSourceLocked(), in the (rare) case where the
3264 // tracing code wants to access the state of its data source from the Trace()
3265 // method.
3266 template <typename T>
3267 class LockedHandle {
3268 public:
LockedHandle(std::recursive_mutex * mtx,T * obj)3269 LockedHandle(std::recursive_mutex* mtx, T* obj) : lock_(*mtx), obj_(obj) {}
3270 LockedHandle() = default; // For the invalid case.
3271 LockedHandle(LockedHandle&&) = default;
3272 LockedHandle& operator=(LockedHandle&&) = default;
3273
valid()3274 bool valid() const { return obj_; }
3275 explicit operator bool() const { return valid(); }
3276
3277 T* operator->() {
3278 assert(valid());
3279 return obj_;
3280 }
3281
3282 T& operator*() { return *(this->operator->()); }
3283
3284 private:
3285 std::unique_lock<std::recursive_mutex> lock_;
3286 T* obj_ = nullptr;
3287 };
3288
3289 } // namespace perfetto
3290
3291 #endif // INCLUDE_PERFETTO_TRACING_LOCKED_HANDLE_H_
3292 // gen_amalgamated begin header: gen/protos/perfetto/trace/trace_packet.pbzero.h
3293 // gen_amalgamated begin header: include/perfetto/protozero/packed_repeated_fields.h
3294 /*
3295 * Copyright (C) 2019 The Android Open Source Project
3296 *
3297 * Licensed under the Apache License, Version 2.0 (the "License");
3298 * you may not use this file except in compliance with the License.
3299 * You may obtain a copy of the License at
3300 *
3301 * http://www.apache.org/licenses/LICENSE-2.0
3302 *
3303 * Unless required by applicable law or agreed to in writing, software
3304 * distributed under the License is distributed on an "AS IS" BASIS,
3305 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3306 * See the License for the specific language governing permissions and
3307 * limitations under the License.
3308 */
3309
3310 #ifndef INCLUDE_PERFETTO_PROTOZERO_PACKED_REPEATED_FIELDS_H_
3311 #define INCLUDE_PERFETTO_PROTOZERO_PACKED_REPEATED_FIELDS_H_
3312
3313 #include <stdint.h>
3314
3315 #include <array>
3316 #include <memory>
3317 #include <type_traits>
3318
3319 // gen_amalgamated expanded: #include "perfetto/base/logging.h"
3320 // gen_amalgamated expanded: #include "perfetto/protozero/proto_utils.h"
3321
3322 namespace protozero {
3323
3324 // This file contains classes used when encoding packed repeated fields.
3325 // To encode such a field, the caller is first expected to accumulate all of the
3326 // values in one of the following types (depending on the wire type of the
3327 // individual elements), defined below:
3328 // * protozero::PackedVarInt
3329 // * protozero::PackedFixedSizeInt</*element_type=*/ uint32_t>
3330 // Then that buffer is passed to the protozero-generated setters as an argument.
3331 // After calling the setter, the buffer can be destroyed.
3332 //
3333 // An example of encoding a packed field:
3334 // protozero::HeapBuffered<protozero::Message> msg;
3335 // protozero::PackedVarInt buf;
3336 // buf.Append(42);
3337 // buf.Append(-1);
3338 // msg->set_fieldname(buf);
3339 // msg.SerializeAsString();
3340
3341 class PackedBufferBase {
3342 public:
PackedBufferBase()3343 PackedBufferBase() { Reset(); }
3344
3345 // Copy or move is disabled due to pointers to stack addresses.
3346 PackedBufferBase(const PackedBufferBase&) = delete;
3347 PackedBufferBase(PackedBufferBase&&) = delete;
3348 PackedBufferBase& operator=(const PackedBufferBase&) = delete;
3349 PackedBufferBase& operator=(PackedBufferBase&&) = delete;
3350
3351 void Reset();
3352
data()3353 const uint8_t* data() const { return storage_begin_; }
3354
size()3355 size_t size() const {
3356 return static_cast<size_t>(write_ptr_ - storage_begin_);
3357 }
3358
3359 protected:
GrowIfNeeded()3360 void GrowIfNeeded() {
3361 PERFETTO_DCHECK(write_ptr_ >= storage_begin_ && write_ptr_ <= storage_end_);
3362 if (PERFETTO_UNLIKELY(write_ptr_ + kMaxElementSize > storage_end_)) {
3363 GrowSlowpath();
3364 }
3365 }
3366
3367 void GrowSlowpath();
3368
3369 // max(uint64_t varint encoding, biggest fixed type (uint64)).
3370 static constexpr size_t kMaxElementSize = 10;
3371
3372 // So sizeof(this) == 8k.
3373 static constexpr size_t kOnStackStorageSize = 8192 - 32;
3374
3375 uint8_t* storage_begin_;
3376 uint8_t* storage_end_;
3377 uint8_t* write_ptr_;
3378 std::unique_ptr<uint8_t[]> heap_buf_;
3379 alignas(uint64_t) uint8_t stack_buf_[kOnStackStorageSize];
3380 };
3381
3382 class PackedVarInt : public PackedBufferBase {
3383 public:
3384 template <typename T>
Append(T value)3385 void Append(T value) {
3386 GrowIfNeeded();
3387 write_ptr_ = proto_utils::WriteVarInt(value, write_ptr_);
3388 }
3389 };
3390
3391 template <typename T /* e.g. uint32_t for Fixed32 */>
3392 class PackedFixedSizeInt : public PackedBufferBase {
3393 public:
Append(T value)3394 void Append(T value) {
3395 static_assert(sizeof(T) == 4 || sizeof(T) == 8,
3396 "PackedFixedSizeInt should be used only with 32/64-bit ints");
3397 static_assert(sizeof(T) <= kMaxElementSize,
3398 "kMaxElementSize needs to be updated");
3399 GrowIfNeeded();
3400 PERFETTO_DCHECK(reinterpret_cast<size_t>(write_ptr_) % alignof(T) == 0);
3401 memcpy(reinterpret_cast<T*>(write_ptr_), &value, sizeof(T));
3402 write_ptr_ += sizeof(T);
3403 }
3404 };
3405
3406 } // namespace protozero
3407
3408 #endif // INCLUDE_PERFETTO_PROTOZERO_PACKED_REPEATED_FIELDS_H_
3409 // gen_amalgamated begin header: include/perfetto/protozero/proto_decoder.h
3410 // gen_amalgamated begin header: include/perfetto/protozero/field.h
3411 /*
3412 * Copyright (C) 2019 The Android Open Source Project
3413 *
3414 * Licensed under the Apache License, Version 2.0 (the "License");
3415 * you may not use this file except in compliance with the License.
3416 * You may obtain a copy of the License at
3417 *
3418 * http://www.apache.org/licenses/LICENSE-2.0
3419 *
3420 * Unless required by applicable law or agreed to in writing, software
3421 * distributed under the License is distributed on an "AS IS" BASIS,
3422 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3423 * See the License for the specific language governing permissions and
3424 * limitations under the License.
3425 */
3426
3427 #ifndef INCLUDE_PERFETTO_PROTOZERO_FIELD_H_
3428 #define INCLUDE_PERFETTO_PROTOZERO_FIELD_H_
3429
3430 #include <stdint.h>
3431
3432 #include <string>
3433 #include <vector>
3434
3435 // gen_amalgamated expanded: #include "perfetto/base/logging.h"
3436 // gen_amalgamated expanded: #include "perfetto/protozero/contiguous_memory_range.h"
3437 // gen_amalgamated expanded: #include "perfetto/protozero/proto_utils.h"
3438
3439 namespace protozero {
3440
3441 struct ConstBytes {
ToStdStringConstBytes3442 std::string ToStdString() const {
3443 return std::string(reinterpret_cast<const char*>(data), size);
3444 }
3445
3446 const uint8_t* data;
3447 size_t size;
3448 };
3449
3450 struct ConstChars {
3451 // Allow implicit conversion to perfetto's base::StringView without depending
3452 // on perfetto/base or viceversa.
3453 static constexpr bool kConvertibleToStringView = true;
ToStdStringConstChars3454 std::string ToStdString() const { return std::string(data, size); }
3455
3456 const char* data;
3457 size_t size;
3458 };
3459
3460 // A protobuf field decoded by the protozero proto decoders. It exposes
3461 // convenience accessors with minimal debug checks.
3462 // This class is used both by the iterator-based ProtoDecoder and by the
3463 // one-shot TypedProtoDecoder.
3464 // If the field is not valid the accessors consistently return zero-integers or
3465 // null strings.
3466 class Field {
3467 public:
valid()3468 bool valid() const { return id_ != 0; }
id()3469 uint16_t id() const { return id_; }
3470 explicit operator bool() const { return valid(); }
3471
type()3472 proto_utils::ProtoWireType type() const {
3473 auto res = static_cast<proto_utils::ProtoWireType>(type_);
3474 PERFETTO_DCHECK(res == proto_utils::ProtoWireType::kVarInt ||
3475 res == proto_utils::ProtoWireType::kLengthDelimited ||
3476 res == proto_utils::ProtoWireType::kFixed32 ||
3477 res == proto_utils::ProtoWireType::kFixed64);
3478 return res;
3479 }
3480
as_bool()3481 bool as_bool() const {
3482 PERFETTO_DCHECK(!valid() || type() == proto_utils::ProtoWireType::kVarInt);
3483 return static_cast<bool>(int_value_);
3484 }
3485
as_uint32()3486 uint32_t as_uint32() const {
3487 PERFETTO_DCHECK(!valid() || type() == proto_utils::ProtoWireType::kVarInt ||
3488 type() == proto_utils::ProtoWireType::kFixed32);
3489 return static_cast<uint32_t>(int_value_);
3490 }
3491
as_int32()3492 int32_t as_int32() const {
3493 PERFETTO_DCHECK(!valid() || type() == proto_utils::ProtoWireType::kVarInt ||
3494 type() == proto_utils::ProtoWireType::kFixed32);
3495 return static_cast<int32_t>(int_value_);
3496 }
3497
as_sint32()3498 int32_t as_sint32() const {
3499 PERFETTO_DCHECK(!valid() || type() == proto_utils::ProtoWireType::kVarInt);
3500 return proto_utils::ZigZagDecode(static_cast<uint32_t>(int_value_));
3501 }
3502
as_uint64()3503 uint64_t as_uint64() const {
3504 PERFETTO_DCHECK(!valid() || type() == proto_utils::ProtoWireType::kVarInt ||
3505 type() == proto_utils::ProtoWireType::kFixed32 ||
3506 type() == proto_utils::ProtoWireType::kFixed64);
3507 return int_value_;
3508 }
3509
as_int64()3510 int64_t as_int64() const {
3511 PERFETTO_DCHECK(!valid() || type() == proto_utils::ProtoWireType::kVarInt ||
3512 type() == proto_utils::ProtoWireType::kFixed32 ||
3513 type() == proto_utils::ProtoWireType::kFixed64);
3514 return static_cast<int64_t>(int_value_);
3515 }
3516
as_sint64()3517 int64_t as_sint64() const {
3518 PERFETTO_DCHECK(!valid() || type() == proto_utils::ProtoWireType::kVarInt);
3519 return proto_utils::ZigZagDecode(static_cast<uint64_t>(int_value_));
3520 }
3521
as_float()3522 float as_float() const {
3523 PERFETTO_DCHECK(!valid() || type() == proto_utils::ProtoWireType::kFixed32);
3524 float res;
3525 uint32_t value32 = static_cast<uint32_t>(int_value_);
3526 memcpy(&res, &value32, sizeof(res));
3527 return res;
3528 }
3529
as_double()3530 double as_double() const {
3531 PERFETTO_DCHECK(!valid() || type() == proto_utils::ProtoWireType::kFixed64);
3532 double res;
3533 memcpy(&res, &int_value_, sizeof(res));
3534 return res;
3535 }
3536
as_string()3537 ConstChars as_string() const {
3538 PERFETTO_DCHECK(!valid() ||
3539 type() == proto_utils::ProtoWireType::kLengthDelimited);
3540 return ConstChars{reinterpret_cast<const char*>(data()), size_};
3541 }
3542
as_std_string()3543 std::string as_std_string() const { return as_string().ToStdString(); }
3544
as_bytes()3545 ConstBytes as_bytes() const {
3546 PERFETTO_DCHECK(!valid() ||
3547 type() == proto_utils::ProtoWireType::kLengthDelimited);
3548 return ConstBytes{data(), size_};
3549 }
3550
data()3551 const uint8_t* data() const {
3552 PERFETTO_DCHECK(!valid() ||
3553 type() == proto_utils::ProtoWireType::kLengthDelimited);
3554 return reinterpret_cast<const uint8_t*>(int_value_);
3555 }
3556
size()3557 size_t size() const {
3558 PERFETTO_DCHECK(!valid() ||
3559 type() == proto_utils::ProtoWireType::kLengthDelimited);
3560 return size_;
3561 }
3562
raw_int_value()3563 uint64_t raw_int_value() const { return int_value_; }
3564
initialize(uint16_t id,uint8_t type,uint64_t int_value,uint32_t size)3565 void initialize(uint16_t id,
3566 uint8_t type,
3567 uint64_t int_value,
3568 uint32_t size) {
3569 id_ = id;
3570 type_ = type;
3571 int_value_ = int_value;
3572 size_ = size;
3573 }
3574
3575 // For use with templates. This is used by RepeatedFieldIterator::operator*().
get(bool * val)3576 void get(bool* val) const { *val = as_bool(); }
get(uint32_t * val)3577 void get(uint32_t* val) const { *val = as_uint32(); }
get(int32_t * val)3578 void get(int32_t* val) const { *val = as_int32(); }
get(uint64_t * val)3579 void get(uint64_t* val) const { *val = as_uint64(); }
get(int64_t * val)3580 void get(int64_t* val) const { *val = as_int64(); }
get(float * val)3581 void get(float* val) const { *val = as_float(); }
get(double * val)3582 void get(double* val) const { *val = as_double(); }
get(std::string * val)3583 void get(std::string* val) const { *val = as_std_string(); }
get(ConstChars * val)3584 void get(ConstChars* val) const { *val = as_string(); }
get(ConstBytes * val)3585 void get(ConstBytes* val) const { *val = as_bytes(); }
get_signed(int32_t * val)3586 void get_signed(int32_t* val) const { *val = as_sint32(); }
get_signed(int64_t * val)3587 void get_signed(int64_t* val) const { *val = as_sint64(); }
3588
3589 // For enum types.
3590 template <typename T,
3591 typename = typename std::enable_if<std::is_enum<T>::value, T>::type>
get(T * val)3592 void get(T* val) const {
3593 *val = static_cast<T>(as_int32());
3594 }
3595
3596 // Serializes the field back into a proto-encoded byte stream and appends it
3597 // to |dst|. |dst| is resized accordingly.
3598 void SerializeAndAppendTo(std::string* dst) const;
3599
3600 // Serializes the field back into a proto-encoded byte stream and appends it
3601 // to |dst|. |dst| is resized accordingly.
3602 void SerializeAndAppendTo(std::vector<uint8_t>* dst) const;
3603
3604 private:
3605 template <typename Container>
3606 void SerializeAndAppendToInternal(Container* dst) const;
3607
3608 // Fields are deliberately not initialized to keep the class trivially
3609 // constructible. It makes a large perf difference for ProtoDecoder.
3610
3611 uint64_t int_value_; // In kLengthDelimited this contains the data() addr.
3612 uint32_t size_; // Only valid when when type == kLengthDelimited.
3613 uint16_t id_; // Proto field ordinal.
3614 uint8_t type_; // proto_utils::ProtoWireType.
3615 };
3616
3617 // The Field struct is used in a lot of perf-sensitive contexts.
3618 static_assert(sizeof(Field) == 16, "Field struct too big");
3619
3620 } // namespace protozero
3621
3622 #endif // INCLUDE_PERFETTO_PROTOZERO_FIELD_H_
3623 /*
3624 * Copyright (C) 2018 The Android Open Source Project
3625 *
3626 * Licensed under the Apache License, Version 2.0 (the "License");
3627 * you may not use this file except in compliance with the License.
3628 * You may obtain a copy of the License at
3629 *
3630 * http://www.apache.org/licenses/LICENSE-2.0
3631 *
3632 * Unless required by applicable law or agreed to in writing, software
3633 * distributed under the License is distributed on an "AS IS" BASIS,
3634 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3635 * See the License for the specific language governing permissions and
3636 * limitations under the License.
3637 */
3638
3639 #ifndef INCLUDE_PERFETTO_PROTOZERO_PROTO_DECODER_H_
3640 #define INCLUDE_PERFETTO_PROTOZERO_PROTO_DECODER_H_
3641
3642 #include <stdint.h>
3643 #include <array>
3644 #include <memory>
3645 #include <vector>
3646
3647 // gen_amalgamated expanded: #include "perfetto/base/compiler.h"
3648 // gen_amalgamated expanded: #include "perfetto/base/logging.h"
3649 // gen_amalgamated expanded: #include "perfetto/protozero/field.h"
3650 // gen_amalgamated expanded: #include "perfetto/protozero/proto_utils.h"
3651
3652 namespace protozero {
3653
3654 // A generic protobuf decoder. Doesn't require any knowledge about the proto
3655 // schema. It tokenizes fields, retrieves their ID and type and exposes
3656 // accessors to retrieve its values.
3657 // It does NOT recurse in nested submessages, instead it just computes their
3658 // boundaries, recursion is left to the caller.
3659 // This class is designed to be used in perf-sensitive contexts. It does not
3660 // allocate and does not perform any proto semantic checks (e.g. repeated /
3661 // required / optional). It's supposedly safe wrt out-of-bounds memory accesses
3662 // (see proto_decoder_fuzzer.cc).
3663 // This class serves also as a building block for TypedProtoDecoder, used when
3664 // the schema is known at compile time.
3665 class PERFETTO_EXPORT ProtoDecoder {
3666 public:
3667 // Creates a ProtoDecoder using the given |buffer| with size |length| bytes.
ProtoDecoder(const void * buffer,size_t length)3668 ProtoDecoder(const void* buffer, size_t length)
3669 : begin_(reinterpret_cast<const uint8_t*>(buffer)),
3670 end_(begin_ + length),
3671 read_ptr_(begin_) {}
ProtoDecoder(const std::string & str)3672 ProtoDecoder(const std::string& str) : ProtoDecoder(str.data(), str.size()) {}
ProtoDecoder(const ConstBytes & cb)3673 ProtoDecoder(const ConstBytes& cb) : ProtoDecoder(cb.data, cb.size) {}
3674
3675 // Reads the next field from the buffer and advances the read cursor. If a
3676 // full field cannot be read, the returned Field will be invalid (i.e.
3677 // field.valid() == false).
3678 Field ReadField();
3679
3680 // Finds the first field with the given id. Doesn't affect the read cursor.
3681 Field FindField(uint32_t field_id);
3682
3683 // Resets the read cursor to the start of the buffer.
Reset()3684 void Reset() { read_ptr_ = begin_; }
3685
3686 // Resets the read cursor to the given position (must be within the buffer).
Reset(const uint8_t * pos)3687 void Reset(const uint8_t* pos) {
3688 PERFETTO_DCHECK(pos >= begin_ && pos < end_);
3689 read_ptr_ = pos;
3690 }
3691
3692 // Returns the position of read cursor, relative to the start of the buffer.
read_offset()3693 size_t read_offset() const { return static_cast<size_t>(read_ptr_ - begin_); }
3694
bytes_left()3695 size_t bytes_left() const {
3696 PERFETTO_DCHECK(read_ptr_ <= end_);
3697 return static_cast<size_t>(end_ - read_ptr_);
3698 }
3699
begin()3700 const uint8_t* begin() const { return begin_; }
end()3701 const uint8_t* end() const { return end_; }
3702
3703 protected:
3704 const uint8_t* const begin_;
3705 const uint8_t* const end_;
3706 const uint8_t* read_ptr_ = nullptr;
3707 };
3708
3709 // An iterator-like class used to iterate through repeated fields. Used by
3710 // TypedProtoDecoder. The iteration sequence is a bit counter-intuitive due to
3711 // the fact that fields_[field_id] holds the *last* value of the field, not the
3712 // first, but the remaining storage holds repeated fields in FIFO order.
3713 // Assume that we push the 10,11,12 into a repeated field with ID=1.
3714 //
3715 // Decoder memory layout: [ fields storage ] [ repeated fields storage ]
3716 // 1st iteration: 10
3717 // 2nd iteration: 11 10
3718 // 3rd iteration: 12 10 11
3719 //
3720 // We start the iteration @ fields_[num_fields], which is the start of the
3721 // repeated fields storage, proceed until the end and lastly jump @ fields_[id].
3722 template <typename T>
3723 class RepeatedFieldIterator {
3724 public:
RepeatedFieldIterator(uint32_t field_id,const Field * begin,const Field * end,const Field * last)3725 RepeatedFieldIterator(uint32_t field_id,
3726 const Field* begin,
3727 const Field* end,
3728 const Field* last)
3729 : field_id_(field_id), iter_(begin), end_(end), last_(last) {
3730 FindNextMatchingId();
3731 }
3732
3733 // Constructs an invalid iterator.
RepeatedFieldIterator()3734 RepeatedFieldIterator()
3735 : field_id_(0u), iter_(nullptr), end_(nullptr), last_(nullptr) {}
3736
3737 explicit operator bool() const { return iter_ != end_; }
field()3738 const Field& field() const { return *iter_; }
3739
3740 T operator*() const {
3741 T val{};
3742 iter_->get(&val);
3743 return val;
3744 }
3745 const Field* operator->() const { return iter_; }
3746
3747 RepeatedFieldIterator& operator++() {
3748 PERFETTO_DCHECK(iter_ != end_);
3749 if (iter_ == last_) {
3750 iter_ = end_;
3751 return *this;
3752 }
3753 ++iter_;
3754 FindNextMatchingId();
3755 return *this;
3756 }
3757
3758 RepeatedFieldIterator operator++(int) {
3759 PERFETTO_DCHECK(iter_ != end_);
3760 RepeatedFieldIterator it(*this);
3761 ++(*this);
3762 return it;
3763 }
3764
3765 private:
FindNextMatchingId()3766 void FindNextMatchingId() {
3767 PERFETTO_DCHECK(iter_ != last_);
3768 for (; iter_ != end_; ++iter_) {
3769 if (iter_->id() == field_id_)
3770 return;
3771 }
3772 iter_ = last_->valid() ? last_ : end_;
3773 }
3774
3775 uint32_t field_id_;
3776
3777 // Initially points to the beginning of the repeated field storage, then is
3778 // incremented as we call operator++().
3779 const Field* iter_;
3780
3781 // Always points to fields_[size_], i.e. past the end of the storage.
3782 const Field* end_;
3783
3784 // Always points to fields_[field_id].
3785 const Field* last_;
3786 };
3787
3788 // As RepeatedFieldIterator, but allows iterating over a packed repeated field
3789 // (which will be initially stored as a single length-delimited field).
3790 // See |GetPackedRepeatedField| for details.
3791 //
3792 // Assumes little endianness, and that the input buffers are well formed -
3793 // containing an exact multiple of encoded elements.
3794 template <proto_utils::ProtoWireType wire_type, typename CppType>
3795 class PackedRepeatedFieldIterator {
3796 public:
PackedRepeatedFieldIterator(const uint8_t * data_begin,size_t size,bool * parse_error_ptr)3797 PackedRepeatedFieldIterator(const uint8_t* data_begin,
3798 size_t size,
3799 bool* parse_error_ptr)
3800 : data_end_(data_begin ? data_begin + size : nullptr),
3801 read_ptr_(data_begin),
3802 parse_error_(parse_error_ptr) {
3803 using proto_utils::ProtoWireType;
3804 static_assert(wire_type == ProtoWireType::kVarInt ||
3805 wire_type == ProtoWireType::kFixed32 ||
3806 wire_type == ProtoWireType::kFixed64,
3807 "invalid type");
3808
3809 PERFETTO_DCHECK(parse_error_ptr);
3810
3811 // Either the field is unset (and there are no data pointer), or the field
3812 // is set with a zero length payload. Mark the iterator as invalid in both
3813 // cases.
3814 if (size == 0) {
3815 curr_value_valid_ = false;
3816 return;
3817 }
3818
3819 if ((wire_type == ProtoWireType::kFixed32 && (size % 4) != 0) ||
3820 (wire_type == ProtoWireType::kFixed64 && (size % 8) != 0)) {
3821 *parse_error_ = true;
3822 curr_value_valid_ = false;
3823 return;
3824 }
3825
3826 ++(*this);
3827 }
3828
3829 const CppType operator*() const { return curr_value_; }
3830 explicit operator bool() const { return curr_value_valid_; }
3831
3832 PackedRepeatedFieldIterator& operator++() {
3833 using proto_utils::ProtoWireType;
3834
3835 if (PERFETTO_UNLIKELY(!curr_value_valid_))
3836 return *this;
3837
3838 if (PERFETTO_UNLIKELY(read_ptr_ == data_end_)) {
3839 curr_value_valid_ = false;
3840 return *this;
3841 }
3842
3843 if (wire_type == ProtoWireType::kVarInt) {
3844 uint64_t new_value = 0;
3845 const uint8_t* new_pos =
3846 proto_utils::ParseVarInt(read_ptr_, data_end_, &new_value);
3847
3848 if (PERFETTO_UNLIKELY(new_pos == read_ptr_)) {
3849 // Failed to decode the varint (probably incomplete buffer).
3850 *parse_error_ = true;
3851 curr_value_valid_ = false;
3852 } else {
3853 read_ptr_ = new_pos;
3854 curr_value_ = static_cast<CppType>(new_value);
3855 }
3856 } else { // kFixed32 or kFixed64
3857 constexpr size_t kStep = wire_type == ProtoWireType::kFixed32 ? 4 : 8;
3858
3859 // NB: the raw buffer is not guaranteed to be aligned, so neither are
3860 // these copies.
3861 memcpy(&curr_value_, read_ptr_, sizeof(CppType));
3862 read_ptr_ += kStep;
3863 }
3864
3865 return *this;
3866 }
3867
3868 PackedRepeatedFieldIterator operator++(int) {
3869 PackedRepeatedFieldIterator it(*this);
3870 ++(*this);
3871 return it;
3872 }
3873
3874 private:
3875 // Might be null if the backing proto field isn't set.
3876 const uint8_t* const data_end_;
3877
3878 // The iterator looks ahead by an element, so |curr_value| holds the value
3879 // to be returned when the caller dereferences the iterator, and |read_ptr_|
3880 // points at the start of the next element to be decoded.
3881 // |read_ptr_| might be null if the backing proto field isn't set.
3882 const uint8_t* read_ptr_;
3883 CppType curr_value_ = 0;
3884
3885 // Set to false once we've exhausted the iterator, or encountered an error.
3886 bool curr_value_valid_ = true;
3887
3888 // Where to set parsing errors, supplied by the caller.
3889 bool* const parse_error_;
3890 };
3891
3892 // This decoder loads all fields upfront, without recursing in nested messages.
3893 // It is used as a base class for typed decoders generated by the pbzero plugin.
3894 // The split between TypedProtoDecoderBase and TypedProtoDecoder<> is to have
3895 // unique definition of functions like ParseAllFields() and ExpandHeapStorage().
3896 // The storage (either on-stack or on-heap) for this class is organized as
3897 // follows:
3898 // |-------------------------- fields_ ----------------------|
3899 // [ field 0 (invalid) ] [ fields 1 .. N ] [ repeated fields ]
3900 // ^ ^
3901 // num_fields_ size_
3902 class PERFETTO_EXPORT TypedProtoDecoderBase : public ProtoDecoder {
3903 public:
3904 // If the field |id| is known at compile time, prefer the templated
3905 // specialization at<kFieldNumber>().
Get(uint32_t id)3906 const Field& Get(uint32_t id) const {
3907 return PERFETTO_LIKELY(id < num_fields_) ? fields_[id] : fields_[0];
3908 }
3909
3910 // Returns an object that allows to iterate over all instances of a repeated
3911 // field given its id. Example usage:
3912 // for (auto it = decoder.GetRepeated<int32_t>(N); it; ++it) { ... }
3913 template <typename T>
GetRepeated(uint32_t field_id)3914 RepeatedFieldIterator<T> GetRepeated(uint32_t field_id) const {
3915 return RepeatedFieldIterator<T>(field_id, &fields_[num_fields_],
3916 &fields_[size_], &fields_[field_id]);
3917 }
3918
3919 // Returns an objects that allows to iterate over all entries of a packed
3920 // repeated field given its id and type. The |wire_type| is necessary for
3921 // decoding the packed field, the |cpp_type| is for convenience & stronger
3922 // typing.
3923 //
3924 // The caller must also supply a pointer to a bool that is set to true if the
3925 // packed buffer is found to be malformed while iterating (so you need to
3926 // exhaust the iterator if you want to check the full extent of the buffer).
3927 //
3928 // Note that unlike standard protobuf parsers, protozero does not allow
3929 // treating of packed repeated fields as non-packed and vice-versa (therefore
3930 // not making the packed option forwards and backwards compatible). So
3931 // the caller needs to use the right accessor for correct results.
3932 template <proto_utils::ProtoWireType wire_type, typename cpp_type>
GetPackedRepeated(uint32_t field_id,bool * parse_error_location)3933 PackedRepeatedFieldIterator<wire_type, cpp_type> GetPackedRepeated(
3934 uint32_t field_id,
3935 bool* parse_error_location) const {
3936 const Field& field = Get(field_id);
3937 if (field.valid()) {
3938 return PackedRepeatedFieldIterator<wire_type, cpp_type>(
3939 field.data(), field.size(), parse_error_location);
3940 } else {
3941 return PackedRepeatedFieldIterator<wire_type, cpp_type>(
3942 nullptr, 0, parse_error_location);
3943 }
3944 }
3945
3946 protected:
TypedProtoDecoderBase(Field * storage,uint32_t num_fields,uint32_t capacity,const uint8_t * buffer,size_t length)3947 TypedProtoDecoderBase(Field* storage,
3948 uint32_t num_fields,
3949 uint32_t capacity,
3950 const uint8_t* buffer,
3951 size_t length)
3952 : ProtoDecoder(buffer, length),
3953 fields_(storage),
3954 num_fields_(num_fields),
3955 size_(num_fields),
3956 capacity_(capacity) {
3957 // The reason why Field needs to be trivially de/constructible is to avoid
3958 // implicit initializers on all the ~1000 entries. We need it to initialize
3959 // only on the first |max_field_id| fields, the remaining capacity doesn't
3960 // require initialization.
3961 static_assert(std::is_trivially_constructible<Field>::value &&
3962 std::is_trivially_destructible<Field>::value &&
3963 std::is_trivial<Field>::value,
3964 "Field must be a trivial aggregate type");
3965 memset(fields_, 0, sizeof(Field) * num_fields_);
3966 }
3967
3968 void ParseAllFields();
3969
3970 // Called when the default on-stack storage is exhausted and new repeated
3971 // fields need to be pushed.
3972 void ExpandHeapStorage();
3973
3974 // Used only in presence of a large number of repeated fields, when the
3975 // default on-stack storage is exhausted.
3976 std::unique_ptr<Field[]> heap_storage_;
3977
3978 // Points to the storage, either on-stack (default, provided by the template
3979 // specialization) or |heap_storage_| after ExpandHeapStorage() is called, in
3980 // case of a large number of repeated fields.
3981 Field* fields_;
3982
3983 // Number of fields without accounting repeated storage. This is equal to
3984 // MAX_FIELD_ID + 1 (to account for the invalid 0th field).
3985 // This value is always <= size_ (and hence <= capacity);
3986 uint32_t num_fields_;
3987
3988 // Number of active |fields_| entries. This is initially equal to the highest
3989 // number of fields for the message (num_fields_ == MAX_FIELD_ID + 1) and can
3990 // grow up to |capacity_| in the case of repeated fields.
3991 uint32_t size_;
3992
3993 // Initially equal to kFieldsCapacity of the TypedProtoDecoder
3994 // specialization. Can grow when falling back on heap-based storage, in which
3995 // case it represents the size (#fields with each entry of a repeated field
3996 // counted individually) of the |heap_storage_| array.
3997 uint32_t capacity_;
3998 };
3999
4000 // Template class instantiated by the auto-generated decoder classes declared in
4001 // xxx.pbzero.h files.
4002 template <int MAX_FIELD_ID, bool HAS_NONPACKED_REPEATED_FIELDS>
4003 class TypedProtoDecoder : public TypedProtoDecoderBase {
4004 public:
TypedProtoDecoder(const uint8_t * buffer,size_t length)4005 TypedProtoDecoder(const uint8_t* buffer, size_t length)
4006 : TypedProtoDecoderBase(on_stack_storage_,
4007 /*num_fields=*/MAX_FIELD_ID + 1,
4008 kCapacity,
4009 buffer,
4010 length) {
4011 static_assert(MAX_FIELD_ID <= kMaxDecoderFieldId, "Field ordinal too high");
4012 TypedProtoDecoderBase::ParseAllFields();
4013 }
4014
4015 template <uint32_t FIELD_ID>
at()4016 const Field& at() const {
4017 static_assert(FIELD_ID <= MAX_FIELD_ID, "FIELD_ID > MAX_FIELD_ID");
4018 return fields_[FIELD_ID];
4019 }
4020
TypedProtoDecoder(TypedProtoDecoder && other)4021 TypedProtoDecoder(TypedProtoDecoder&& other) noexcept
4022 : TypedProtoDecoderBase(std::move(other)) {
4023 // If the moved-from decoder was using on-stack storage, we need to update
4024 // our pointer to point to this decoder's on-stack storage.
4025 if (fields_ == other.on_stack_storage_) {
4026 fields_ = on_stack_storage_;
4027 memcpy(on_stack_storage_, other.on_stack_storage_,
4028 sizeof(on_stack_storage_));
4029 }
4030 }
4031
4032 private:
4033 // In the case of non-repeated fields, this constant defines the highest field
4034 // id we are able to decode. This is to limit the on-stack storage.
4035 // In the case of repeated fields, this constant defines the max number of
4036 // repeated fields that we'll be able to store before falling back on the
4037 // heap. Keep this value in sync with the one in protozero_generator.cc.
4038 static constexpr size_t kMaxDecoderFieldId = 999;
4039
4040 // If we the message has no repeated fields we need at most N Field entries
4041 // in the on-stack storage, where N is the highest field id.
4042 // Otherwise we need some room to store repeated fields.
4043 static constexpr size_t kCapacity =
4044 1 + (HAS_NONPACKED_REPEATED_FIELDS ? kMaxDecoderFieldId : MAX_FIELD_ID);
4045
4046 Field on_stack_storage_[kCapacity];
4047 };
4048
4049 } // namespace protozero
4050
4051 #endif // INCLUDE_PERFETTO_PROTOZERO_PROTO_DECODER_H_
4052 // Autogenerated by the ProtoZero compiler plugin. DO NOT EDIT.
4053
4054 #ifndef PERFETTO_PROTOS_PROTOS_PERFETTO_TRACE_TRACE_PACKET_PROTO_H_
4055 #define PERFETTO_PROTOS_PROTOS_PERFETTO_TRACE_TRACE_PACKET_PROTO_H_
4056
4057 #include <stddef.h>
4058 #include <stdint.h>
4059
4060 // gen_amalgamated expanded: #include "perfetto/protozero/message.h"
4061 // gen_amalgamated expanded: #include "perfetto/protozero/packed_repeated_fields.h"
4062 // gen_amalgamated expanded: #include "perfetto/protozero/proto_decoder.h"
4063 // gen_amalgamated expanded: #include "perfetto/protozero/proto_utils.h"
4064
4065 namespace perfetto {
4066 namespace protos {
4067 namespace pbzero {
4068
4069 class AndroidLogPacket;
4070 class BatteryCounters;
4071 class ChromeBenchmarkMetadata;
4072 class ChromeEventBundle;
4073 class ChromeMetadataPacket;
4074 class ClockSnapshot;
4075 class CpuInfo;
4076 class DeobfuscationMapping;
4077 class ExtensionDescriptor;
4078 class FtraceEventBundle;
4079 class FtraceStats;
4080 class GpuCounterEvent;
4081 class GpuLog;
4082 class GpuMemTotalEvent;
4083 class GpuRenderStageEvent;
4084 class GraphicsFrameEvent;
4085 class HeapGraph;
4086 class InitialDisplayState;
4087 class InodeFileMap;
4088 class InternedData;
4089 class MemoryTrackerSnapshot;
4090 class ModuleSymbols;
4091 class PackagesList;
4092 class PerfSample;
4093 class PerfettoMetatrace;
4094 class PowerRails;
4095 class ProcessDescriptor;
4096 class ProcessStats;
4097 class ProcessTree;
4098 class ProfilePacket;
4099 class ProfiledFrameSymbols;
4100 class SmapsPacket;
4101 class StreamingProfilePacket;
4102 class SysStats;
4103 class SystemInfo;
4104 class TestEvent;
4105 class ThreadDescriptor;
4106 class TraceConfig;
4107 class TracePacketDefaults;
4108 class TraceStats;
4109 class TracingServiceEvent;
4110 class TrackDescriptor;
4111 class TrackEvent;
4112 class Trigger;
4113 class VulkanApiEvent;
4114 class VulkanMemoryEvent;
4115
4116 enum TracePacket_SequenceFlags : int32_t {
4117 TracePacket_SequenceFlags_SEQ_UNSPECIFIED = 0,
4118 TracePacket_SequenceFlags_SEQ_INCREMENTAL_STATE_CLEARED = 1,
4119 TracePacket_SequenceFlags_SEQ_NEEDS_INCREMENTAL_STATE = 2,
4120 };
4121
4122 const TracePacket_SequenceFlags TracePacket_SequenceFlags_MIN = TracePacket_SequenceFlags_SEQ_UNSPECIFIED;
4123 const TracePacket_SequenceFlags TracePacket_SequenceFlags_MAX = TracePacket_SequenceFlags_SEQ_NEEDS_INCREMENTAL_STATE;
4124
4125 class TracePacket_Decoder : public ::protozero::TypedProtoDecoder</*MAX_FIELD_ID=*/900, /*HAS_NONPACKED_REPEATED_FIELDS=*/false> {
4126 public:
TracePacket_Decoder(const uint8_t * data,size_t len)4127 TracePacket_Decoder(const uint8_t* data, size_t len) : TypedProtoDecoder(data, len) {}
TracePacket_Decoder(const std::string & raw)4128 explicit TracePacket_Decoder(const std::string& raw) : TypedProtoDecoder(reinterpret_cast<const uint8_t*>(raw.data()), raw.size()) {}
TracePacket_Decoder(const::protozero::ConstBytes & raw)4129 explicit TracePacket_Decoder(const ::protozero::ConstBytes& raw) : TypedProtoDecoder(raw.data, raw.size) {}
has_timestamp()4130 bool has_timestamp() const { return at<8>().valid(); }
timestamp()4131 uint64_t timestamp() const { return at<8>().as_uint64(); }
has_timestamp_clock_id()4132 bool has_timestamp_clock_id() const { return at<58>().valid(); }
timestamp_clock_id()4133 uint32_t timestamp_clock_id() const { return at<58>().as_uint32(); }
has_process_tree()4134 bool has_process_tree() const { return at<2>().valid(); }
process_tree()4135 ::protozero::ConstBytes process_tree() const { return at<2>().as_bytes(); }
has_process_stats()4136 bool has_process_stats() const { return at<9>().valid(); }
process_stats()4137 ::protozero::ConstBytes process_stats() const { return at<9>().as_bytes(); }
has_inode_file_map()4138 bool has_inode_file_map() const { return at<4>().valid(); }
inode_file_map()4139 ::protozero::ConstBytes inode_file_map() const { return at<4>().as_bytes(); }
has_chrome_events()4140 bool has_chrome_events() const { return at<5>().valid(); }
chrome_events()4141 ::protozero::ConstBytes chrome_events() const { return at<5>().as_bytes(); }
has_clock_snapshot()4142 bool has_clock_snapshot() const { return at<6>().valid(); }
clock_snapshot()4143 ::protozero::ConstBytes clock_snapshot() const { return at<6>().as_bytes(); }
has_sys_stats()4144 bool has_sys_stats() const { return at<7>().valid(); }
sys_stats()4145 ::protozero::ConstBytes sys_stats() const { return at<7>().as_bytes(); }
has_track_event()4146 bool has_track_event() const { return at<11>().valid(); }
track_event()4147 ::protozero::ConstBytes track_event() const { return at<11>().as_bytes(); }
has_trace_config()4148 bool has_trace_config() const { return at<33>().valid(); }
trace_config()4149 ::protozero::ConstBytes trace_config() const { return at<33>().as_bytes(); }
has_ftrace_stats()4150 bool has_ftrace_stats() const { return at<34>().valid(); }
ftrace_stats()4151 ::protozero::ConstBytes ftrace_stats() const { return at<34>().as_bytes(); }
has_trace_stats()4152 bool has_trace_stats() const { return at<35>().valid(); }
trace_stats()4153 ::protozero::ConstBytes trace_stats() const { return at<35>().as_bytes(); }
has_profile_packet()4154 bool has_profile_packet() const { return at<37>().valid(); }
profile_packet()4155 ::protozero::ConstBytes profile_packet() const { return at<37>().as_bytes(); }
has_battery()4156 bool has_battery() const { return at<38>().valid(); }
battery()4157 ::protozero::ConstBytes battery() const { return at<38>().as_bytes(); }
has_power_rails()4158 bool has_power_rails() const { return at<40>().valid(); }
power_rails()4159 ::protozero::ConstBytes power_rails() const { return at<40>().as_bytes(); }
has_android_log()4160 bool has_android_log() const { return at<39>().valid(); }
android_log()4161 ::protozero::ConstBytes android_log() const { return at<39>().as_bytes(); }
has_system_info()4162 bool has_system_info() const { return at<45>().valid(); }
system_info()4163 ::protozero::ConstBytes system_info() const { return at<45>().as_bytes(); }
has_trigger()4164 bool has_trigger() const { return at<46>().valid(); }
trigger()4165 ::protozero::ConstBytes trigger() const { return at<46>().as_bytes(); }
has_packages_list()4166 bool has_packages_list() const { return at<47>().valid(); }
packages_list()4167 ::protozero::ConstBytes packages_list() const { return at<47>().as_bytes(); }
has_chrome_benchmark_metadata()4168 bool has_chrome_benchmark_metadata() const { return at<48>().valid(); }
chrome_benchmark_metadata()4169 ::protozero::ConstBytes chrome_benchmark_metadata() const { return at<48>().as_bytes(); }
has_perfetto_metatrace()4170 bool has_perfetto_metatrace() const { return at<49>().valid(); }
perfetto_metatrace()4171 ::protozero::ConstBytes perfetto_metatrace() const { return at<49>().as_bytes(); }
has_chrome_metadata()4172 bool has_chrome_metadata() const { return at<51>().valid(); }
chrome_metadata()4173 ::protozero::ConstBytes chrome_metadata() const { return at<51>().as_bytes(); }
has_gpu_counter_event()4174 bool has_gpu_counter_event() const { return at<52>().valid(); }
gpu_counter_event()4175 ::protozero::ConstBytes gpu_counter_event() const { return at<52>().as_bytes(); }
has_gpu_render_stage_event()4176 bool has_gpu_render_stage_event() const { return at<53>().valid(); }
gpu_render_stage_event()4177 ::protozero::ConstBytes gpu_render_stage_event() const { return at<53>().as_bytes(); }
has_streaming_profile_packet()4178 bool has_streaming_profile_packet() const { return at<54>().valid(); }
streaming_profile_packet()4179 ::protozero::ConstBytes streaming_profile_packet() const { return at<54>().as_bytes(); }
has_heap_graph()4180 bool has_heap_graph() const { return at<56>().valid(); }
heap_graph()4181 ::protozero::ConstBytes heap_graph() const { return at<56>().as_bytes(); }
has_graphics_frame_event()4182 bool has_graphics_frame_event() const { return at<57>().valid(); }
graphics_frame_event()4183