arena.h 33 KB

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