arena.h 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  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. // This file defines an Arena allocator for better allocation performance.
  31. #ifndef GOOGLE_PROTOBUF_ARENA_H__
  32. #define GOOGLE_PROTOBUF_ARENA_H__
  33. #include <limits>
  34. #include <type_traits>
  35. #include <utility>
  36. #ifdef max
  37. #undef max // Visual Studio defines this macro
  38. #endif
  39. #if defined(_MSC_VER) && !defined(_LIBCPP_STD_VER) && !_HAS_EXCEPTIONS
  40. // Work around bugs in MSVC <typeinfo> header when _HAS_EXCEPTIONS=0.
  41. #include <exception>
  42. #include <typeinfo>
  43. namespace std {
  44. using type_info = ::type_info;
  45. }
  46. #else
  47. #include <typeinfo>
  48. #endif
  49. #include <type_traits>
  50. #include <google/protobuf/arena_impl.h>
  51. #include <google/protobuf/port.h>
  52. #include <google/protobuf/port_def.inc>
  53. #ifdef SWIG
  54. #error "You cannot SWIG proto headers"
  55. #endif
  56. namespace google {
  57. namespace protobuf {
  58. struct ArenaOptions; // defined below
  59. } // namespace protobuf
  60. } // namespace google
  61. namespace google {
  62. namespace protobuf {
  63. class Arena; // defined below
  64. class Message; // defined in message.h
  65. class MessageLite;
  66. template <typename Key, typename T>
  67. class Map;
  68. namespace arena_metrics {
  69. void EnableArenaMetrics(ArenaOptions* options);
  70. } // namespace arena_metrics
  71. namespace TestUtil {
  72. class ReflectionTester; // defined in test_util.h
  73. } // namespace TestUtil
  74. namespace internal {
  75. struct ArenaStringPtr; // defined in arenastring.h
  76. class InlinedStringField; // defined in inlined_string_field.h
  77. class LazyField; // defined in lazy_field.h
  78. class EpsCopyInputStream; // defined in parse_context.h
  79. template <typename Type>
  80. class GenericTypeHandler; // defined in repeated_field.h
  81. inline PROTOBUF_ALWAYS_INLINE
  82. void* AlignTo(void* ptr, size_t align) {
  83. return reinterpret_cast<void*>(
  84. (reinterpret_cast<uintptr_t>(ptr) + align - 1) & (~align + 1));
  85. }
  86. // Templated cleanup methods.
  87. template <typename T>
  88. void arena_destruct_object(void* object) {
  89. reinterpret_cast<T*>(object)->~T();
  90. }
  91. template <bool destructor_skippable, typename T>
  92. struct ObjectDestructor {
  93. constexpr static void (*destructor)(void*) = &arena_destruct_object<T>;
  94. };
  95. template <typename T>
  96. struct ObjectDestructor<true, T> {
  97. constexpr static void (*destructor)(void*) = nullptr;
  98. };
  99. template <typename T>
  100. void arena_delete_object(void* object) {
  101. delete reinterpret_cast<T*>(object);
  102. }
  103. } // namespace internal
  104. // ArenaOptions provides optional additional parameters to arena construction
  105. // that control its block-allocation behavior.
  106. struct ArenaOptions {
  107. // This defines the size of the first block requested from the system malloc.
  108. // Subsequent block sizes will increase in a geometric series up to a maximum.
  109. size_t start_block_size;
  110. // This defines the maximum block size requested from system malloc (unless an
  111. // individual arena allocation request occurs with a size larger than this
  112. // maximum). Requested block sizes increase up to this value, then remain
  113. // here.
  114. size_t max_block_size;
  115. // An initial block of memory for the arena to use, or NULL for none. If
  116. // provided, the block must live at least as long as the arena itself. The
  117. // creator of the Arena retains ownership of the block after the Arena is
  118. // destroyed.
  119. char* initial_block;
  120. // The size of the initial block, if provided.
  121. size_t initial_block_size;
  122. // A function pointer to an alloc method that returns memory blocks of size
  123. // requested. By default, it contains a ptr to the malloc function.
  124. //
  125. // NOTE: block_alloc and dealloc functions are expected to behave like
  126. // malloc and free, including Asan poisoning.
  127. void* (*block_alloc)(size_t);
  128. // A function pointer to a dealloc method that takes ownership of the blocks
  129. // from the arena. By default, it contains a ptr to a wrapper function that
  130. // calls free.
  131. void (*block_dealloc)(void*, size_t);
  132. ArenaOptions()
  133. : start_block_size(internal::AllocationPolicy::kDefaultStartBlockSize),
  134. max_block_size(internal::AllocationPolicy::kDefaultMaxBlockSize),
  135. initial_block(NULL),
  136. initial_block_size(0),
  137. block_alloc(nullptr),
  138. block_dealloc(nullptr),
  139. make_metrics_collector(nullptr) {}
  140. private:
  141. // If make_metrics_collector is not nullptr, it will be called at Arena init
  142. // time. It may return a pointer to a collector instance that will be notified
  143. // of interesting events related to the arena.
  144. internal::ArenaMetricsCollector* (*make_metrics_collector)();
  145. internal::ArenaMetricsCollector* MetricsCollector() const {
  146. return make_metrics_collector ? (*make_metrics_collector)() : nullptr;
  147. }
  148. internal::AllocationPolicy AllocationPolicy() const {
  149. internal::AllocationPolicy res;
  150. res.start_block_size = start_block_size;
  151. res.max_block_size = max_block_size;
  152. res.block_alloc = block_alloc;
  153. res.block_dealloc = block_dealloc;
  154. res.metrics_collector = MetricsCollector();
  155. return res;
  156. }
  157. friend void arena_metrics::EnableArenaMetrics(ArenaOptions*);
  158. friend class Arena;
  159. friend class ArenaOptionsTestFriend;
  160. };
  161. // Support for non-RTTI environments. (The metrics hooks API uses type
  162. // information.)
  163. #if PROTOBUF_RTTI
  164. #define RTTI_TYPE_ID(type) (&typeid(type))
  165. #else
  166. #define RTTI_TYPE_ID(type) (NULL)
  167. #endif
  168. // Arena allocator. Arena allocation replaces ordinary (heap-based) allocation
  169. // with new/delete, and improves performance by aggregating allocations into
  170. // larger blocks and freeing allocations all at once. Protocol messages are
  171. // allocated on an arena by using Arena::CreateMessage<T>(Arena*), below, and
  172. // are automatically freed when the arena is destroyed.
  173. //
  174. // This is a thread-safe implementation: multiple threads may allocate from the
  175. // arena concurrently. Destruction is not thread-safe and the destructing
  176. // thread must synchronize with users of the arena first.
  177. //
  178. // An arena provides two allocation interfaces: CreateMessage<T>, which works
  179. // for arena-enabled proto2 message types as well as other types that satisfy
  180. // the appropriate protocol (described below), and Create<T>, which works for
  181. // any arbitrary type T. CreateMessage<T> is better when the type T supports it,
  182. // because this interface (i) passes the arena pointer to the created object so
  183. // that its sub-objects and internal allocations can use the arena too, and (ii)
  184. // elides the object's destructor call when possible. Create<T> does not place
  185. // any special requirements on the type T, and will invoke the object's
  186. // destructor when the arena is destroyed.
  187. //
  188. // The arena message allocation protocol, required by
  189. // CreateMessage<T>(Arena* arena, Args&&... args), is as follows:
  190. //
  191. // - The type T must have (at least) two constructors: a constructor callable
  192. // with `args` (without `arena`), called when a T is allocated on the heap;
  193. // and a constructor callable with `Arena* arena, Args&&... args`, called when
  194. // a T is allocated on an arena. If the second constructor is called with a
  195. // NULL arena pointer, it must be equivalent to invoking the first
  196. // (`args`-only) constructor.
  197. //
  198. // - The type T must have a particular type trait: a nested type
  199. // |InternalArenaConstructable_|. This is usually a typedef to |void|. If no
  200. // such type trait exists, then the instantiation CreateMessage<T> will fail
  201. // to compile.
  202. //
  203. // - The type T *may* have the type trait |DestructorSkippable_|. If this type
  204. // trait is present in the type, then its destructor will not be called if and
  205. // only if it was passed a non-NULL arena pointer. If this type trait is not
  206. // present on the type, then its destructor is always called when the
  207. // containing arena is destroyed.
  208. //
  209. // This protocol is implemented by all arena-enabled proto2 message classes as
  210. // well as protobuf container types like RepeatedPtrField and Map. The protocol
  211. // is internal to protobuf and is not guaranteed to be stable. Non-proto types
  212. // should not rely on this protocol.
  213. class PROTOBUF_EXPORT PROTOBUF_ALIGNAS(8) Arena final {
  214. public:
  215. // Default constructor with sensible default options, tuned for average
  216. // use-cases.
  217. inline Arena() : impl_() {}
  218. // Construct an arena with default options, except for the supplied
  219. // initial block. It is more efficient to use this constructor
  220. // instead of passing ArenaOptions if the only configuration needed
  221. // by the caller is supplying an initial block.
  222. inline Arena(char* initial_block, size_t initial_block_size)
  223. : impl_(initial_block, initial_block_size) {}
  224. // Arena constructor taking custom options. See ArenaOptions above for
  225. // descriptions of the options available.
  226. explicit Arena(const ArenaOptions& options)
  227. : impl_(options.initial_block, options.initial_block_size,
  228. options.AllocationPolicy()) {}
  229. // Block overhead. Use this as a guide for how much to over-allocate the
  230. // initial block if you want an allocation of size N to fit inside it.
  231. //
  232. // WARNING: if you allocate multiple objects, it is difficult to guarantee
  233. // that a series of allocations will fit in the initial block, especially if
  234. // Arena changes its alignment guarantees in the future!
  235. static const size_t kBlockOverhead =
  236. internal::ThreadSafeArena::kBlockHeaderSize +
  237. internal::ThreadSafeArena::kSerialArenaSize;
  238. inline ~Arena() {}
  239. // TODO(protobuf-team): Fix callers to use constructor and delete this method.
  240. void Init(const ArenaOptions&) {}
  241. // API to create proto2 message objects on the arena. If the arena passed in
  242. // is NULL, then a heap allocated object is returned. Type T must be a message
  243. // defined in a .proto file with cc_enable_arenas set to true, otherwise a
  244. // compilation error will occur.
  245. //
  246. // RepeatedField and RepeatedPtrField may also be instantiated directly on an
  247. // arena with this method.
  248. //
  249. // This function also accepts any type T that satisfies the arena message
  250. // allocation protocol, documented above.
  251. template <typename T, typename... Args>
  252. PROTOBUF_ALWAYS_INLINE static T* CreateMessage(Arena* arena, Args&&... args) {
  253. static_assert(
  254. InternalHelper<T>::is_arena_constructable::value,
  255. "CreateMessage can only construct types that are ArenaConstructable");
  256. // We must delegate to CreateMaybeMessage() and NOT CreateMessageInternal()
  257. // because protobuf generated classes specialize CreateMaybeMessage() and we
  258. // need to use that specialization for code size reasons.
  259. return Arena::CreateMaybeMessage<T>(arena, static_cast<Args&&>(args)...);
  260. }
  261. // API to create any objects on the arena. Note that only the object will
  262. // be created on the arena; the underlying ptrs (in case of a proto2 message)
  263. // will be still heap allocated. Proto messages should usually be allocated
  264. // with CreateMessage<T>() instead.
  265. //
  266. // Note that even if T satisfies the arena message construction protocol
  267. // (InternalArenaConstructable_ trait and optional DestructorSkippable_
  268. // trait), as described above, this function does not follow the protocol;
  269. // instead, it treats T as a black-box type, just as if it did not have these
  270. // traits. Specifically, T's constructor arguments will always be only those
  271. // passed to Create<T>() -- no additional arena pointer is implicitly added.
  272. // Furthermore, the destructor will always be called at arena destruction time
  273. // (unless the destructor is trivial). Hence, from T's point of view, it is as
  274. // if the object were allocated on the heap (except that the underlying memory
  275. // is obtained from the arena).
  276. template <typename T, typename... Args>
  277. PROTOBUF_NDEBUG_INLINE static T* Create(Arena* arena, Args&&... args) {
  278. return CreateInternal<T>(arena, std::is_convertible<T*, MessageLite*>(),
  279. static_cast<Args&&>(args)...);
  280. }
  281. // Create an array of object type T on the arena *without* invoking the
  282. // constructor of T. If `arena` is null, then the return value should be freed
  283. // with `delete[] x;` (or `::operator delete[](x);`).
  284. // To ensure safe uses, this function checks at compile time
  285. // (when compiled as C++11) that T is trivially default-constructible and
  286. // trivially destructible.
  287. template <typename T>
  288. PROTOBUF_NDEBUG_INLINE static T* CreateArray(Arena* arena,
  289. size_t num_elements) {
  290. static_assert(std::is_trivial<T>::value,
  291. "CreateArray requires a trivially constructible type");
  292. static_assert(std::is_trivially_destructible<T>::value,
  293. "CreateArray requires a trivially destructible type");
  294. GOOGLE_CHECK_LE(num_elements, std::numeric_limits<size_t>::max() / sizeof(T))
  295. << "Requested size is too large to fit into size_t.";
  296. if (arena == NULL) {
  297. return static_cast<T*>(::operator new[](num_elements * sizeof(T)));
  298. } else {
  299. return arena->CreateInternalRawArray<T>(num_elements);
  300. }
  301. }
  302. // The following are routines are for monitoring. They will approximate the
  303. // total sum allocated and used memory, but the exact value is an
  304. // implementation deal. For instance allocated space depends on growth
  305. // policies. Do not use these in unit tests.
  306. // Returns the total space allocated by the arena, which is the sum of the
  307. // sizes of the underlying blocks.
  308. uint64_t SpaceAllocated() const { return impl_.SpaceAllocated(); }
  309. // Returns the total space used by the arena. Similar to SpaceAllocated but
  310. // does not include free space and block overhead. The total space returned
  311. // may not include space used by other threads executing concurrently with
  312. // the call to this method.
  313. uint64_t SpaceUsed() const { return impl_.SpaceUsed(); }
  314. // Frees all storage allocated by this arena after calling destructors
  315. // registered with OwnDestructor() and freeing objects registered with Own().
  316. // Any objects allocated on this arena are unusable after this call. It also
  317. // returns the total space used by the arena which is the sums of the sizes
  318. // of the allocated blocks. This method is not thread-safe.
  319. uint64_t Reset() { return impl_.Reset(); }
  320. // Adds |object| to a list of heap-allocated objects to be freed with |delete|
  321. // when the arena is destroyed or reset.
  322. template <typename T>
  323. PROTOBUF_ALWAYS_INLINE void Own(T* object) {
  324. OwnInternal(object, std::is_convertible<T*, MessageLite*>());
  325. }
  326. // Adds |object| to a list of objects whose destructors will be manually
  327. // called when the arena is destroyed or reset. This differs from Own() in
  328. // that it does not free the underlying memory with |delete|; hence, it is
  329. // normally only used for objects that are placement-newed into
  330. // arena-allocated memory.
  331. template <typename T>
  332. PROTOBUF_ALWAYS_INLINE void OwnDestructor(T* object) {
  333. if (object != NULL) {
  334. impl_.AddCleanup(object, &internal::arena_destruct_object<T>);
  335. }
  336. }
  337. // Adds a custom member function on an object to the list of destructors that
  338. // will be manually called when the arena is destroyed or reset. This differs
  339. // from OwnDestructor() in that any member function may be specified, not only
  340. // the class destructor.
  341. PROTOBUF_ALWAYS_INLINE void OwnCustomDestructor(void* object,
  342. void (*destruct)(void*)) {
  343. impl_.AddCleanup(object, destruct);
  344. }
  345. // Retrieves the arena associated with |value| if |value| is an arena-capable
  346. // message, or NULL otherwise. If possible, the call resolves at compile time.
  347. // Note that we can often devirtualize calls to `value->GetArena()` so usually
  348. // calling this method is unnecessary.
  349. template <typename T>
  350. PROTOBUF_ALWAYS_INLINE static Arena* GetArena(const T* value) {
  351. return GetArenaInternal(value);
  352. }
  353. template <typename T>
  354. class InternalHelper {
  355. public:
  356. // Provides access to protected GetOwningArena to generated messages.
  357. static Arena* GetOwningArena(const T* p) { return p->GetOwningArena(); }
  358. // Provides access to protected GetArenaForAllocation to generated messages.
  359. static Arena* GetArenaForAllocation(const T* p) {
  360. return GetArenaForAllocationInternal(
  361. p, std::is_convertible<T*, MessageLite*>());
  362. }
  363. private:
  364. static Arena* GetArenaForAllocationInternal(
  365. const T* p, std::true_type /*is_derived_from<MessageLite>*/) {
  366. return p->GetArenaForAllocation();
  367. }
  368. static Arena* GetArenaForAllocationInternal(
  369. const T* p, std::false_type /*is_derived_from<MessageLite>*/) {
  370. return GetArenaForAllocationForNonMessage(
  371. p, typename is_arena_constructable::type());
  372. }
  373. static Arena* GetArenaForAllocationForNonMessage(
  374. const T* p, std::true_type /*is_arena_constructible*/) {
  375. return p->GetArena();
  376. }
  377. static Arena* GetArenaForAllocationForNonMessage(
  378. const T* p, std::false_type /*is_arena_constructible*/) {
  379. return GetArenaForAllocationForNonMessageNonArenaConstructible(
  380. p, typename has_get_arena::type());
  381. }
  382. static Arena* GetArenaForAllocationForNonMessageNonArenaConstructible(
  383. const T* p, std::true_type /*has_get_arena*/) {
  384. return p->GetArena();
  385. }
  386. static Arena* GetArenaForAllocationForNonMessageNonArenaConstructible(
  387. const T* /* p */, std::false_type /*has_get_arena*/) {
  388. return nullptr;
  389. }
  390. template <typename U>
  391. static char DestructorSkippable(const typename U::DestructorSkippable_*);
  392. template <typename U>
  393. static double DestructorSkippable(...);
  394. typedef std::integral_constant<
  395. bool, sizeof(DestructorSkippable<T>(static_cast<const T*>(0))) ==
  396. sizeof(char) ||
  397. std::is_trivially_destructible<T>::value>
  398. is_destructor_skippable;
  399. template <typename U>
  400. static char ArenaConstructable(
  401. const typename U::InternalArenaConstructable_*);
  402. template <typename U>
  403. static double ArenaConstructable(...);
  404. typedef std::integral_constant<bool, sizeof(ArenaConstructable<T>(
  405. static_cast<const T*>(0))) ==
  406. sizeof(char)>
  407. is_arena_constructable;
  408. template <typename U,
  409. typename std::enable_if<
  410. std::is_same<Arena*, decltype(std::declval<const U>()
  411. .GetArena())>::value,
  412. int>::type = 0>
  413. static char HasGetArena(decltype(&U::GetArena));
  414. template <typename U>
  415. static double HasGetArena(...);
  416. typedef std::integral_constant<bool, sizeof(HasGetArena<T>(nullptr)) ==
  417. sizeof(char)>
  418. has_get_arena;
  419. template <typename... Args>
  420. static T* Construct(void* ptr, Args&&... args) {
  421. return new (ptr) T(static_cast<Args&&>(args)...);
  422. }
  423. static T* New() {
  424. return new T(nullptr);
  425. }
  426. static Arena* GetArena(const T* p) { return p->GetArena(); }
  427. friend class Arena;
  428. friend class TestUtil::ReflectionTester;
  429. };
  430. // Helper typetraits that indicates support for arenas in a type T at compile
  431. // time. This is public only to allow construction of higher-level templated
  432. // utilities.
  433. //
  434. // is_arena_constructable<T>::value is true if the message type T has arena
  435. // support enabled, and false otherwise.
  436. //
  437. // is_destructor_skippable<T>::value is true if the message type T has told
  438. // the arena that it is safe to skip the destructor, and false otherwise.
  439. //
  440. // This is inside Arena because only Arena has the friend relationships
  441. // necessary to see the underlying generated code traits.
  442. template <typename T>
  443. struct is_arena_constructable : InternalHelper<T>::is_arena_constructable {};
  444. template <typename T>
  445. struct is_destructor_skippable : InternalHelper<T>::is_destructor_skippable {
  446. };
  447. private:
  448. internal::ThreadSafeArena impl_;
  449. template <typename T>
  450. struct has_get_arena : InternalHelper<T>::has_get_arena {};
  451. template <typename T, typename... Args>
  452. PROTOBUF_NDEBUG_INLINE static T* CreateMessageInternal(Arena* arena,
  453. Args&&... args) {
  454. static_assert(
  455. InternalHelper<T>::is_arena_constructable::value,
  456. "CreateMessage can only construct types that are ArenaConstructable");
  457. if (arena == NULL) {
  458. return new T(nullptr, static_cast<Args&&>(args)...);
  459. } else {
  460. return arena->DoCreateMessage<T>(static_cast<Args&&>(args)...);
  461. }
  462. }
  463. // This specialization for no arguments is necessary, because its behavior is
  464. // slightly different. When the arena pointer is nullptr, it calls T()
  465. // instead of T(nullptr).
  466. template <typename T>
  467. PROTOBUF_NDEBUG_INLINE static T* CreateMessageInternal(Arena* arena) {
  468. static_assert(
  469. InternalHelper<T>::is_arena_constructable::value,
  470. "CreateMessage can only construct types that are ArenaConstructable");
  471. if (arena == NULL) {
  472. // Generated arena constructor T(Arena*) is protected. Call via
  473. // InternalHelper.
  474. return InternalHelper<T>::New();
  475. } else {
  476. return arena->DoCreateMessage<T>();
  477. }
  478. }
  479. // Allocate and also optionally call collector with the allocated type info
  480. // when allocation recording is enabled.
  481. PROTOBUF_NDEBUG_INLINE void* AllocateInternal(size_t size, size_t align,
  482. void (*destructor)(void*),
  483. const std::type_info* type) {
  484. // Monitor allocation if needed.
  485. if (destructor == nullptr) {
  486. return AllocateAlignedWithHook(size, align, type);
  487. } else {
  488. if (align <= 8) {
  489. auto res = AllocateAlignedWithCleanup(internal::AlignUpTo8(size), type);
  490. res.second->elem = res.first;
  491. res.second->cleanup = destructor;
  492. return res.first;
  493. } else {
  494. auto res = AllocateAlignedWithCleanup(size + align - 8, type);
  495. auto ptr = internal::AlignTo(res.first, align);
  496. res.second->elem = ptr;
  497. res.second->cleanup = destructor;
  498. return ptr;
  499. }
  500. }
  501. }
  502. // CreateMessage<T> requires that T supports arenas, but this private method
  503. // works whether or not T supports arenas. These are not exposed to user code
  504. // as it can cause confusing API usages, and end up having double free in
  505. // user code. These are used only internally from LazyField and Repeated
  506. // fields, since they are designed to work in all mode combinations.
  507. template <typename Msg, typename... Args>
  508. PROTOBUF_ALWAYS_INLINE static Msg* DoCreateMaybeMessage(Arena* arena,
  509. std::true_type,
  510. Args&&... args) {
  511. return CreateMessageInternal<Msg>(arena, std::forward<Args>(args)...);
  512. }
  513. template <typename T, typename... Args>
  514. PROTOBUF_ALWAYS_INLINE static T* DoCreateMaybeMessage(Arena* arena,
  515. std::false_type,
  516. Args&&... args) {
  517. return Create<T>(arena, std::forward<Args>(args)...);
  518. }
  519. template <typename T, typename... Args>
  520. PROTOBUF_ALWAYS_INLINE static T* CreateMaybeMessage(Arena* arena,
  521. Args&&... args) {
  522. return DoCreateMaybeMessage<T>(arena, is_arena_constructable<T>(),
  523. std::forward<Args>(args)...);
  524. }
  525. // Just allocate the required size for the given type assuming the
  526. // type has a trivial constructor.
  527. template <typename T>
  528. PROTOBUF_NDEBUG_INLINE T* CreateInternalRawArray(size_t num_elements) {
  529. GOOGLE_CHECK_LE(num_elements, std::numeric_limits<size_t>::max() / sizeof(T))
  530. << "Requested size is too large to fit into size_t.";
  531. // We count on compiler to realize that if sizeof(T) is a multiple of
  532. // 8 AlignUpTo can be elided.
  533. const size_t n = sizeof(T) * num_elements;
  534. return static_cast<T*>(
  535. AllocateAlignedWithHook(n, alignof(T), RTTI_TYPE_ID(T)));
  536. }
  537. template <typename T, typename... Args>
  538. PROTOBUF_NDEBUG_INLINE T* DoCreateMessage(Args&&... args) {
  539. return InternalHelper<T>::Construct(
  540. AllocateInternal(sizeof(T), alignof(T),
  541. internal::ObjectDestructor<
  542. InternalHelper<T>::is_destructor_skippable::value,
  543. T>::destructor,
  544. RTTI_TYPE_ID(T)),
  545. this, std::forward<Args>(args)...);
  546. }
  547. // CreateInArenaStorage is used to implement map field. Without it,
  548. // Map need to call generated message's protected arena constructor,
  549. // which needs to declare Map as friend of generated message.
  550. template <typename T, typename... Args>
  551. static void CreateInArenaStorage(T* ptr, Arena* arena, Args&&... args) {
  552. CreateInArenaStorageInternal(ptr, arena,
  553. typename is_arena_constructable<T>::type(),
  554. std::forward<Args>(args)...);
  555. if (arena != nullptr) {
  556. RegisterDestructorInternal(
  557. ptr, arena,
  558. typename InternalHelper<T>::is_destructor_skippable::type());
  559. }
  560. }
  561. template <typename T, typename... Args>
  562. static void CreateInArenaStorageInternal(T* ptr, Arena* arena,
  563. std::true_type, Args&&... args) {
  564. InternalHelper<T>::Construct(ptr, arena, std::forward<Args>(args)...);
  565. }
  566. template <typename T, typename... Args>
  567. static void CreateInArenaStorageInternal(T* ptr, Arena* /* arena */,
  568. std::false_type, Args&&... args) {
  569. new (ptr) T(std::forward<Args>(args)...);
  570. }
  571. template <typename T>
  572. static void RegisterDestructorInternal(T* /* ptr */, Arena* /* arena */,
  573. std::true_type) {}
  574. template <typename T>
  575. static void RegisterDestructorInternal(T* ptr, Arena* arena,
  576. std::false_type) {
  577. arena->OwnDestructor(ptr);
  578. }
  579. // These implement Create(). The second parameter has type 'true_type' if T is
  580. // a subtype of Message and 'false_type' otherwise.
  581. template <typename T, typename... Args>
  582. PROTOBUF_ALWAYS_INLINE static T* CreateInternal(Arena* arena, std::true_type,
  583. Args&&... args) {
  584. if (arena == nullptr) {
  585. return new T(std::forward<Args>(args)...);
  586. } else {
  587. auto destructor =
  588. internal::ObjectDestructor<std::is_trivially_destructible<T>::value,
  589. T>::destructor;
  590. T* result =
  591. new (arena->AllocateInternal(sizeof(T), alignof(T), destructor,
  592. RTTI_TYPE_ID(T)))
  593. T(std::forward<Args>(args)...);
  594. return result;
  595. }
  596. }
  597. template <typename T, typename... Args>
  598. PROTOBUF_ALWAYS_INLINE static T* CreateInternal(Arena* arena, std::false_type,
  599. Args&&... args) {
  600. if (arena == nullptr) {
  601. return new T(std::forward<Args>(args)...);
  602. } else {
  603. auto destructor =
  604. internal::ObjectDestructor<std::is_trivially_destructible<T>::value,
  605. T>::destructor;
  606. return new (arena->AllocateInternal(sizeof(T), alignof(T), destructor,
  607. RTTI_TYPE_ID(T)))
  608. T(std::forward<Args>(args)...);
  609. }
  610. }
  611. // These implement Own(), which registers an object for deletion (destructor
  612. // call and operator delete()). The second parameter has type 'true_type' if T
  613. // is a subtype of Message and 'false_type' otherwise. Collapsing
  614. // all template instantiations to one for generic Message reduces code size,
  615. // using the virtual destructor instead.
  616. template <typename T>
  617. PROTOBUF_ALWAYS_INLINE void OwnInternal(T* object, std::true_type) {
  618. if (object != NULL) {
  619. impl_.AddCleanup(object, &internal::arena_delete_object<MessageLite>);
  620. }
  621. }
  622. template <typename T>
  623. PROTOBUF_ALWAYS_INLINE void OwnInternal(T* object, std::false_type) {
  624. if (object != NULL) {
  625. impl_.AddCleanup(object, &internal::arena_delete_object<T>);
  626. }
  627. }
  628. // Implementation for GetArena(). Only message objects with
  629. // InternalArenaConstructable_ tags can be associated with an arena, and such
  630. // objects must implement a GetArena() method.
  631. template <typename T, typename std::enable_if<
  632. is_arena_constructable<T>::value, int>::type = 0>
  633. PROTOBUF_ALWAYS_INLINE static Arena* GetArenaInternal(const T* value) {
  634. return InternalHelper<T>::GetArena(value);
  635. }
  636. template <typename T,
  637. typename std::enable_if<!is_arena_constructable<T>::value &&
  638. has_get_arena<T>::value,
  639. int>::type = 0>
  640. PROTOBUF_ALWAYS_INLINE static Arena* GetArenaInternal(const T* value) {
  641. return value->GetArena();
  642. }
  643. template <typename T,
  644. typename std::enable_if<!is_arena_constructable<T>::value &&
  645. !has_get_arena<T>::value,
  646. int>::type = 0>
  647. PROTOBUF_ALWAYS_INLINE static Arena* GetArenaInternal(const T* value) {
  648. (void)value;
  649. return nullptr;
  650. }
  651. template <typename T>
  652. PROTOBUF_ALWAYS_INLINE static Arena* GetOwningArena(const T* value) {
  653. return GetOwningArenaInternal(
  654. value, std::is_convertible<T*, MessageLite*>());
  655. }
  656. // Implementation for GetOwningArena(). All and only message objects have
  657. // GetOwningArena() method.
  658. template <typename T>
  659. PROTOBUF_ALWAYS_INLINE static Arena* GetOwningArenaInternal(
  660. const T* value, std::true_type) {
  661. return InternalHelper<T>::GetOwningArena(value);
  662. }
  663. template <typename T>
  664. PROTOBUF_ALWAYS_INLINE static Arena* GetOwningArenaInternal(
  665. const T* /* value */, std::false_type) {
  666. return nullptr;
  667. }
  668. // For friends of arena.
  669. void* AllocateAligned(size_t n, size_t align = 8) {
  670. if (align <= 8) {
  671. return AllocateAlignedNoHook(internal::AlignUpTo8(n));
  672. } else {
  673. // We are wasting space by over allocating align - 8 bytes. Compared
  674. // to a dedicated function that takes current alignment in consideration.
  675. // Such a scheme would only waste (align - 8)/2 bytes on average, but
  676. // requires a dedicated function in the outline arena allocation
  677. // functions. Possibly re-evaluate tradeoffs later.
  678. return internal::AlignTo(AllocateAlignedNoHook(n + align - 8), align);
  679. }
  680. }
  681. void* AllocateAlignedWithHook(size_t n, size_t align,
  682. const std::type_info* type) {
  683. if (align <= 8) {
  684. return AllocateAlignedWithHook(internal::AlignUpTo8(n), type);
  685. } else {
  686. // We are wasting space by over allocating align - 8 bytes. Compared
  687. // to a dedicated function that takes current alignment in consideration.
  688. // Such a schemee would only waste (align - 8)/2 bytes on average, but
  689. // requires a dedicated function in the outline arena allocation
  690. // functions. Possibly re-evaluate tradeoffs later.
  691. return internal::AlignTo(AllocateAlignedWithHook(n + align - 8, type),
  692. align);
  693. }
  694. }
  695. void* AllocateAlignedNoHook(size_t n);
  696. void* AllocateAlignedWithHook(size_t n, const std::type_info* type);
  697. std::pair<void*, internal::SerialArena::CleanupNode*>
  698. AllocateAlignedWithCleanup(size_t n, const std::type_info* type);
  699. template <typename Type>
  700. friend class internal::GenericTypeHandler;
  701. friend struct internal::ArenaStringPtr; // For AllocateAligned.
  702. friend class internal::InlinedStringField; // For AllocateAligned.
  703. friend class internal::LazyField; // For CreateMaybeMessage.
  704. friend class internal::EpsCopyInputStream; // For parser performance
  705. friend class MessageLite;
  706. template <typename Key, typename T>
  707. friend class Map;
  708. };
  709. // Defined above for supporting environments without RTTI.
  710. #undef RTTI_TYPE_ID
  711. } // namespace protobuf
  712. } // namespace google
  713. #include <google/protobuf/port_undef.inc>
  714. #endif // GOOGLE_PROTOBUF_ARENA_H__