诸暨麻将添加redis
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

327 lines
12 KiB

  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_IMPL_H__
  32. #define GOOGLE_PROTOBUF_ARENA_IMPL_H__
  33. #include <atomic>
  34. #include <limits>
  35. #include <google/protobuf/stubs/common.h>
  36. #include <google/protobuf/stubs/logging.h>
  37. #ifdef ADDRESS_SANITIZER
  38. #include <sanitizer/asan_interface.h>
  39. #endif // ADDRESS_SANITIZER
  40. #include <google/protobuf/port_def.inc>
  41. namespace google {
  42. namespace protobuf {
  43. namespace internal {
  44. inline size_t AlignUpTo8(size_t n) {
  45. // Align n to next multiple of 8 (from Hacker's Delight, Chapter 3.)
  46. return (n + 7) & static_cast<size_t>(-8);
  47. }
  48. using LifecycleId = int64_t;
  49. // This class provides the core Arena memory allocation library. Different
  50. // implementations only need to implement the public interface below.
  51. // Arena is not a template type as that would only be useful if all protos
  52. // in turn would be templates, which will/cannot happen. However separating
  53. // the memory allocation part from the cruft of the API users expect we can
  54. // use #ifdef the select the best implementation based on hardware / OS.
  55. class PROTOBUF_EXPORT ArenaImpl {
  56. public:
  57. struct Options {
  58. size_t start_block_size;
  59. size_t max_block_size;
  60. char* initial_block;
  61. size_t initial_block_size;
  62. void* (*block_alloc)(size_t);
  63. void (*block_dealloc)(void*, size_t);
  64. template <typename O>
  65. explicit Options(const O& options)
  66. : start_block_size(options.start_block_size),
  67. max_block_size(options.max_block_size),
  68. initial_block(options.initial_block),
  69. initial_block_size(options.initial_block_size),
  70. block_alloc(options.block_alloc),
  71. block_dealloc(options.block_dealloc) {}
  72. };
  73. template <typename O>
  74. explicit ArenaImpl(const O& options) : options_(options) {
  75. if (options_.initial_block != NULL && options_.initial_block_size > 0) {
  76. GOOGLE_CHECK_GE(options_.initial_block_size, sizeof(Block))
  77. << ": Initial block size too small for header.";
  78. initial_block_ = reinterpret_cast<Block*>(options_.initial_block);
  79. } else {
  80. initial_block_ = NULL;
  81. }
  82. Init();
  83. }
  84. // Destructor deletes all owned heap allocated objects, and destructs objects
  85. // that have non-trivial destructors, except for proto2 message objects whose
  86. // destructors can be skipped. Also, frees all blocks except the initial block
  87. // if it was passed in.
  88. ~ArenaImpl();
  89. uint64 Reset();
  90. uint64 SpaceAllocated() const;
  91. uint64 SpaceUsed() const;
  92. void* AllocateAligned(size_t n);
  93. void* AllocateAlignedAndAddCleanup(size_t n, void (*cleanup)(void*));
  94. // Add object pointer and cleanup function pointer to the list.
  95. void AddCleanup(void* elem, void (*cleanup)(void*));
  96. private:
  97. void* AllocateAlignedFallback(size_t n);
  98. void* AllocateAlignedAndAddCleanupFallback(size_t n, void (*cleanup)(void*));
  99. void AddCleanupFallback(void* elem, void (*cleanup)(void*));
  100. // Node contains the ptr of the object to be cleaned up and the associated
  101. // cleanup function ptr.
  102. struct CleanupNode {
  103. void* elem; // Pointer to the object to be cleaned up.
  104. void (*cleanup)(void*); // Function pointer to the destructor or deleter.
  105. };
  106. // Cleanup uses a chunked linked list, to reduce pointer chasing.
  107. struct CleanupChunk {
  108. static size_t SizeOf(size_t i) {
  109. return sizeof(CleanupChunk) + (sizeof(CleanupNode) * (i - 1));
  110. }
  111. size_t size; // Total elements in the list.
  112. CleanupChunk* next; // Next node in the list.
  113. CleanupNode nodes[1]; // True length is |size|.
  114. };
  115. class Block;
  116. // A thread-unsafe Arena that can only be used within its owning thread.
  117. class PROTOBUF_EXPORT SerialArena {
  118. public:
  119. // The allocate/free methods here are a little strange, since SerialArena is
  120. // allocated inside a Block which it also manages. This is to avoid doing
  121. // an extra allocation for the SerialArena itself.
  122. // Creates a new SerialArena inside Block* and returns it.
  123. static SerialArena* New(Block* b, void* owner, ArenaImpl* arena);
  124. // Destroys this SerialArena, freeing all blocks with the given dealloc
  125. // function, except any block equal to |initial_block|.
  126. static uint64 Free(SerialArena* serial, Block* initial_block,
  127. void (*block_dealloc)(void*, size_t));
  128. void CleanupList();
  129. uint64 SpaceUsed() const;
  130. void* AllocateAligned(size_t n) {
  131. GOOGLE_DCHECK_EQ(internal::AlignUpTo8(n), n); // Must be already aligned.
  132. GOOGLE_DCHECK_GE(limit_, ptr_);
  133. if (PROTOBUF_PREDICT_FALSE(static_cast<size_t>(limit_ - ptr_) < n)) {
  134. return AllocateAlignedFallback(n);
  135. }
  136. void* ret = ptr_;
  137. ptr_ += n;
  138. #ifdef ADDRESS_SANITIZER
  139. ASAN_UNPOISON_MEMORY_REGION(ret, n);
  140. #endif // ADDRESS_SANITIZER
  141. return ret;
  142. }
  143. void AddCleanup(void* elem, void (*cleanup)(void*)) {
  144. if (PROTOBUF_PREDICT_FALSE(cleanup_ptr_ == cleanup_limit_)) {
  145. AddCleanupFallback(elem, cleanup);
  146. return;
  147. }
  148. cleanup_ptr_->elem = elem;
  149. cleanup_ptr_->cleanup = cleanup;
  150. cleanup_ptr_++;
  151. }
  152. void* AllocateAlignedAndAddCleanup(size_t n, void (*cleanup)(void*)) {
  153. void* ret = AllocateAligned(n);
  154. AddCleanup(ret, cleanup);
  155. return ret;
  156. }
  157. void* owner() const { return owner_; }
  158. SerialArena* next() const { return next_; }
  159. void set_next(SerialArena* next) { next_ = next; }
  160. private:
  161. void* AllocateAlignedFallback(size_t n);
  162. void AddCleanupFallback(void* elem, void (*cleanup)(void*));
  163. void CleanupListFallback();
  164. ArenaImpl* arena_; // Containing arena.
  165. void* owner_; // &ThreadCache of this thread;
  166. Block* head_; // Head of linked list of blocks.
  167. CleanupChunk* cleanup_; // Head of cleanup list.
  168. SerialArena* next_; // Next SerialArena in this linked list.
  169. // Next pointer to allocate from. Always 8-byte aligned. Points inside
  170. // head_ (and head_->pos will always be non-canonical). We keep these
  171. // here to reduce indirection.
  172. char* ptr_;
  173. char* limit_;
  174. // Next CleanupList members to append to. These point inside cleanup_.
  175. CleanupNode* cleanup_ptr_;
  176. CleanupNode* cleanup_limit_;
  177. };
  178. // Blocks are variable length malloc-ed objects. The following structure
  179. // describes the common header for all blocks.
  180. class PROTOBUF_EXPORT Block {
  181. public:
  182. Block(size_t size, Block* next);
  183. char* Pointer(size_t n) {
  184. GOOGLE_DCHECK(n <= size_);
  185. return reinterpret_cast<char*>(this) + n;
  186. }
  187. Block* next() const { return next_; }
  188. size_t pos() const { return pos_; }
  189. size_t size() const { return size_; }
  190. void set_pos(size_t pos) { pos_ = pos; }
  191. private:
  192. Block* next_; // Next block for this thread.
  193. size_t pos_;
  194. size_t size_;
  195. // data follows
  196. };
  197. struct ThreadCache {
  198. #if defined(GOOGLE_PROTOBUF_NO_THREADLOCAL)
  199. // If we are using the ThreadLocalStorage class to store the ThreadCache,
  200. // then the ThreadCache's default constructor has to be responsible for
  201. // initializing it.
  202. ThreadCache() : last_lifecycle_id_seen(-1), last_serial_arena(NULL) {}
  203. #endif
  204. // The ThreadCache is considered valid as long as this matches the
  205. // lifecycle_id of the arena being used.
  206. LifecycleId last_lifecycle_id_seen;
  207. SerialArena* last_serial_arena;
  208. };
  209. static std::atomic<LifecycleId> lifecycle_id_generator_;
  210. #if defined(GOOGLE_PROTOBUF_NO_THREADLOCAL)
  211. // Android ndk does not support GOOGLE_THREAD_LOCAL keyword so we use a custom thread
  212. // local storage class we implemented.
  213. // iOS also does not support the GOOGLE_THREAD_LOCAL keyword.
  214. static ThreadCache& thread_cache();
  215. #elif defined(PROTOBUF_USE_DLLS)
  216. // Thread local variables cannot be exposed through DLL interface but we can
  217. // wrap them in static functions.
  218. static ThreadCache& thread_cache();
  219. #else
  220. static GOOGLE_THREAD_LOCAL ThreadCache thread_cache_;
  221. static ThreadCache& thread_cache() { return thread_cache_; }
  222. #endif
  223. void Init();
  224. // Free all blocks and return the total space used which is the sums of sizes
  225. // of the all the allocated blocks.
  226. uint64 FreeBlocks();
  227. // Delete or Destruct all objects owned by the arena.
  228. void CleanupList();
  229. inline void CacheSerialArena(SerialArena* serial) {
  230. thread_cache().last_serial_arena = serial;
  231. thread_cache().last_lifecycle_id_seen = lifecycle_id_;
  232. // TODO(haberman): evaluate whether we would gain efficiency by getting rid
  233. // of hint_. It's the only write we do to ArenaImpl in the allocation path,
  234. // which will dirty the cache line.
  235. hint_.store(serial, std::memory_order_release);
  236. }
  237. std::atomic<SerialArena*>
  238. threads_; // Pointer to a linked list of SerialArena.
  239. std::atomic<SerialArena*> hint_; // Fast thread-local block access
  240. std::atomic<size_t> space_allocated_; // Total size of all allocated blocks.
  241. Block* initial_block_; // If non-NULL, points to the block that came from
  242. // user data.
  243. Block* NewBlock(Block* last_block, size_t min_bytes);
  244. SerialArena* GetSerialArena();
  245. bool GetSerialArenaFast(SerialArena** arena);
  246. SerialArena* GetSerialArenaFallback(void* me);
  247. LifecycleId lifecycle_id_; // Unique for each arena. Changes on Reset().
  248. Options options_;
  249. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ArenaImpl);
  250. // All protos have pointers back to the arena hence Arena must have
  251. // pointer stability.
  252. ArenaImpl(ArenaImpl&&) = delete;
  253. ArenaImpl& operator=(ArenaImpl&&) = delete;
  254. public:
  255. // kBlockHeaderSize is sizeof(Block), aligned up to the nearest multiple of 8
  256. // to protect the invariant that pos is always at a multiple of 8.
  257. static const size_t kBlockHeaderSize =
  258. (sizeof(Block) + 7) & static_cast<size_t>(-8);
  259. static const size_t kSerialArenaSize =
  260. (sizeof(SerialArena) + 7) & static_cast<size_t>(-8);
  261. static_assert(kBlockHeaderSize % 8 == 0,
  262. "kBlockHeaderSize must be a multiple of 8.");
  263. static_assert(kSerialArenaSize % 8 == 0,
  264. "kSerialArenaSize must be a multiple of 8.");
  265. };
  266. } // namespace internal
  267. } // namespace protobuf
  268. } // namespace google
  269. #include <google/protobuf/port_undef.inc>
  270. #endif // GOOGLE_PROTOBUF_ARENA_IMPL_H__