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" | |
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 | |
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 int32_t Reference; | |
47 | |
48 // Internal state information when iterating over memory allocations. | |
49 struct Iterator { | |
50 Reference last; | |
51 uint32_t niter; | |
52 }; | |
53 | |
54 // Returned information about the internal state of the heap. | |
55 struct MemoryInfo { | |
56 size_t total; | |
57 size_t free; | |
58 }; | |
59 | |
60 enum : uint32_t { | |
61 kTypeIdAny = 0 // Match any type-id inside GetAsObject(). | |
62 }; | |
63 | |
64 // The allocator operates on any arbitrary block of memory. Creation and | |
65 // persisting or sharing of that block with another process is the | |
66 // responsibility of the caller. The allocator needs to know only the | |
67 // block's |base| address, the total |size| of the block, and any internal | |
68 // |page| size (zero if not paged) across which allocations should not span. | |
69 // The |name|, if provided, is used to distinguish histograms for this | |
70 // allocator. Only the primary owner of the segment should define this value; | |
71 // other processes can learn it from the shared state. | |
72 // | |
73 // PersistentMemoryAllocator does NOT take ownership of the memory block. | |
74 // The caller must manage it and ensure it stays available throughout the | |
75 // lifetime of this object. | |
76 // | |
77 // Memory segments for sharing must have had an allocator attached to them | |
78 // before actually being shared. If the memory segment was just created, it | |
79 // should be zeroed before being passed here. If it was an existing segment, | |
80 // the values here will be compared to copies stored in the shared segment | |
81 // as a guard against corruption. | |
82 PersistentMemoryAllocator(void* base, size_t size, size_t page_size, | |
83 const std::string& name); | |
84 ~PersistentMemoryAllocator(); | |
85 | |
86 // Get an object referenced by a |ref|. For safety reasons, the |type_id| | |
87 // code and size-of(|T|) are compared to ensure the reference is valid | |
88 // and cannot return an object outside of the memory segment. A |type_id| of | |
89 // zero will match any though the size is still checked. NULL is returned | |
90 // if any problem is detected, such as corrupted storage or incorrect | |
91 // parameters. Callers MUST check that the returned value is not-null EVERY | |
92 // TIME before accessing it or risk crashing! Once dereferenced, the pointer | |
93 // is safe to reuse forever. | |
94 // | |
95 // NOTE: Though this method will guarantee that an object of the specified | |
96 // type can be accessed without going outside the bounds of the memory | |
97 // segment, it makes no guarantees of the validity of the data within the | |
98 // object itself. If it is expected that the contents of the segment could | |
99 // be compromised with malicious intent, the object must be hardened as well. | |
100 template <typename T> | |
101 T* GetAsObject(Reference ref, uint32_t type_id) { | |
102 // Though the persistent data may be "volatile" in that it is shared with | |
103 // other processes, it is not necessarily the case. The internaal | |
JF
2015/11/20 20:43:31
typo "internaal"
bcwhite
2015/11/23 16:48:22
Done.
| |
104 // "volatile" designation is discarded here so as to not propagate the | |
105 // viral nature of that keyword to the caller. | |
106 return const_cast<T*>( | |
107 reinterpret_cast<volatile T*>(GetBlockData(ref, type_id, sizeof(T)))); | |
JF
2015/11/20 20:43:31
I'm not sure I understand this: is the T* returned
bcwhite
2015/11/20 21:57:05
That is correct. Note that it may or may not be s
| |
108 } | |
109 | |
110 // Get the number of bytes allocated to a block. This is useful when storing | |
111 // arrays in order to validate the ending boundary. The returned value will | |
112 // include any padding added to achieve the required alignment and so could | |
113 // be larger than given in the original Allocate() request. | |
114 size_t GetAllocSize(Reference ref); | |
115 | |
116 // Access the internal "type" of an object. This generally isn't necessary | |
117 // but can be used to "clear" the type and so effectively mark it as deleted | |
118 // even though the memory stays valid and allocated. | |
119 uint32_t GetType(Reference ref); | |
120 void SetType(Reference ref, uint32_t type_id); | |
121 | |
122 // Reserve space in the memory segment of the desired |size| and |type_id|. | |
123 // A return value of zero indicates the allocation failed, otherwise the | |
124 // returned reference can be used by any process to get a real pointer via | |
125 // the GetAsObject() call. | |
126 int32_t Allocate(size_t size, uint32_t type_id); | |
127 | |
128 // Allocated objects can be added to an internal list that can then be | |
129 // iterated over by other processes. If an allocated object can be found | |
130 // another way, such as by having its reference within a different object | |
131 // that will be made iterable, then this call is not necessary. This always | |
132 // succeeds unless corruption is detected; check IsCorrupted() to find out. | |
133 void MakeIterable(Reference ref); | |
134 | |
135 // Get the information about the amount of free space in the allocator. The | |
136 // amount of free space should be treated as approximate due to extras from | |
137 // alignment and metadata. Concurrent allocations from other threads will | |
138 // also make the true amount less than what is reported. | |
139 void GetMemoryInfo(MemoryInfo* meminfo); | |
140 | |
141 // Iterating uses a |state| structure (initialized by CreateIterator) and | |
142 // returns both the reference to the object as well as the |type_id| of | |
143 // that object. A zero return value indicates there are currently no more | |
144 // objects to be found but future attempts can be made without having to | |
145 // reset the iterator to "first". | |
146 void CreateIterator(Iterator* state); | |
147 int32_t GetNextIterable(Iterator* state, uint32_t* type_id); | |
148 | |
149 // If there is some indication that the memory has become corrupted, | |
150 // calling this will attempt to prevent further damage by indicating to | |
151 // all processes that something is not as expected. | |
152 void SetCorrupt(); | |
153 | |
154 // This can be called to determine if corruption has been detected in the | |
155 // segment, possibly my a malicious actor. Once detected, future allocations | |
156 // will fail and iteration may not locate all objects. | |
157 bool IsCorrupt(); | |
158 | |
159 // Flag set if an allocation has failed because the memory segment was full. | |
160 bool IsFull(); | |
161 | |
162 // Update static-state histograms. This should be called on a periodic basis | |
163 // to record such things as how much of the total space is used. | |
164 void UpdateStaticHistograms(); | |
165 | |
166 protected: | |
167 volatile char* const mem_base_; // Memory base. (char so sizeof guaranteed 1) | |
168 const int32_t mem_size_; // Size of entire memory segment. | |
169 const int32_t mem_page_; // Page size allocations shouldn't cross. | |
170 | |
171 private: | |
172 struct SharedMetadata; | |
173 struct BlockHeader; | |
174 static const Reference kReferenceQueue; | |
175 static const Reference kReferenceNull; | |
176 | |
177 // The shared metadata is always located at the top of the memory segment. | |
178 // This convenience function eliminates constant casting of the base pointer | |
179 // within the code. | |
180 volatile SharedMetadata* shared_meta() { | |
181 return reinterpret_cast<volatile SharedMetadata*>(mem_base_); | |
182 } | |
183 | |
184 volatile BlockHeader* GetBlock(Reference ref, uint32_t type_id, int32_t size, | |
185 bool queue_ok, bool free_ok); | |
186 volatile void* GetBlockData(Reference ref, uint32_t type_id, int32_t size); | |
187 | |
188 std::atomic<bool> corrupt_; // Local version of "corrupted" flag. | |
189 | |
190 HistogramBase* allocs_histogram_; // Histogram recording allocs. | |
191 HistogramBase* used_histogram_; // Histogram recording used space. | |
192 | |
193 FRIEND_TEST_ALL_PREFIXES(PersistentMemoryAllocatorTest, AllocateAndIterate); | |
194 DISALLOW_COPY_AND_ASSIGN(PersistentMemoryAllocator); | |
195 }; | |
196 | |
197 | |
198 // This allocator uses a local memory block it allocates from the general | |
199 // heap. It is generally used when some kind of "death rattle" handler will | |
200 // save the contents to persistent storage during process shutdown. It is | |
201 // also useful for testing. | |
202 class BASE_EXPORT LocalPersistentMemoryAllocator | |
203 : public PersistentMemoryAllocator { | |
204 public: | |
205 LocalPersistentMemoryAllocator(size_t size, const std::string& name); | |
206 ~LocalPersistentMemoryAllocator(); | |
207 | |
208 private: | |
209 DISALLOW_COPY_AND_ASSIGN(LocalPersistentMemoryAllocator); | |
210 }; | |
211 | |
212 } // namespace base | |
213 | |
214 #endif // BASE_MEMORY_PERSISTENT_MEMORY_ALLOCATOR_H_ | |
OLD | NEW |