third_party/protobuf/src/google/protobuf/arena.h
Go to the documentation of this file.
1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc. All rights reserved.
3 // https://developers.google.com/protocol-buffers/
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 // * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 // * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following disclaimer
13 // in the documentation and/or other materials provided with the
14 // distribution.
15 // * Neither the name of Google Inc. nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 
31 // This file defines an Arena allocator for better allocation performance.
32 
33 #ifndef GOOGLE_PROTOBUF_ARENA_H__
34 #define GOOGLE_PROTOBUF_ARENA_H__
35 
36 
37 #include <limits>
38 #include <type_traits>
39 #include <utility>
40 #ifdef max
41 #undef max // Visual Studio defines this macro
42 #endif
43 #if defined(_MSC_VER) && !defined(_LIBCPP_STD_VER) && !_HAS_EXCEPTIONS
44 // Work around bugs in MSVC <typeinfo> header when _HAS_EXCEPTIONS=0.
45 #include <exception>
46 #include <typeinfo>
47 namespace std {
48 using type_info = ::type_info;
49 }
50 #else
51 #include <typeinfo>
52 #endif
53 
54 #include <type_traits>
55 #include <google/protobuf/arena_impl.h>
56 #include <google/protobuf/port.h>
57 
58 #include <google/protobuf/port_def.inc>
59 
60 #ifdef SWIG
61 #error "You cannot SWIG proto headers"
62 #endif
63 
64 namespace google {
65 namespace protobuf {
66 
67 struct ArenaOptions; // defined below
68 class Arena; // defined below
69 class Message; // defined in message.h
70 class MessageLite;
71 template <typename Key, typename T>
72 class Map;
73 
74 namespace arena_metrics {
75 
76 void EnableArenaMetrics(ArenaOptions* options);
77 
78 } // namespace arena_metrics
79 
80 namespace TestUtil {
81 class ReflectionTester; // defined in test_util.h
82 } // namespace TestUtil
83 
84 namespace internal {
85 
86 struct ArenaStringPtr; // defined in arenastring.h
87 class InlinedStringField; // defined in inlined_string_field.h
88 class LazyField; // defined in lazy_field.h
89 class EpsCopyInputStream; // defined in parse_context.h
90 
91 template <typename Type>
92 class GenericTypeHandler; // defined in repeated_field.h
93 
94 inline PROTOBUF_ALWAYS_INLINE
95 void* AlignTo(void* ptr, size_t align) {
96  return reinterpret_cast<void*>(
97  (reinterpret_cast<uintptr_t>(ptr) + align - 1) & (~align + 1));
98 }
99 
100 // Templated cleanup methods.
101 template <typename T>
102 void arena_destruct_object(void* object) {
103  reinterpret_cast<T*>(object)->~T();
104 }
105 
106 template <bool destructor_skippable, typename T>
108  constexpr static void (*destructor)(void*) = &arena_destruct_object<T>;
109 };
110 
111 template <typename T>
113  constexpr static void (*destructor)(void*) = nullptr;
114 };
115 
116 template <typename T>
117 void arena_delete_object(void* object) {
118  delete reinterpret_cast<T*>(object);
119 }
120 } // namespace internal
121 
122 // ArenaOptions provides optional additional parameters to arena construction
123 // that control its block-allocation behavior.
124 struct ArenaOptions {
125  // This defines the size of the first block requested from the system malloc.
126  // Subsequent block sizes will increase in a geometric series up to a maximum.
127  size_t start_block_size;
128 
129  // This defines the maximum block size requested from system malloc (unless an
130  // individual arena allocation request occurs with a size larger than this
131  // maximum). Requested block sizes increase up to this value, then remain
132  // here.
133  size_t max_block_size;
134 
135  // An initial block of memory for the arena to use, or NULL for none. If
136  // provided, the block must live at least as long as the arena itself. The
137  // creator of the Arena retains ownership of the block after the Arena is
138  // destroyed.
139  char* initial_block;
140 
141  // The size of the initial block, if provided.
142  size_t initial_block_size;
143 
144  // A function pointer to an alloc method that returns memory blocks of size
145  // requested. By default, it contains a ptr to the malloc function.
146  //
147  // NOTE: block_alloc and dealloc functions are expected to behave like
148  // malloc and free, including Asan poisoning.
149  void* (*block_alloc)(size_t);
150  // A function pointer to a dealloc method that takes ownership of the blocks
151  // from the arena. By default, it contains a ptr to a wrapper function that
152  // calls free.
153  void (*block_dealloc)(void*, size_t);
154 
158  initial_block(NULL),
160  block_alloc(nullptr),
161  block_dealloc(nullptr),
162  make_metrics_collector(nullptr) {}
163 
164  private:
165  // If make_metrics_collector is not nullptr, it will be called at Arena init
166  // time. It may return a pointer to a collector instance that will be notified
167  // of interesting events related to the arena.
168  internal::ArenaMetricsCollector* (*make_metrics_collector)();
169 
171  return make_metrics_collector ? (*make_metrics_collector)() : nullptr;
172  }
173 
178  res.block_alloc = block_alloc;
181  return res;
182  }
183 
185 
186  friend class Arena;
187  friend class ArenaOptionsTestFriend;
188 };
189 
190 // Support for non-RTTI environments. (The metrics hooks API uses type
191 // information.)
192 #if PROTOBUF_RTTI
193 #define RTTI_TYPE_ID(type) (&typeid(type))
194 #else
195 #define RTTI_TYPE_ID(type) (NULL)
196 #endif
197 
198 // Arena allocator. Arena allocation replaces ordinary (heap-based) allocation
199 // with new/delete, and improves performance by aggregating allocations into
200 // larger blocks and freeing allocations all at once. Protocol messages are
201 // allocated on an arena by using Arena::CreateMessage<T>(Arena*), below, and
202 // are automatically freed when the arena is destroyed.
203 //
204 // This is a thread-safe implementation: multiple threads may allocate from the
205 // arena concurrently. Destruction is not thread-safe and the destructing
206 // thread must synchronize with users of the arena first.
207 //
208 // An arena provides two allocation interfaces: CreateMessage<T>, which works
209 // for arena-enabled proto2 message types as well as other types that satisfy
210 // the appropriate protocol (described below), and Create<T>, which works for
211 // any arbitrary type T. CreateMessage<T> is better when the type T supports it,
212 // because this interface (i) passes the arena pointer to the created object so
213 // that its sub-objects and internal allocations can use the arena too, and (ii)
214 // elides the object's destructor call when possible. Create<T> does not place
215 // any special requirements on the type T, and will invoke the object's
216 // destructor when the arena is destroyed.
217 //
218 // The arena message allocation protocol, required by
219 // CreateMessage<T>(Arena* arena, Args&&... args), is as follows:
220 //
221 // - The type T must have (at least) two constructors: a constructor callable
222 // with `args` (without `arena`), called when a T is allocated on the heap;
223 // and a constructor callable with `Arena* arena, Args&&... args`, called when
224 // a T is allocated on an arena. If the second constructor is called with a
225 // NULL arena pointer, it must be equivalent to invoking the first
226 // (`args`-only) constructor.
227 //
228 // - The type T must have a particular type trait: a nested type
229 // |InternalArenaConstructable_|. This is usually a typedef to |void|. If no
230 // such type trait exists, then the instantiation CreateMessage<T> will fail
231 // to compile.
232 //
233 // - The type T *may* have the type trait |DestructorSkippable_|. If this type
234 // trait is present in the type, then its destructor will not be called if and
235 // only if it was passed a non-NULL arena pointer. If this type trait is not
236 // present on the type, then its destructor is always called when the
237 // containing arena is destroyed.
238 //
239 // This protocol is implemented by all arena-enabled proto2 message classes as
240 // well as protobuf container types like RepeatedPtrField and Map. The protocol
241 // is internal to protobuf and is not guaranteed to be stable. Non-proto types
242 // should not rely on this protocol.
243 class PROTOBUF_EXPORT PROTOBUF_ALIGNAS(8) Arena final {
244  public:
245  // Default constructor with sensible default options, tuned for average
246  // use-cases.
247  inline Arena() : impl_() {}
248 
249  // Construct an arena with default options, except for the supplied
250  // initial block. It is more efficient to use this constructor
251  // instead of passing ArenaOptions if the only configuration needed
252  // by the caller is supplying an initial block.
253  inline Arena(char* initial_block, size_t initial_block_size)
254  : impl_(initial_block, initial_block_size) {}
255 
256  // Arena constructor taking custom options. See ArenaOptions above for
257  // descriptions of the options available.
258  explicit Arena(const ArenaOptions& options)
259  : impl_(options.initial_block, options.initial_block_size,
260  options.AllocationPolicy()) {}
261 
262  // Block overhead. Use this as a guide for how much to over-allocate the
263  // initial block if you want an allocation of size N to fit inside it.
264  //
265  // WARNING: if you allocate multiple objects, it is difficult to guarantee
266  // that a series of allocations will fit in the initial block, especially if
267  // Arena changes its alignment guarantees in the future!
268  static const size_t kBlockOverhead =
271 
272  inline ~Arena() {}
273 
274  // TODO(protobuf-team): Fix callers to use constructor and delete this method.
275  void Init(const ArenaOptions&) {}
276 
277  // API to create proto2 message objects on the arena. If the arena passed in
278  // is NULL, then a heap allocated object is returned. Type T must be a message
279  // defined in a .proto file with cc_enable_arenas set to true, otherwise a
280  // compilation error will occur.
281  //
282  // RepeatedField and RepeatedPtrField may also be instantiated directly on an
283  // arena with this method.
284  //
285  // This function also accepts any type T that satisfies the arena message
286  // allocation protocol, documented above.
287  template <typename T, typename... Args>
288  PROTOBUF_ALWAYS_INLINE static T* CreateMessage(Arena* arena, Args&&... args) {
289  static_assert(
291  "CreateMessage can only construct types that are ArenaConstructable");
292  // We must delegate to CreateMaybeMessage() and NOT CreateMessageInternal()
293  // because protobuf generated classes specialize CreateMaybeMessage() and we
294  // need to use that specialization for code size reasons.
295  return Arena::CreateMaybeMessage<T>(arena, static_cast<Args&&>(args)...);
296  }
297 
298  // API to create any objects on the arena. Note that only the object will
299  // be created on the arena; the underlying ptrs (in case of a proto2 message)
300  // will be still heap allocated. Proto messages should usually be allocated
301  // with CreateMessage<T>() instead.
302  //
303  // Note that even if T satisfies the arena message construction protocol
304  // (InternalArenaConstructable_ trait and optional DestructorSkippable_
305  // trait), as described above, this function does not follow the protocol;
306  // instead, it treats T as a black-box type, just as if it did not have these
307  // traits. Specifically, T's constructor arguments will always be only those
308  // passed to Create<T>() -- no additional arena pointer is implicitly added.
309  // Furthermore, the destructor will always be called at arena destruction time
310  // (unless the destructor is trivial). Hence, from T's point of view, it is as
311  // if the object were allocated on the heap (except that the underlying memory
312  // is obtained from the arena).
313  template <typename T, typename... Args>
314  PROTOBUF_NDEBUG_INLINE static T* Create(Arena* arena, Args&&... args) {
315  return CreateInternal<T>(arena, std::is_convertible<T*, MessageLite*>(),
316  static_cast<Args&&>(args)...);
317  }
318 
319  // Create an array of object type T on the arena *without* invoking the
320  // constructor of T. If `arena` is null, then the return value should be freed
321  // with `delete[] x;` (or `::operator delete[](x);`).
322  // To ensure safe uses, this function checks at compile time
323  // (when compiled as C++11) that T is trivially default-constructible and
324  // trivially destructible.
325  template <typename T>
326  PROTOBUF_NDEBUG_INLINE static T* CreateArray(Arena* arena,
327  size_t num_elements) {
328  static_assert(std::is_trivial<T>::value,
329  "CreateArray requires a trivially constructible type");
331  "CreateArray requires a trivially destructible type");
333  << "Requested size is too large to fit into size_t.";
334  if (arena == NULL) {
335  return static_cast<T*>(::operator new[](num_elements * sizeof(T)));
336  } else {
337  return arena->CreateInternalRawArray<T>(num_elements);
338  }
339  }
340 
341  // The following are routines are for monitoring. They will approximate the
342  // total sum allocated and used memory, but the exact value is an
343  // implementation deal. For instance allocated space depends on growth
344  // policies. Do not use these in unit tests.
345  // Returns the total space allocated by the arena, which is the sum of the
346  // sizes of the underlying blocks.
347  uint64_t SpaceAllocated() const { return impl_.SpaceAllocated(); }
348  // Returns the total space used by the arena. Similar to SpaceAllocated but
349  // does not include free space and block overhead. The total space returned
350  // may not include space used by other threads executing concurrently with
351  // the call to this method.
352  uint64_t SpaceUsed() const { return impl_.SpaceUsed(); }
353 
354  // Frees all storage allocated by this arena after calling destructors
355  // registered with OwnDestructor() and freeing objects registered with Own().
356  // Any objects allocated on this arena are unusable after this call. It also
357  // returns the total space used by the arena which is the sums of the sizes
358  // of the allocated blocks. This method is not thread-safe.
359  uint64_t Reset() { return impl_.Reset(); }
360 
361  // Adds |object| to a list of heap-allocated objects to be freed with |delete|
362  // when the arena is destroyed or reset.
363  template <typename T>
364  PROTOBUF_ALWAYS_INLINE void Own(T* object) {
365  OwnInternal(object, std::is_convertible<T*, MessageLite*>());
366  }
367 
368  // Adds |object| to a list of objects whose destructors will be manually
369  // called when the arena is destroyed or reset. This differs from Own() in
370  // that it does not free the underlying memory with |delete|; hence, it is
371  // normally only used for objects that are placement-newed into
372  // arena-allocated memory.
373  template <typename T>
374  PROTOBUF_ALWAYS_INLINE void OwnDestructor(T* object) {
375  if (object != NULL) {
376  impl_.AddCleanup(object, &internal::arena_destruct_object<T>);
377  }
378  }
379 
380  // Adds a custom member function on an object to the list of destructors that
381  // will be manually called when the arena is destroyed or reset. This differs
382  // from OwnDestructor() in that any member function may be specified, not only
383  // the class destructor.
384  PROTOBUF_ALWAYS_INLINE void OwnCustomDestructor(void* object,
385  void (*destruct)(void*)) {
386  impl_.AddCleanup(object, destruct);
387  }
388 
389  // Retrieves the arena associated with |value| if |value| is an arena-capable
390  // message, or NULL otherwise. If possible, the call resolves at compile time.
391  // Note that we can often devirtualize calls to `value->GetArena()` so usually
392  // calling this method is unnecessary.
393  template <typename T>
394  PROTOBUF_ALWAYS_INLINE static Arena* GetArena(const T* value) {
395  return GetArenaInternal(value);
396  }
397 
398  template <typename T>
399  class InternalHelper {
400  public:
401  // Provides access to protected GetOwningArena to generated messages.
402  static Arena* GetOwningArena(const T* p) { return p->GetOwningArena(); }
403 
404  // Provides access to protected GetArenaForAllocation to generated messages.
405  static Arena* GetArenaForAllocation(const T* p) {
406  return GetArenaForAllocationInternal(
407  p, std::is_convertible<T*, MessageLite*>());
408  }
409 
410  // Creates message-owned arena.
411  static Arena* CreateMessageOwnedArena() {
412  return new Arena(internal::MessageOwned{});
413  }
414 
415  // Checks whether the given arena is message-owned.
416  static bool IsMessageOwnedArena(Arena* arena) {
417  return arena->IsMessageOwned();
418  }
419 
420  private:
421  static Arena* GetArenaForAllocationInternal(
422  const T* p, std::true_type /*is_derived_from<MessageLite>*/) {
423  return p->GetArenaForAllocation();
424  }
425 
426  static Arena* GetArenaForAllocationInternal(
427  const T* p, std::false_type /*is_derived_from<MessageLite>*/) {
428  return GetArenaForAllocationForNonMessage(
429  p, typename is_arena_constructable::type());
430  }
431 
432  static Arena* GetArenaForAllocationForNonMessage(
433  const T* p, std::true_type /*is_arena_constructible*/) {
434  return p->GetArena();
435  }
436 
437  static Arena* GetArenaForAllocationForNonMessage(
438  const T* p, std::false_type /*is_arena_constructible*/) {
439  return GetArenaForAllocationForNonMessageNonArenaConstructible(
440  p, typename has_get_arena::type());
441  }
442 
443  static Arena* GetArenaForAllocationForNonMessageNonArenaConstructible(
444  const T* p, std::true_type /*has_get_arena*/) {
445  return p->GetArena();
446  }
447 
448  static Arena* GetArenaForAllocationForNonMessageNonArenaConstructible(
449  const T* /* p */, std::false_type /*has_get_arena*/) {
450  return nullptr;
451  }
452 
453  template <typename U>
454  static char DestructorSkippable(const typename U::DestructorSkippable_*);
455  template <typename U>
456  static double DestructorSkippable(...);
457 
458  typedef std::integral_constant<
459  bool, sizeof(DestructorSkippable<T>(static_cast<const T*>(0))) ==
460  sizeof(char) ||
462  is_destructor_skippable;
463 
464  template <typename U>
465  static char ArenaConstructable(
466  const typename U::InternalArenaConstructable_*);
467  template <typename U>
468  static double ArenaConstructable(...);
469 
470  typedef std::integral_constant<bool, sizeof(ArenaConstructable<T>(
471  static_cast<const T*>(0))) ==
472  sizeof(char)>
473  is_arena_constructable;
474 
475  template <typename U,
476  typename std::enable_if<
477  std::is_same<Arena*, decltype(std::declval<const U>()
478  .GetArena())>::value,
479  int>::type = 0>
480  static char HasGetArena(decltype(&U::GetArena));
481  template <typename U>
482  static double HasGetArena(...);
483 
484  typedef std::integral_constant<bool, sizeof(HasGetArena<T>(nullptr)) ==
485  sizeof(char)>
486  has_get_arena;
487 
488  template <typename... Args>
489  static T* Construct(void* ptr, Args&&... args) {
490  return new (ptr) T(static_cast<Args&&>(args)...);
491  }
492 
493  static inline PROTOBUF_ALWAYS_INLINE T* New() {
494  return new T(nullptr);
495  }
496 
497  static Arena* GetArena(const T* p) { return p->GetArena(); }
498 
499  friend class Arena;
500  friend class TestUtil::ReflectionTester;
501  };
502 
503  // Helper typetraits that indicates support for arenas in a type T at compile
504  // time. This is public only to allow construction of higher-level templated
505  // utilities.
506  //
507  // is_arena_constructable<T>::value is true if the message type T has arena
508  // support enabled, and false otherwise.
509  //
510  // is_destructor_skippable<T>::value is true if the message type T has told
511  // the arena that it is safe to skip the destructor, and false otherwise.
512  //
513  // This is inside Arena because only Arena has the friend relationships
514  // necessary to see the underlying generated code traits.
515  template <typename T>
516  struct is_arena_constructable : InternalHelper<T>::is_arena_constructable {};
517  template <typename T>
518  struct is_destructor_skippable : InternalHelper<T>::is_destructor_skippable {
519  };
520 
521  private:
523 
524  template <typename T>
525  struct has_get_arena : InternalHelper<T>::has_get_arena {};
526 
527  // Constructor solely used by message-owned arena.
529 
530  // Checks whether this arena is message-owned.
531  PROTOBUF_ALWAYS_INLINE bool IsMessageOwned() const {
532  return impl_.IsMessageOwned();
533  }
534 
535  template <typename T, typename... Args>
536  PROTOBUF_NDEBUG_INLINE static T* CreateMessageInternal(Arena* arena,
537  Args&&... args) {
538  static_assert(
540  "CreateMessage can only construct types that are ArenaConstructable");
541  if (arena == NULL) {
542  return new T(nullptr, static_cast<Args&&>(args)...);
543  } else {
544  return arena->DoCreateMessage<T>(static_cast<Args&&>(args)...);
545  }
546  }
547 
548  // This specialization for no arguments is necessary, because its behavior is
549  // slightly different. When the arena pointer is nullptr, it calls T()
550  // instead of T(nullptr).
551  template <typename T>
552  PROTOBUF_NDEBUG_INLINE static T* CreateMessageInternal(Arena* arena) {
553  static_assert(
555  "CreateMessage can only construct types that are ArenaConstructable");
556  if (arena == NULL) {
557  // Generated arena constructor T(Arena*) is protected. Call via
558  // InternalHelper.
559  return InternalHelper<T>::New();
560  } else {
561  return arena->DoCreateMessage<T>();
562  }
563  }
564 
565  // Allocate and also optionally call collector with the allocated type info
566  // when allocation recording is enabled.
567  PROTOBUF_NDEBUG_INLINE void* AllocateInternal(size_t size, size_t align,
568  void (*destructor)(void*),
569  const std::type_info* type) {
570  // Monitor allocation if needed.
571  if (destructor == nullptr) {
572  return AllocateAlignedWithHook(size, align, type);
573  } else {
574  if (align <= 8) {
575  auto res = AllocateAlignedWithCleanup(internal::AlignUpTo8(size), type);
576  res.second->elem = res.first;
577  res.second->cleanup = destructor;
578  return res.first;
579  } else {
580  auto res = AllocateAlignedWithCleanup(size + align - 8, type);
581  auto ptr = internal::AlignTo(res.first, align);
582  res.second->elem = ptr;
583  res.second->cleanup = destructor;
584  return ptr;
585  }
586  }
587  }
588 
589  // CreateMessage<T> requires that T supports arenas, but this private method
590  // works whether or not T supports arenas. These are not exposed to user code
591  // as it can cause confusing API usages, and end up having double free in
592  // user code. These are used only internally from LazyField and Repeated
593  // fields, since they are designed to work in all mode combinations.
594  template <typename Msg, typename... Args>
595  PROTOBUF_ALWAYS_INLINE static Msg* DoCreateMaybeMessage(Arena* arena,
597  Args&&... args) {
598  return CreateMessageInternal<Msg>(arena, std::forward<Args>(args)...);
599  }
600 
601  template <typename T, typename... Args>
602  PROTOBUF_ALWAYS_INLINE static T* DoCreateMaybeMessage(Arena* arena,
604  Args&&... args) {
605  return Create<T>(arena, std::forward<Args>(args)...);
606  }
607 
608  template <typename T, typename... Args>
609  PROTOBUF_ALWAYS_INLINE static T* CreateMaybeMessage(Arena* arena,
610  Args&&... args) {
611  return DoCreateMaybeMessage<T>(arena, is_arena_constructable<T>(),
612  std::forward<Args>(args)...);
613  }
614 
615  // Just allocate the required size for the given type assuming the
616  // type has a trivial constructor.
617  template <typename T>
618  PROTOBUF_NDEBUG_INLINE T* CreateInternalRawArray(size_t num_elements) {
620  << "Requested size is too large to fit into size_t.";
621  // We count on compiler to realize that if sizeof(T) is a multiple of
622  // 8 AlignUpTo can be elided.
623  const size_t n = sizeof(T) * num_elements;
624  return static_cast<T*>(
625  AllocateAlignedWithHook(n, alignof(T), RTTI_TYPE_ID(T)));
626  }
627 
628  template <typename T, typename... Args>
629  PROTOBUF_NDEBUG_INLINE T* DoCreateMessage(Args&&... args) {
631  AllocateInternal(sizeof(T), alignof(T),
634  T>::destructor,
635  RTTI_TYPE_ID(T)),
636  this, std::forward<Args>(args)...);
637  }
638 
639  // CreateInArenaStorage is used to implement map field. Without it,
640  // Map need to call generated message's protected arena constructor,
641  // which needs to declare Map as friend of generated message.
642  template <typename T, typename... Args>
643  static void CreateInArenaStorage(T* ptr, Arena* arena, Args&&... args) {
644  CreateInArenaStorageInternal(ptr, arena,
646  std::forward<Args>(args)...);
647  if (arena != nullptr) {
648  RegisterDestructorInternal(
649  ptr, arena,
651  }
652  }
653 
654  template <typename T, typename... Args>
655  static void CreateInArenaStorageInternal(T* ptr, Arena* arena,
656  std::true_type, Args&&... args) {
657  InternalHelper<T>::Construct(ptr, arena, std::forward<Args>(args)...);
658  }
659  template <typename T, typename... Args>
660  static void CreateInArenaStorageInternal(T* ptr, Arena* /* arena */,
661  std::false_type, Args&&... args) {
662  new (ptr) T(std::forward<Args>(args)...);
663  }
664 
665  template <typename T>
666  static void RegisterDestructorInternal(T* /* ptr */, Arena* /* arena */,
667  std::true_type) {}
668  template <typename T>
669  static void RegisterDestructorInternal(T* ptr, Arena* arena,
670  std::false_type) {
671  arena->OwnDestructor(ptr);
672  }
673 
674  // These implement Create(). The second parameter has type 'true_type' if T is
675  // a subtype of Message and 'false_type' otherwise.
676  template <typename T, typename... Args>
677  PROTOBUF_ALWAYS_INLINE static T* CreateInternal(Arena* arena, std::true_type,
678  Args&&... args) {
679  if (arena == nullptr) {
680  return new T(std::forward<Args>(args)...);
681  } else {
682  auto destructor =
684  T>::destructor;
685  T* result =
686  new (arena->AllocateInternal(sizeof(T), alignof(T), destructor,
687  RTTI_TYPE_ID(T)))
688  T(std::forward<Args>(args)...);
689  return result;
690  }
691  }
692  template <typename T, typename... Args>
693  PROTOBUF_ALWAYS_INLINE static T* CreateInternal(Arena* arena, std::false_type,
694  Args&&... args) {
695  if (arena == nullptr) {
696  return new T(std::forward<Args>(args)...);
697  } else {
698  auto destructor =
700  T>::destructor;
701  return new (arena->AllocateInternal(sizeof(T), alignof(T), destructor,
702  RTTI_TYPE_ID(T)))
703  T(std::forward<Args>(args)...);
704  }
705  }
706 
707  // These implement Own(), which registers an object for deletion (destructor
708  // call and operator delete()). The second parameter has type 'true_type' if T
709  // is a subtype of Message and 'false_type' otherwise. Collapsing
710  // all template instantiations to one for generic Message reduces code size,
711  // using the virtual destructor instead.
712  template <typename T>
713  PROTOBUF_ALWAYS_INLINE void OwnInternal(T* object, std::true_type) {
714  if (object != NULL) {
715  impl_.AddCleanup(object, &internal::arena_delete_object<MessageLite>);
716  }
717  }
718  template <typename T>
719  PROTOBUF_ALWAYS_INLINE void OwnInternal(T* object, std::false_type) {
720  if (object != NULL) {
721  impl_.AddCleanup(object, &internal::arena_delete_object<T>);
722  }
723  }
724 
725  // Implementation for GetArena(). Only message objects with
726  // InternalArenaConstructable_ tags can be associated with an arena, and such
727  // objects must implement a GetArena() method.
728  template <typename T, typename std::enable_if<
730  PROTOBUF_ALWAYS_INLINE static Arena* GetArenaInternal(const T* value) {
732  }
733  template <typename T,
736  int>::type = 0>
737  PROTOBUF_ALWAYS_INLINE static Arena* GetArenaInternal(const T* value) {
738  return value->GetArena();
739  }
740  template <typename T,
743  int>::type = 0>
744  PROTOBUF_ALWAYS_INLINE static Arena* GetArenaInternal(const T* value) {
745  (void)value;
746  return nullptr;
747  }
748 
749  template <typename T>
750  PROTOBUF_ALWAYS_INLINE static Arena* GetOwningArena(const T* value) {
751  return GetOwningArenaInternal(
752  value, std::is_convertible<T*, MessageLite*>());
753  }
754 
755  // Implementation for GetOwningArena(). All and only message objects have
756  // GetOwningArena() method.
757  template <typename T>
758  PROTOBUF_ALWAYS_INLINE static Arena* GetOwningArenaInternal(
759  const T* value, std::true_type) {
760  return InternalHelper<T>::GetOwningArena(value);
761  }
762  template <typename T>
763  PROTOBUF_ALWAYS_INLINE static Arena* GetOwningArenaInternal(
764  const T* /* value */, std::false_type) {
765  return nullptr;
766  }
767 
768  // For friends of arena.
769  void* AllocateAligned(size_t n, size_t align = 8) {
770  if (align <= 8) {
771  return AllocateAlignedNoHook(internal::AlignUpTo8(n));
772  } else {
773  // We are wasting space by over allocating align - 8 bytes. Compared
774  // to a dedicated function that takes current alignment in consideration.
775  // Such a scheme would only waste (align - 8)/2 bytes on average, but
776  // requires a dedicated function in the outline arena allocation
777  // functions. Possibly re-evaluate tradeoffs later.
778  return internal::AlignTo(AllocateAlignedNoHook(n + align - 8), align);
779  }
780  }
781 
782  void* AllocateAlignedWithHook(size_t n, size_t align,
783  const std::type_info* type) {
784  if (align <= 8) {
785  return AllocateAlignedWithHook(internal::AlignUpTo8(n), type);
786  } else {
787  // We are wasting space by over allocating align - 8 bytes. Compared
788  // to a dedicated function that takes current alignment in consideration.
789  // Such a schemee would only waste (align - 8)/2 bytes on average, but
790  // requires a dedicated function in the outline arena allocation
791  // functions. Possibly re-evaluate tradeoffs later.
792  return internal::AlignTo(AllocateAlignedWithHook(n + align - 8, type),
793  align);
794  }
795  }
796 
797  void* AllocateAlignedNoHook(size_t n);
798  void* AllocateAlignedWithHook(size_t n, const std::type_info* type);
799  std::pair<void*, internal::SerialArena::CleanupNode*>
800  AllocateAlignedWithCleanup(size_t n, const std::type_info* type);
801 
802  template <typename Type>
803  friend class internal::GenericTypeHandler;
804  friend struct internal::ArenaStringPtr; // For AllocateAligned.
805  friend class internal::InlinedStringField; // For AllocateAligned.
806  friend class internal::LazyField; // For CreateMaybeMessage.
807  friend class internal::EpsCopyInputStream; // For parser performance
808  friend class MessageLite;
809  template <typename Key, typename T>
810  friend class Map;
811 };
812 
813 // Defined above for supporting environments without RTTI.
814 #undef RTTI_TYPE_ID
815 
816 } // namespace protobuf
817 } // namespace google
818 
819 #include <google/protobuf/port_undef.inc>
820 
821 #endif // GOOGLE_PROTOBUF_ARENA_H__
ptr
char * ptr
Definition: abseil-cpp/absl/base/internal/low_level_alloc_test.cc:45
_gevent_test_main.result
result
Definition: _gevent_test_main.py:96
google::protobuf::ArenaOptions::ArenaOptions
ArenaOptions()
Definition: third_party/protobuf/src/google/protobuf/arena.h:155
google::protobuf.internal::EpsCopyInputStream
Definition: bloaty/third_party/protobuf/src/google/protobuf/parse_context.h:107
Arena
struct Arena Arena
Definition: third_party/bloaty/third_party/protobuf/src/google/protobuf/arena.h:189
google::protobuf.internal::GetArena
Arena * GetArena(MessageLite *msg, int64 arena_offset)
Definition: bloaty/third_party/protobuf/src/google/protobuf/generated_message_table_driven_lite.h:86
google::protobuf::value
const Descriptor::ReservedRange value
Definition: bloaty/third_party/protobuf/src/google/protobuf/descriptor.h:1954
google::protobuf::ArenaOptions::MetricsCollector
internal::ArenaMetricsCollector * MetricsCollector() const
Definition: third_party/protobuf/src/google/protobuf/arena.h:170
google::protobuf.internal::ThreadSafeArena
Definition: protobuf/src/google/protobuf/arena_impl.h:344
bool
bool
Definition: setup_once.h:312
Map
Definition: bloaty/third_party/protobuf/ruby/ext/google/protobuf_c/protobuf.h:451
google::protobuf.internal::AllocationPolicy::block_alloc
void *(* block_alloc)(size_t)
Definition: protobuf/src/google/protobuf/arena_impl.h:100
google::protobuf.internal::AllocationPolicy::block_dealloc
void(* block_dealloc)(void *, size_t)
Definition: protobuf/src/google/protobuf/arena_impl.h:101
google::protobuf.internal::AllocationPolicy::start_block_size
size_t start_block_size
Definition: protobuf/src/google/protobuf/arena_impl.h:98
options
double_dict options[]
Definition: capstone_test.c:55
google::protobuf.internal::true_type
integral_constant< bool, true > true_type
Definition: bloaty/third_party/protobuf/src/google/protobuf/stubs/template_util.h:89
google::protobuf.internal::false_type
integral_constant< bool, false > false_type
Definition: bloaty/third_party/protobuf/src/google/protobuf/stubs/template_util.h:90
Arena
Definition: arena.c:39
google::protobuf.internal::AlignUpTo8
size_t AlignUpTo8(size_t n)
Definition: bloaty/third_party/protobuf/src/google/protobuf/arena_impl.h:53
google::protobuf.internal::ObjectDestructor
Definition: third_party/protobuf/src/google/protobuf/arena.h:107
New
T * New(Args &&... args)
Definition: third_party/boringssl-with-bazel/src/ssl/internal.h:195
google::protobuf
Definition: bloaty/third_party/protobuf/benchmarks/util/data_proto2_to_proto3_util.h:12
google::protobuf.internal::ThreadSafeArena::kSerialArenaSize
static constexpr size_t kSerialArenaSize
Definition: protobuf/src/google/protobuf/arena_impl.h:548
google::protobuf::python::cmessage::Init
static int Init(CMessage *self, PyObject *args, PyObject *kwargs)
Definition: bloaty/third_party/protobuf/python/google/protobuf/pyext/message.cc:1287
num_elements
static size_t num_elements(const uint8_t *in, size_t in_len)
Definition: evp_asn1.c:283
google::protobuf::MessageLite
Definition: bloaty/third_party/protobuf/src/google/protobuf/message_lite.h:184
T
#define T(upbtypeconst, upbtype, ctype, default_value)
google::protobuf::ArenaOptions::start_block_size
size_t start_block_size
Definition: third_party/bloaty/third_party/protobuf/src/google/protobuf/arena.h:120
true
#define true
Definition: setup_once.h:324
arena
grpc_core::ScopedArenaPtr arena
Definition: binder_transport_test.cc:237
google::protobuf.internal::AlignTo
PROTOBUF_ALWAYS_INLINE void * AlignTo(void *ptr, size_t align)
Definition: third_party/protobuf/src/google/protobuf/arena.h:95
asyncio_get_stats.args
args
Definition: asyncio_get_stats.py:40
mox.Reset
def Reset(*args)
Definition: bloaty/third_party/protobuf/python/mox.py:257
hpack_encoder_fixtures::Args
Args({0, 16384})
max
int max
Definition: bloaty/third_party/zlib/examples/enough.c:170
google::protobuf::ArenaOptions::block_dealloc
void(* block_dealloc)(void *, size_t)
Definition: third_party/bloaty/third_party/protobuf/src/google/protobuf/arena.h:146
impl_
std::shared_ptr< ExternalConnectionAcceptorImpl > impl_
Definition: external_connection_acceptor_impl.cc:43
grpc::protobuf::MessageLite
GRPC_CUSTOM_MESSAGELITE MessageLite
Definition: include/grpcpp/impl/codegen/config_protobuf.h:79
google::protobuf::ArenaOptionsTestFriend
Definition: bloaty/third_party/protobuf/src/google/protobuf/arena_unittest.cc:1424
google::protobuf.internal::AllocationPolicy::metrics_collector
ArenaMetricsCollector * metrics_collector
Definition: protobuf/src/google/protobuf/arena_impl.h:102
uint64_t
unsigned __int64 uint64_t
Definition: stdint-msvc2008.h:90
google::protobuf::TestUtil::ReflectionTester
Definition: bloaty/third_party/protobuf/src/google/protobuf/test_util.h:57
uintptr_t
_W64 unsigned int uintptr_t
Definition: stdint-msvc2008.h:119
google::protobuf::ArenaOptions::block_alloc
void *(* block_alloc)(size_t)
Definition: third_party/bloaty/third_party/protobuf/src/google/protobuf/arena.h:142
n
int n
Definition: abseil-cpp/absl/container/btree_test.cc:1080
google::protobuf.internal::AllocationPolicy
Definition: protobuf/src/google/protobuf/arena_impl.h:94
google::protobuf.internal::InlinedStringField
Definition: bloaty/third_party/protobuf/src/google/protobuf/inlined_string_field.h:62
grpc_core::Construct
void Construct(T *p, Args &&... args)
Definition: construct_destruct.h:34
value
const char * value
Definition: hpack_parser_table.cc:165
google::protobuf::ArenaOptions
Definition: third_party/bloaty/third_party/protobuf/src/google/protobuf/arena.h:117
google::protobuf.internal::arena_delete_object
void arena_delete_object(void *object)
Definition: third_party/bloaty/third_party/protobuf/src/google/protobuf/arena.h:101
absl::time_internal::cctz::detail::align
CONSTEXPR_F fields align(second_tag, fields f) noexcept
Definition: abseil-cpp/absl/time/internal/cctz/include/cctz/civil_time_detail.h:325
google::protobuf::ArenaOptions::kDefaultMaxBlockSize
static const size_t kDefaultMaxBlockSize
Definition: third_party/bloaty/third_party/protobuf/src/google/protobuf/arena.h:186
std
Definition: grpcpp/impl/codegen/async_unary_call.h:407
RTTI_TYPE_ID
#define RTTI_TYPE_ID(type)
Definition: third_party/protobuf/src/google/protobuf/arena.h:195
google::protobuf.internal::arena_destruct_object
void arena_destruct_object(void *object)
Definition: third_party/bloaty/third_party/protobuf/src/google/protobuf/arena.h:97
google::protobuf::arena_metrics::EnableArenaMetrics
void EnableArenaMetrics(ArenaOptions *options)
google::protobuf::ArenaOptions::max_block_size
size_t max_block_size
Definition: third_party/bloaty/third_party/protobuf/src/google/protobuf/arena.h:126
google::protobuf::ArenaOptions::initial_block
char * initial_block
Definition: third_party/bloaty/third_party/protobuf/src/google/protobuf/arena.h:132
google::protobuf::ArenaOptions::initial_block_size
size_t initial_block_size
Definition: third_party/bloaty/third_party/protobuf/src/google/protobuf/arena.h:135
google::protobuf::ArenaOptions::make_metrics_collector
internal::ArenaMetricsCollector *(* make_metrics_collector)()
Definition: third_party/protobuf/src/google/protobuf/arena.h:168
google::protobuf.internal::MessageOwned
Definition: protobuf/src/google/protobuf/arena_impl.h:334
google::protobuf::Map
Definition: third_party/bloaty/third_party/protobuf/src/google/protobuf/arena.h:79
internal
Definition: benchmark/test/output_test_helper.cc:20
google::protobuf.internal::ObjectDestructor::destructor
constexpr static void(* destructor)(void *)
Definition: third_party/protobuf/src/google/protobuf/arena.h:108
google::protobuf.internal::GenericTypeHandler
Definition: third_party/bloaty/third_party/protobuf/src/google/protobuf/arena.h:93
google::protobuf.internal::AllocationPolicy::max_block_size
size_t max_block_size
Definition: protobuf/src/google/protobuf/arena_impl.h:99
asyncio_get_stats.type
type
Definition: asyncio_get_stats.py:37
google::protobuf.internal::ThreadSafeArena::kBlockHeaderSize
static constexpr size_t kBlockHeaderSize
Definition: protobuf/src/google/protobuf/arena_impl.h:547
size
voidpf void uLong size
Definition: bloaty/third_party/zlib/contrib/minizip/ioapi.h:136
google::protobuf::ArenaOptions::kDefaultStartBlockSize
static const size_t kDefaultStartBlockSize
Definition: third_party/bloaty/third_party/protobuf/src/google/protobuf/arena.h:185
google::protobuf.internal::ArenaMetricsCollector
Definition: protobuf/src/google/protobuf/arena_impl.h:62
google::protobuf::PROTOBUF_ALIGNAS
class PROTOBUF_EXPORT PROTOBUF_ALIGNAS(8) Arena final
Definition: third_party/protobuf/src/google/protobuf/arena.h:243
google
Definition: bloaty/third_party/protobuf/benchmarks/util/data_proto2_to_proto3_util.h:11
google::protobuf.internal::ArenaStringPtr
Definition: bloaty/third_party/protobuf/src/google/protobuf/arenastring.h:74
GOOGLE_CHECK_LE
#define GOOGLE_CHECK_LE(A, B)
Definition: bloaty/third_party/protobuf/src/google/protobuf/stubs/logging.h:159
google::protobuf::ArenaOptions::AllocationPolicy
internal::AllocationPolicy AllocationPolicy() const
Definition: third_party/protobuf/src/google/protobuf/arena.h:174
Message
Definition: protobuf/php/ext/google/protobuf/message.c:53


grpc
Author(s):
autogenerated on Fri May 16 2025 02:57:42