arena.h 31 KB

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