OLD | NEW |
---|---|
(Empty) | |
1 // Copyright (c) 2015 The Chromium Authors. All rights reserved. | |
2 // Use of this source code is governed by a BSD-style license that can be | |
3 // found in the LICENSE file. | |
4 | |
5 #ifndef BASE_MEMORY_PERSISTENT_MEMORY_ALLOCATOR_H_ | |
6 #define BASE_MEMORY_PERSISTENT_MEMORY_ALLOCATOR_H_ | |
7 | |
8 #include <stdint.h> | |
9 #include <atomic> | |
10 #include <string> | |
11 | |
12 #include "base/atomicops.h" | |
Dmitry Vyukov
2015/12/03 20:51:37
Do you still need this include?
| |
13 #include "base/base_export.h" | |
14 #include "base/gtest_prod_util.h" | |
15 #include "base/macros.h" | |
16 | |
17 namespace base { | |
18 | |
19 class HistogramBase; | |
20 | |
21 // Simple allocator for pieces of a memory block that may be persistent | |
22 // to some storage or shared across multiple processes. | |
23 // | |
24 // This class provides for thread-secure (i.e. safe against other threads | |
25 // or processes that may be compromised and thus have malicious intent) | |
26 // allocation of memory within a designated block and also a mechanism by | |
27 // which other threads can learn of these allocations. | |
28 // | |
29 // There is (currently) no way to release an allocated block of data because | |
30 // doing so would risk invalidating pointers held by other processes and | |
31 // greatly complicate the allocation algorithm. | |
32 // | |
33 // Construction of this object can accept new, clean (i.e. zeroed) memory | |
34 // or previously initialized memory. In the first case, construction must | |
35 // be allowed to complete before letting other allocators attach to the same | |
36 // segment. In other words, don't share the segment until at least one | |
37 // allocator has been attached to it. | |
38 // | |
39 // It should be noted that memory doesn't need to actually have zeros written | |
Dmitry Vyukov
2015/12/03 20:51:37
I still don't understand this comment. All memory
bcwhite
2015/12/03 21:53:41
I guess it is somewhat redundant since the previou
| |
40 // throughout; it just needs to read as zero until something diffferent is | |
41 // written to a location. This is an important distinction as it supports the | |
42 // use-case of non-pinned memory, such as from a demand-allocated region by | |
43 // the OS or a memory-mapped file that auto-grows from a starting size of zero. | |
44 class BASE_EXPORT PersistentMemoryAllocator { | |
45 public: | |
46 typedef uint32_t Reference; | |
47 | |
48 // Internal state information when iterating over memory allocations. | |
49 class Iterator { | |
50 public: | |
51 Iterator() : last(0) {} | |
52 | |
53 bool operator==(const Iterator& rhs) const { return last == rhs.last; } | |
54 bool operator!=(const Iterator& rhs) const { return last != rhs.last; } | |
55 | |
56 void clear() { last = 0; } | |
57 bool is_clear() { return last == 0; } | |
58 | |
59 private: | |
60 friend class PersistentMemoryAllocator; | |
61 | |
62 Reference last; | |
63 uint32_t niter; | |
64 }; | |
65 | |
66 // Returned information about the internal state of the heap. | |
67 struct MemoryInfo { | |
68 size_t total; | |
69 size_t free; | |
70 }; | |
71 | |
72 enum : uint32_t { | |
73 kTypeIdAny = 0 // Match any type-id inside GetAsObject(). | |
74 }; | |
75 | |
76 // The allocator operates on any arbitrary block of memory. Creation and | |
77 // persisting or sharing of that block with another process is the | |
78 // responsibility of the caller. The allocator needs to know only the | |
79 // block's |base| address, the total |size| of the block, and any internal | |
80 // |page| size (zero if not paged) across which allocations should not span. | |
81 // The |name|, if provided, is used to distinguish histograms for this | |
82 // allocator. Only the primary owner of the segment should define this value; | |
83 // other processes can learn it from the shared state. | |
84 // | |
85 // PersistentMemoryAllocator does NOT take ownership of the memory block. | |
86 // The caller must manage it and ensure it stays available throughout the | |
87 // lifetime of this object. | |
88 // | |
89 // Memory segments for sharing must have had an allocator attached to them | |
90 // before actually being shared. If the memory segment was just created, it | |
91 // should be zeroed before being passed here. If it was an existing segment, | |
92 // the values here will be compared to copies stored in the shared segment | |
93 // as a guard against corruption. | |
94 PersistentMemoryAllocator(void* base, size_t size, size_t page_size, | |
95 const std::string& name); | |
96 ~PersistentMemoryAllocator(); | |
97 | |
98 // Get an object referenced by a |ref|. For safety reasons, the |type_id| | |
99 // code and size-of(|T|) are compared to ensure the reference is valid | |
100 // and cannot return an object outside of the memory segment. A |type_id| of | |
101 // zero will match any though the size is still checked. NULL is returned | |
102 // if any problem is detected, such as corrupted storage or incorrect | |
103 // parameters. Callers MUST check that the returned value is not-null EVERY | |
104 // TIME before accessing it or risk crashing! Once dereferenced, the pointer | |
105 // is safe to reuse forever. | |
106 // | |
107 // NOTE: Though this method will guarantee that an object of the specified | |
108 // type can be accessed without going outside the bounds of the memory | |
109 // segment, it makes no guarantees of the validity of the data within the | |
110 // object itself. If it is expected that the contents of the segment could | |
111 // be compromised with malicious intent, the object must be hardened as well. | |
112 template <typename T> | |
113 T* GetAsObject(Reference ref, uint32_t type_id) { | |
114 // Though the persistent data may be "volatile" in that it is shared with | |
115 // other processes, it is not necessarily the case. The internal | |
116 // "volatile" designation is discarded here so as to not propagate the | |
117 // viral nature of that keyword to the caller. | |
118 return const_cast<T*>( | |
119 reinterpret_cast<volatile T*>(GetBlockData(ref, type_id, sizeof(T)))); | |
120 } | |
121 | |
122 // Get the number of bytes allocated to a block. This is useful when storing | |
123 // arrays in order to validate the ending boundary. The returned value will | |
124 // include any padding added to achieve the required alignment and so could | |
125 // be larger than given in the original Allocate() request. | |
126 size_t GetAllocSize(Reference ref); | |
127 | |
128 // Access the internal "type" of an object. This generally isn't necessary | |
129 // but can be used to "clear" the type and so effectively mark it as deleted | |
130 // even though the memory stays valid and allocated. | |
131 uint32_t GetType(Reference ref); | |
132 void SetType(Reference ref, uint32_t type_id); | |
133 | |
134 // Reserve space in the memory segment of the desired |size| and |type_id|. | |
135 // A return value of zero indicates the allocation failed, otherwise the | |
136 // returned reference can be used by any process to get a real pointer via | |
137 // the GetAsObject() call. | |
138 Reference Allocate(size_t size, uint32_t type_id); | |
139 | |
140 // Allocated objects can be added to an internal list that can then be | |
141 // iterated over by other processes. If an allocated object can be found | |
142 // another way, such as by having its reference within a different object | |
143 // that will be made iterable, then this call is not necessary. This always | |
144 // succeeds unless corruption is detected; check IsCorrupted() to find out. | |
145 void MakeIterable(Reference ref); | |
146 | |
147 // Get the information about the amount of free space in the allocator. The | |
148 // amount of free space should be treated as approximate due to extras from | |
149 // alignment and metadata. Concurrent allocations from other threads will | |
150 // also make the true amount less than what is reported. | |
151 void GetMemoryInfo(MemoryInfo* meminfo); | |
152 | |
153 // Iterating uses a |state| structure (initialized by CreateIterator) and | |
154 // returns both the reference to the object as well as the |type_id| of | |
155 // that object. A zero return value indicates there are currently no more | |
156 // objects to be found but future attempts can be made without having to | |
157 // reset the iterator to "first". | |
158 void CreateIterator(Iterator* state); | |
159 Reference GetNextIterable(Iterator* state, uint32_t* type_id); | |
160 | |
161 // If there is some indication that the memory has become corrupted, | |
162 // calling this will attempt to prevent further damage by indicating to | |
163 // all processes that something is not as expected. | |
164 void SetCorrupt(); | |
165 | |
166 // This can be called to determine if corruption has been detected in the | |
167 // segment, possibly my a malicious actor. Once detected, future allocations | |
168 // will fail and iteration may not locate all objects. | |
169 bool IsCorrupt(); | |
170 | |
171 // Flag set if an allocation has failed because the memory segment was full. | |
172 bool IsFull(); | |
173 | |
174 // Update static-state histograms. This should be called on a periodic basis | |
175 // to record such things as how much of the total space is used. | |
176 void UpdateStaticHistograms(); | |
177 | |
178 protected: | |
179 volatile char* const mem_base_; // Memory base. (char so sizeof guaranteed 1) | |
180 const uint32_t mem_size_; // Size of entire memory segment. | |
181 const uint32_t mem_page_; // Page size allocations shouldn't cross. | |
182 | |
183 private: | |
184 struct SharedMetadata; | |
185 struct BlockHeader; | |
186 static const Reference kReferenceQueue; | |
187 static const Reference kReferenceNull; | |
188 | |
189 // The shared metadata is always located at the top of the memory segment. | |
190 // This convenience function eliminates constant casting of the base pointer | |
191 // within the code. | |
192 volatile SharedMetadata* shared_meta() { | |
193 return reinterpret_cast<volatile SharedMetadata*>(mem_base_); | |
194 } | |
195 | |
196 volatile BlockHeader* GetBlock(Reference ref, uint32_t type_id, uint32_t size, | |
197 bool queue_ok, bool free_ok); | |
198 volatile void* GetBlockData(Reference ref, uint32_t type_id, uint32_t size); | |
199 | |
200 std::atomic<bool> corrupt_; // Local version of "corrupted" flag. | |
201 | |
202 HistogramBase* allocs_histogram_; // Histogram recording allocs. | |
203 HistogramBase* used_histogram_; // Histogram recording used space. | |
204 | |
205 FRIEND_TEST_ALL_PREFIXES(PersistentMemoryAllocatorTest, AllocateAndIterate); | |
206 DISALLOW_COPY_AND_ASSIGN(PersistentMemoryAllocator); | |
207 }; | |
208 | |
209 | |
210 // This allocator uses a local memory block it allocates from the general | |
211 // heap. It is generally used when some kind of "death rattle" handler will | |
212 // save the contents to persistent storage during process shutdown. It is | |
213 // also useful for testing. | |
214 class BASE_EXPORT LocalPersistentMemoryAllocator | |
215 : public PersistentMemoryAllocator { | |
216 public: | |
217 LocalPersistentMemoryAllocator(size_t size, const std::string& name); | |
218 ~LocalPersistentMemoryAllocator(); | |
219 | |
220 private: | |
221 DISALLOW_COPY_AND_ASSIGN(LocalPersistentMemoryAllocator); | |
222 }; | |
223 | |
224 } // namespace base | |
225 | |
226 #endif // BASE_MEMORY_PERSISTENT_MEMORY_ALLOCATOR_H_ | |
OLD | NEW |