arena.h 33 KB

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