arena.h 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  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. #ifdef max
  35. #undef max // Visual Studio defines this macro
  36. #endif
  37. #if defined(_MSC_VER) && !defined(_LIBCPP_STD_VER) && !_HAS_EXCEPTIONS
  38. // Work around bugs in MSVC <typeinfo> header when _HAS_EXCEPTIONS=0.
  39. #include <exception>
  40. #include <typeinfo>
  41. namespace std {
  42. using type_info = ::type_info;
  43. }
  44. #else
  45. #include <typeinfo>
  46. #endif
  47. #include <google/protobuf/arena_impl.h>
  48. #include <google/protobuf/stubs/port.h>
  49. #include <type_traits>
  50. namespace google {
  51. namespace protobuf {
  52. struct ArenaOptions; // defined below
  53. } // namespace protobuf
  54. namespace quality_webanswers {
  55. void TempPrivateWorkAround(::google::protobuf::ArenaOptions* arena_options);
  56. } // namespace quality_webanswers
  57. namespace protobuf {
  58. class Arena; // defined below
  59. class Message; // defined in message.h
  60. class MessageLite;
  61. namespace arena_metrics {
  62. void EnableArenaMetrics(::google::protobuf::ArenaOptions* options);
  63. } // namespace arena_metrics
  64. namespace internal {
  65. struct ArenaStringPtr; // defined in arenastring.h
  66. class LazyField; // defined in lazy_field.h
  67. template <typename Type>
  68. class GenericTypeHandler; // defined in repeated_field.h
  69. // Templated cleanup methods.
  70. template <typename T>
  71. void arena_destruct_object(void* object) {
  72. reinterpret_cast<T*>(object)->~T();
  73. }
  74. template <typename T>
  75. void arena_delete_object(void* object) {
  76. delete reinterpret_cast<T*>(object);
  77. }
  78. inline void arena_free(void* object, size_t size) {
  79. #if defined(__GXX_DELETE_WITH_SIZE__) || defined(__cpp_sized_deallocation)
  80. ::operator delete(object, size);
  81. #else
  82. (void)size;
  83. ::operator delete(object);
  84. #endif
  85. }
  86. } // namespace internal
  87. // ArenaOptions provides optional additional parameters to arena construction
  88. // that control its block-allocation behavior.
  89. struct ArenaOptions {
  90. // This defines the size of the first block requested from the system malloc.
  91. // Subsequent block sizes will increase in a geometric series up to a maximum.
  92. size_t start_block_size;
  93. // This defines the maximum block size requested from system malloc (unless an
  94. // individual arena allocation request occurs with a size larger than this
  95. // maximum). Requested block sizes increase up to this value, then remain
  96. // here.
  97. size_t max_block_size;
  98. // An initial block of memory for the arena to use, or NULL for none. If
  99. // provided, the block must live at least as long as the arena itself. The
  100. // creator of the Arena retains ownership of the block after the Arena is
  101. // destroyed.
  102. char* initial_block;
  103. // The size of the initial block, if provided.
  104. size_t initial_block_size;
  105. // A function pointer to an alloc method that returns memory blocks of size
  106. // requested. By default, it contains a ptr to the malloc function.
  107. //
  108. // NOTE: block_alloc and dealloc functions are expected to behave like
  109. // malloc and free, including Asan poisoning.
  110. void* (*block_alloc)(size_t);
  111. // A function pointer to a dealloc method that takes ownership of the blocks
  112. // from the arena. By default, it contains a ptr to a wrapper function that
  113. // calls free.
  114. void (*block_dealloc)(void*, size_t);
  115. ArenaOptions()
  116. : start_block_size(kDefaultStartBlockSize),
  117. max_block_size(kDefaultMaxBlockSize),
  118. initial_block(NULL),
  119. initial_block_size(0),
  120. block_alloc(&::operator new),
  121. block_dealloc(&internal::arena_free),
  122. on_arena_init(NULL),
  123. on_arena_reset(NULL),
  124. on_arena_destruction(NULL),
  125. on_arena_allocation(NULL) {}
  126. private:
  127. // Hooks for adding external functionality such as user-specific metrics
  128. // collection, specific debugging abilities, etc.
  129. // Init hook may return a pointer to a cookie to be stored in the arena.
  130. // reset and destruction hooks will then be called with the same cookie
  131. // pointer. This allows us to save an external object per arena instance and
  132. // use it on the other hooks (Note: It is just as legal for init to return
  133. // NULL and not use the cookie feature).
  134. // on_arena_reset and on_arena_destruction also receive the space used in
  135. // the arena just before the reset.
  136. void* (*on_arena_init)(Arena* arena);
  137. void (*on_arena_reset)(Arena* arena, void* cookie, uint64 space_used);
  138. void (*on_arena_destruction)(Arena* arena, void* cookie, uint64 space_used);
  139. // type_info is promised to be static - its lifetime extends to
  140. // match program's lifetime (It is given by typeid operator).
  141. // Note: typeid(void) will be passed as allocated_type every time we
  142. // intentionally want to avoid monitoring an allocation. (i.e. internal
  143. // allocations for managing the arena)
  144. void (*on_arena_allocation)(const std::type_info* allocated_type,
  145. uint64 alloc_size, void* cookie);
  146. // Constants define default starting block size and max block size for
  147. // arena allocator behavior -- see descriptions above.
  148. static const size_t kDefaultStartBlockSize = 256;
  149. static const size_t kDefaultMaxBlockSize = 8192;
  150. friend void ::google::protobuf::arena_metrics::EnableArenaMetrics(ArenaOptions*);
  151. friend void quality_webanswers::TempPrivateWorkAround(ArenaOptions*);
  152. friend class Arena;
  153. friend class ArenaOptionsTestFriend;
  154. };
  155. // Support for non-RTTI environments. (The metrics hooks API uses type
  156. // information.)
  157. #ifndef GOOGLE_PROTOBUF_NO_RTTI
  158. #define RTTI_TYPE_ID(type) (&typeid(type))
  159. #else
  160. #define RTTI_TYPE_ID(type) (NULL)
  161. #endif
  162. // Arena allocator. Arena allocation replaces ordinary (heap-based) allocation
  163. // with new/delete, and improves performance by aggregating allocations into
  164. // larger blocks and freeing allocations all at once. Protocol messages are
  165. // allocated on an arena by using Arena::CreateMessage<T>(Arena*), below, and
  166. // are automatically freed when the arena is destroyed.
  167. //
  168. // This is a thread-safe implementation: multiple threads may allocate from the
  169. // arena concurrently. Destruction is not thread-safe and the destructing
  170. // thread must synchronize with users of the arena first.
  171. //
  172. // An arena provides two allocation interfaces: CreateMessage<T>, which works
  173. // for arena-enabled proto2 message types as well as other types that satisfy
  174. // the appropriate protocol (described below), and Create<T>, which works for
  175. // any arbitrary type T. CreateMessage<T> is better when the type T supports it,
  176. // because this interface (i) passes the arena pointer to the created object so
  177. // that its sub-objects and internal allocations can use the arena too, and (ii)
  178. // elides the object's destructor call when possible. Create<T> does not place
  179. // any special requirements on the type T, and will invoke the object's
  180. // destructor when the arena is destroyed.
  181. //
  182. // The arena message allocation protocol, required by CreateMessage<T>, is as
  183. // follows:
  184. //
  185. // - The type T must have (at least) two constructors: a constructor with no
  186. // arguments, called when a T is allocated on the heap; and a constructor with
  187. // a google::protobuf::Arena* argument, called when a T is allocated on an arena. If the
  188. // second constructor is called with a NULL arena pointer, it must be
  189. // equivalent to invoking the first (no-argument) constructor.
  190. //
  191. // - The type T must have a particular type trait: a nested type
  192. // |InternalArenaConstructable_|. This is usually a typedef to |void|. If no
  193. // such type trait exists, then the instantiation CreateMessage<T> will fail
  194. // to compile.
  195. //
  196. // - The type T *may* have the type trait |DestructorSkippable_|. If this type
  197. // trait is present in the type, then its destructor will not be called if and
  198. // only if it was passed a non-NULL arena pointer. If this type trait is not
  199. // present on the type, then its destructor is always called when the
  200. // containing arena is destroyed.
  201. //
  202. // - One- and two-user-argument forms of CreateMessage<T>() also exist that
  203. // forward these constructor arguments to T's constructor: for example,
  204. // CreateMessage<T>(Arena*, arg1, arg2) forwards to a constructor T(Arena*,
  205. // arg1, arg2).
  206. //
  207. // This protocol is implemented by all arena-enabled proto2 message classes as
  208. // well as RepeatedPtrField.
  209. //
  210. // Do NOT subclass Arena. This class will be marked as final when C++11 is
  211. // enabled.
  212. class LIBPROTOBUF_EXPORT Arena {
  213. public:
  214. // Arena constructor taking custom options. See ArenaOptions below for
  215. // descriptions of the options available.
  216. explicit Arena(const ArenaOptions& options) : impl_(options) {
  217. Init(options);
  218. }
  219. // Block overhead. Use this as a guide for how much to over-allocate the
  220. // initial block if you want an allocation of size N to fit inside it.
  221. //
  222. // WARNING: if you allocate multiple objects, it is difficult to guarantee
  223. // that a series of allocations will fit in the initial block, especially if
  224. // Arena changes its alignment guarantees in the future!
  225. static const size_t kBlockOverhead = internal::ArenaImpl::kBlockHeaderSize +
  226. internal::ArenaImpl::kSerialArenaSize;
  227. // Default constructor with sensible default options, tuned for average
  228. // use-cases.
  229. Arena() : impl_(ArenaOptions()) { Init(ArenaOptions()); }
  230. ~Arena() {
  231. if (hooks_cookie_) {
  232. CallDestructorHooks();
  233. }
  234. }
  235. void Init(const ArenaOptions& options) {
  236. on_arena_allocation_ = options.on_arena_allocation;
  237. on_arena_reset_ = options.on_arena_reset;
  238. on_arena_destruction_ = options.on_arena_destruction;
  239. // Call the initialization hook
  240. if (options.on_arena_init != NULL) {
  241. hooks_cookie_ = options.on_arena_init(this);
  242. } else {
  243. hooks_cookie_ = NULL;
  244. }
  245. }
  246. // API to create proto2 message objects on the arena. If the arena passed in
  247. // is NULL, then a heap allocated object is returned. Type T must be a message
  248. // defined in a .proto file with cc_enable_arenas set to true, otherwise a
  249. // compilation error will occur.
  250. //
  251. // RepeatedField and RepeatedPtrField may also be instantiated directly on an
  252. // arena with this method.
  253. //
  254. // This function also accepts any type T that satisfies the arena message
  255. // allocation protocol, documented above.
  256. template <typename T, typename... Args>
  257. GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMessage(
  258. Arena* arena, Args&&... args) {
  259. static_assert(
  260. InternalHelper<T>::is_arena_constructable::value,
  261. "CreateMessage can only construct types that are ArenaConstructable");
  262. // We must delegate to CreateMaybeMessage() and NOT CreateMessageInternal()
  263. // because protobuf generated classes specialize CreateMaybeMessage() and we
  264. // need to use that specialization for code size reasons.
  265. return Arena::CreateMaybeMessage<T>(arena, std::forward<Args>(args)...);
  266. }
  267. // API to create any objects on the arena. Note that only the object will
  268. // be created on the arena; the underlying ptrs (in case of a proto2 message)
  269. // will be still heap allocated. Proto messages should usually be allocated
  270. // with CreateMessage<T>() instead.
  271. //
  272. // Note that even if T satisfies the arena message construction protocol
  273. // (InternalArenaConstructable_ trait and optional DestructorSkippable_
  274. // trait), as described above, this function does not follow the protocol;
  275. // instead, it treats T as a black-box type, just as if it did not have these
  276. // traits. Specifically, T's constructor arguments will always be only those
  277. // passed to Create<T>() -- no additional arena pointer is implicitly added.
  278. // Furthermore, the destructor will always be called at arena destruction time
  279. // (unless the destructor is trivial). Hence, from T's point of view, it is as
  280. // if the object were allocated on the heap (except that the underlying memory
  281. // is obtained from the arena).
  282. template <typename T, typename... Args>
  283. GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* Create(Arena* arena,
  284. Args&&... args) {
  285. return CreateNoMessage<T>(arena, is_arena_constructable<T>(),
  286. std::forward<Args>(args)...);
  287. }
  288. // Create an array of object type T on the arena *without* invoking the
  289. // constructor of T. If `arena` is null, then the return value should be freed
  290. // with `delete[] x;` (or `::operator delete[](x);`).
  291. // To ensure safe uses, this function checks at compile time
  292. // (when compiled as C++11) that T is trivially default-constructible and
  293. // trivially destructible.
  294. template <typename T>
  295. GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateArray(
  296. Arena* arena, size_t num_elements) {
  297. static_assert(std::is_pod<T>::value,
  298. "CreateArray requires a trivially constructible type");
  299. static_assert(std::is_trivially_destructible<T>::value,
  300. "CreateArray requires a trivially destructible type");
  301. GOOGLE_CHECK_LE(num_elements, std::numeric_limits<size_t>::max() / sizeof(T))
  302. << "Requested size is too large to fit into size_t.";
  303. if (arena == NULL) {
  304. return static_cast<T*>(::operator new[](num_elements * sizeof(T)));
  305. } else {
  306. return arena->CreateInternalRawArray<T>(num_elements);
  307. }
  308. }
  309. // Returns the total space allocated by the arena, which is the sum of the
  310. // sizes of the underlying blocks. This method is relatively fast; a counter
  311. // is kept as blocks are allocated.
  312. uint64 SpaceAllocated() const { return impl_.SpaceAllocated(); }
  313. // Returns the total space used by the arena. Similar to SpaceAllocated but
  314. // does not include free space and block overhead. The total space returned
  315. // may not include space used by other threads executing concurrently with
  316. // the call to this method.
  317. uint64 SpaceUsed() const { return impl_.SpaceUsed(); }
  318. // DEPRECATED. Please use SpaceAllocated() and SpaceUsed().
  319. //
  320. // Combines SpaceAllocated and SpaceUsed. Returns a pair of
  321. // <space_allocated, space_used>.
  322. PROTOBUF_RUNTIME_DEPRECATED("Please use SpaceAllocated() and SpaceUsed()")
  323. std::pair<uint64, uint64> SpaceAllocatedAndUsed() const {
  324. return std::make_pair(SpaceAllocated(), SpaceUsed());
  325. }
  326. // Frees all storage allocated by this arena after calling destructors
  327. // registered with OwnDestructor() and freeing objects registered with Own().
  328. // Any objects allocated on this arena are unusable after this call. It also
  329. // returns the total space used by the arena which is the sums of the sizes
  330. // of the allocated blocks. This method is not thread-safe.
  331. GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE uint64 Reset() {
  332. // Call the reset hook
  333. if (on_arena_reset_ != NULL) {
  334. on_arena_reset_(this, hooks_cookie_, impl_.SpaceAllocated());
  335. }
  336. return impl_.Reset();
  337. }
  338. // Adds |object| to a list of heap-allocated objects to be freed with |delete|
  339. // when the arena is destroyed or reset.
  340. template <typename T>
  341. GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE void Own(T* object) {
  342. OwnInternal(object, std::is_convertible<T*, Message*>());
  343. }
  344. // Adds |object| to a list of objects whose destructors will be manually
  345. // called when the arena is destroyed or reset. This differs from Own() in
  346. // that it does not free the underlying memory with |delete|; hence, it is
  347. // normally only used for objects that are placement-newed into
  348. // arena-allocated memory.
  349. template <typename T>
  350. GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE void OwnDestructor(T* object) {
  351. if (object != NULL) {
  352. impl_.AddCleanup(object, &internal::arena_destruct_object<T>);
  353. }
  354. }
  355. // Adds a custom member function on an object to the list of destructors that
  356. // will be manually called when the arena is destroyed or reset. This differs
  357. // from OwnDestructor() in that any member function may be specified, not only
  358. // the class destructor.
  359. GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE void OwnCustomDestructor(
  360. void* object, void (*destruct)(void*)) {
  361. impl_.AddCleanup(object, destruct);
  362. }
  363. // Retrieves the arena associated with |value| if |value| is an arena-capable
  364. // message, or NULL otherwise. This differs from value->GetArena() in that the
  365. // latter is a virtual call, while this method is a templated call that
  366. // resolves at compile-time.
  367. template <typename T>
  368. GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Arena* GetArena(
  369. const T* value) {
  370. return GetArenaInternal(value, is_arena_constructable<T>());
  371. }
  372. template <typename T>
  373. class InternalHelper {
  374. template <typename U>
  375. static char DestructorSkippable(const typename U::DestructorSkippable_*);
  376. template <typename U>
  377. static double DestructorSkippable(...);
  378. typedef std::integral_constant<
  379. bool, sizeof(DestructorSkippable<T>(static_cast<const T*>(0))) ==
  380. sizeof(char) ||
  381. std::is_trivially_destructible<T>::value>
  382. is_destructor_skippable;
  383. template <typename U>
  384. static char ArenaConstructable(
  385. const typename U::InternalArenaConstructable_*);
  386. template <typename U>
  387. static double ArenaConstructable(...);
  388. typedef std::integral_constant<bool, sizeof(ArenaConstructable<T>(
  389. static_cast<const T*>(0))) ==
  390. sizeof(char)>
  391. is_arena_constructable;
  392. template <typename... Args>
  393. static T* Construct(void* ptr, Args&&... args) {
  394. return new (ptr) T(std::forward<Args>(args)...);
  395. }
  396. static Arena* GetArena(const T* p) { return p->GetArenaNoVirtual(); }
  397. friend class Arena;
  398. };
  399. // Helper typetraits that indicates support for arenas in a type T at compile
  400. // time. This is public only to allow construction of higher-level templated
  401. // utilities.
  402. //
  403. // is_arena_constructable<T>::value is true if the message type T has arena
  404. // support enabled, and false otherwise.
  405. //
  406. // is_destructor_skippable<T>::value is true if the message type T has told
  407. // the arena that it is safe to skip the destructor, and false otherwise.
  408. //
  409. // This is inside Arena because only Arena has the friend relationships
  410. // necessary to see the underlying generated code traits.
  411. template <typename T>
  412. struct is_arena_constructable : InternalHelper<T>::is_arena_constructable {};
  413. template <typename T>
  414. struct is_destructor_skippable : InternalHelper<T>::is_destructor_skippable {
  415. };
  416. private:
  417. template <typename T, typename... Args>
  418. GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMessageInternal(
  419. Arena* arena, Args&&... args) {
  420. static_assert(
  421. InternalHelper<T>::is_arena_constructable::value,
  422. "CreateMessage can only construct types that are ArenaConstructable");
  423. if (arena == NULL) {
  424. return new T(nullptr, std::forward<Args>(args)...);
  425. } else {
  426. return arena->DoCreateMessage<T>(std::forward<Args>(args)...);
  427. }
  428. }
  429. // This specialization for no arguments is necessary, because its behavior is
  430. // slightly different. When the arena pointer is nullptr, it calls T()
  431. // instead of T(nullptr).
  432. template <typename T>
  433. GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMessageInternal(
  434. Arena* arena) {
  435. static_assert(
  436. InternalHelper<T>::is_arena_constructable::value,
  437. "CreateMessage can only construct types that are ArenaConstructable");
  438. if (arena == NULL) {
  439. return new T();
  440. } else {
  441. return arena->DoCreateMessage<T>();
  442. }
  443. }
  444. template <typename T, typename... Args>
  445. GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateInternal(
  446. Arena* arena, Args&&... args) {
  447. if (arena == NULL) {
  448. return new T(std::forward<Args>(args)...);
  449. } else {
  450. return arena->DoCreate<T>(std::is_trivially_destructible<T>::value,
  451. std::forward<Args>(args)...);
  452. }
  453. }
  454. void CallDestructorHooks();
  455. void OnArenaAllocation(const std::type_info* allocated_type, size_t n) const;
  456. inline void AllocHook(const std::type_info* allocated_type, size_t n) const {
  457. if (GOOGLE_PREDICT_FALSE(hooks_cookie_ != NULL)) {
  458. OnArenaAllocation(allocated_type, n);
  459. }
  460. }
  461. // Allocate and also optionally call on_arena_allocation callback with the
  462. // allocated type info when the hooks are in place in ArenaOptions and
  463. // the cookie is not null.
  464. template <typename T>
  465. GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void* AllocateInternal(
  466. bool skip_explicit_ownership) {
  467. const size_t n = internal::AlignUpTo8(sizeof(T));
  468. AllocHook(RTTI_TYPE_ID(T), n);
  469. // Monitor allocation if needed.
  470. if (skip_explicit_ownership) {
  471. return impl_.AllocateAligned(n);
  472. } else {
  473. return impl_.AllocateAlignedAndAddCleanup(
  474. n, &internal::arena_destruct_object<T>);
  475. }
  476. }
  477. // CreateMessage<T> requires that T supports arenas, but this private method
  478. // works whether or not T supports arenas. These are not exposed to user code
  479. // as it can cause confusing API usages, and end up having double free in
  480. // user code. These are used only internally from LazyField and Repeated
  481. // fields, since they are designed to work in all mode combinations.
  482. template <typename Msg, typename... Args>
  483. GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Msg* DoCreateMaybeMessage(
  484. Arena* arena, std::true_type, Args&&... args) {
  485. return CreateMessageInternal<Msg>(arena, std::forward<Args>(args)...);
  486. }
  487. template <typename T, typename... Args>
  488. GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* DoCreateMaybeMessage(
  489. Arena* arena, std::false_type, Args&&... args) {
  490. return CreateInternal<T>(arena, std::forward<Args>(args)...);
  491. }
  492. template <typename T, typename... Args>
  493. GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMaybeMessage(
  494. Arena* arena, Args&&... args) {
  495. return DoCreateMaybeMessage<T>(arena, is_arena_constructable<T>(),
  496. std::forward<Args>(args)...);
  497. }
  498. template <typename T, typename... Args>
  499. GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateNoMessage(
  500. Arena* arena, std::true_type, Args&&... args) {
  501. // User is constructing with Create() despite the fact that T supports arena
  502. // construction. In this case we have to delegate to CreateInternal(), and
  503. // we can't use any CreateMaybeMessage() specialization that may be defined.
  504. return CreateInternal<T>(arena, std::forward<Args>(args)...);
  505. }
  506. template <typename T, typename... Args>
  507. GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateNoMessage(
  508. Arena* arena, std::false_type, Args&&... args) {
  509. // User is constructing with Create() and the type does not support arena
  510. // construction. In this case we can delegate to CreateMaybeMessage() and
  511. // use any specialization that may be available for that.
  512. return CreateMaybeMessage<T>(arena, std::forward<Args>(args)...);
  513. }
  514. // Just allocate the required size for the given type assuming the
  515. // type has a trivial constructor.
  516. template <typename T>
  517. GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* CreateInternalRawArray(
  518. size_t num_elements) {
  519. GOOGLE_CHECK_LE(num_elements, std::numeric_limits<size_t>::max() / sizeof(T))
  520. << "Requested size is too large to fit into size_t.";
  521. const size_t n = internal::AlignUpTo8(sizeof(T) * num_elements);
  522. // Monitor allocation if needed.
  523. AllocHook(RTTI_TYPE_ID(T), n);
  524. return static_cast<T*>(impl_.AllocateAligned(n));
  525. }
  526. template <typename T, typename... Args>
  527. GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* DoCreate(
  528. bool skip_explicit_ownership, Args&&... args) {
  529. return new (AllocateInternal<T>(skip_explicit_ownership))
  530. T(std::forward<Args>(args)...);
  531. }
  532. template <typename T, typename... Args>
  533. GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* DoCreateMessage(Args&&... args) {
  534. return InternalHelper<T>::Construct(
  535. AllocateInternal<T>(InternalHelper<T>::is_destructor_skippable::value),
  536. this, std::forward<Args>(args)...);
  537. }
  538. // CreateInArenaStorage is used to implement map field. Without it,
  539. // google::protobuf::Map need to call generated message's protected arena constructor,
  540. // which needs to declare google::protobuf::Map as friend of generated message.
  541. template <typename T>
  542. static void CreateInArenaStorage(T* ptr, Arena* arena) {
  543. CreateInArenaStorageInternal(ptr, arena,
  544. typename is_arena_constructable<T>::type());
  545. RegisterDestructorInternal(
  546. ptr, arena,
  547. typename InternalHelper<T>::is_destructor_skippable::type());
  548. }
  549. template <typename T>
  550. static void CreateInArenaStorageInternal(T* ptr, Arena* arena,
  551. std::true_type) {
  552. InternalHelper<T>::Construct(ptr, arena);
  553. }
  554. template <typename T>
  555. static void CreateInArenaStorageInternal(T* ptr, Arena* /* arena */,
  556. std::false_type) {
  557. new (ptr) T();
  558. }
  559. template <typename T>
  560. static void RegisterDestructorInternal(T* /* ptr */, Arena* /* arena */,
  561. std::true_type) {}
  562. template <typename T>
  563. static void RegisterDestructorInternal(T* ptr, Arena* arena,
  564. std::false_type) {
  565. arena->OwnDestructor(ptr);
  566. }
  567. // These implement Own(), which registers an object for deletion (destructor
  568. // call and operator delete()). The second parameter has type 'true_type' if T
  569. // is a subtype of ::google::protobuf::Message and 'false_type' otherwise. Collapsing
  570. // all template instantiations to one for generic Message reduces code size,
  571. // using the virtual destructor instead.
  572. template <typename T>
  573. GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void OwnInternal(T* object,
  574. std::true_type) {
  575. if (object != NULL) {
  576. impl_.AddCleanup(object, &internal::arena_delete_object<Message>);
  577. }
  578. }
  579. template <typename T>
  580. GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void OwnInternal(T* object,
  581. std::false_type) {
  582. if (object != NULL) {
  583. impl_.AddCleanup(object, &internal::arena_delete_object<T>);
  584. }
  585. }
  586. // Implementation for GetArena(). Only message objects with
  587. // InternalArenaConstructable_ tags can be associated with an arena, and such
  588. // objects must implement a GetArenaNoVirtual() method.
  589. template <typename T>
  590. GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Arena* GetArenaInternal(
  591. const T* value, std::true_type) {
  592. return InternalHelper<T>::GetArena(value);
  593. }
  594. template <typename T>
  595. GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Arena* GetArenaInternal(
  596. const T* /* value */, std::false_type) {
  597. return NULL;
  598. }
  599. // For friends of arena.
  600. void* AllocateAligned(size_t n) {
  601. AllocHook(NULL, n);
  602. return impl_.AllocateAligned(internal::AlignUpTo8(n));
  603. }
  604. internal::ArenaImpl impl_;
  605. void (*on_arena_allocation_)(const std::type_info* allocated_type,
  606. uint64 alloc_size, void* cookie);
  607. void (*on_arena_reset_)(Arena* arena, void* cookie, uint64 space_used);
  608. void (*on_arena_destruction_)(Arena* arena, void* cookie, uint64 space_used);
  609. // The arena may save a cookie it receives from the external on_init hook
  610. // and then use it when calling the on_reset and on_destruction hooks.
  611. void* hooks_cookie_;
  612. template <typename Type>
  613. friend class internal::GenericTypeHandler;
  614. friend struct internal::ArenaStringPtr; // For AllocateAligned.
  615. friend class internal::LazyField; // For CreateMaybeMessage.
  616. friend class MessageLite;
  617. template <typename Key, typename T>
  618. friend class Map;
  619. };
  620. // Defined above for supporting environments without RTTI.
  621. #undef RTTI_TYPE_ID
  622. } // namespace protobuf
  623. } // namespace google
  624. #endif // GOOGLE_PROTOBUF_ARENA_H__