1 // Copyright (c) 2012 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.
5 #ifndef BASE_MEMORY_SHARED_MEMORY_H_
6 #define BASE_MEMORY_SHARED_MEMORY_H_
8 #include "build/build_config.h"
14 #include <sys/types.h>
15 #include <semaphore.h>
18 #include "base/base_export.h"
19 #include "base/basictypes.h"
20 #include "base/process/process_handle.h"
23 #include "base/file_descriptor_posix.h"
24 #include "base/files/file_util.h"
25 #include "base/files/scoped_file.h"
32 // SharedMemoryHandle is a platform specific type which represents
33 // the underlying OS handle to a shared memory segment.
35 typedef HANDLE SharedMemoryHandle
;
36 #elif defined(OS_POSIX)
37 // A SharedMemoryId is sufficient to identify a given shared memory segment on a
38 // system, but insufficient to map it.
39 typedef FileDescriptor SharedMemoryHandle
;
40 typedef ino_t SharedMemoryId
;
43 // Options for creating a shared memory object.
44 struct SharedMemoryCreateOptions
{
45 SharedMemoryCreateOptions()
46 : name_deprecated(NULL
),
48 open_existing_deprecated(false),
50 share_read_only(false) {}
52 // DEPRECATED (crbug.com/345734):
53 // If NULL, the object is anonymous. This pointer is owned by the caller
54 // and must live through the call to Create().
55 const std::string
* name_deprecated
;
57 // Size of the shared memory object to be created.
58 // When opening an existing object, this has no effect.
61 // DEPRECATED (crbug.com/345734):
62 // If true, and the shared memory already exists, Create() will open the
63 // existing shared memory and ignore the size parameter. If false,
64 // shared memory must not exist. This flag is meaningless unless
65 // name_deprecated is non-NULL.
66 bool open_existing_deprecated
;
68 // If true, mappings might need to be made executable later.
71 // If true, the file can be shared read-only to a process.
75 // Platform abstraction for shared memory. Provides a C++ wrapper
76 // around the OS primitive for a memory mapped file.
77 class BASE_EXPORT SharedMemory
{
82 // Similar to the default constructor, except that this allows for
83 // calling LockDeprecated() to acquire the named mutex before either Create or
84 // Open are called on Windows.
85 explicit SharedMemory(const std::wstring
& name
);
88 // Create a new SharedMemory object from an existing, open
89 // shared memory file.
91 // WARNING: This does not reduce the OS-level permissions on the handle; it
92 // only affects how the SharedMemory will be mmapped. Use
93 // ShareReadOnlyToProcess to drop permissions. TODO(jln,jyasskin): DCHECK
94 // that |read_only| matches the permissions of the handle.
95 SharedMemory(SharedMemoryHandle handle
, bool read_only
);
97 // Create a new SharedMemory object from an existing, open
98 // shared memory file that was created by a remote process and not shared
99 // to the current process.
100 SharedMemory(SharedMemoryHandle handle
, bool read_only
,
101 ProcessHandle process
);
103 // Closes any open files.
106 // Return true iff the given handle is valid (i.e. not the distingished
107 // invalid value; NULL for a HANDLE and -1 for a file descriptor)
108 static bool IsHandleValid(const SharedMemoryHandle
& handle
);
110 // Returns invalid handle (see comment above for exact definition).
111 static SharedMemoryHandle
NULLHandle();
113 // Closes a shared memory handle.
114 static void CloseHandle(const SharedMemoryHandle
& handle
);
116 // Returns the maximum number of handles that can be open at once per process.
117 static size_t GetHandleLimit();
119 // Creates a shared memory object as described by the options struct.
120 // Returns true on success and false on failure.
121 bool Create(const SharedMemoryCreateOptions
& options
);
123 // Creates and maps an anonymous shared memory segment of size size.
124 // Returns true on success and false on failure.
125 bool CreateAndMapAnonymous(size_t size
);
127 // Creates an anonymous shared memory segment of size size.
128 // Returns true on success and false on failure.
129 bool CreateAnonymous(size_t size
) {
130 SharedMemoryCreateOptions options
;
132 return Create(options
);
135 // DEPRECATED (crbug.com/345734):
136 // Creates or opens a shared memory segment based on a name.
137 // If open_existing is true, and the shared memory already exists,
138 // opens the existing shared memory and ignores the size parameter.
139 // If open_existing is false, shared memory must not exist.
140 // size is the size of the block to be created.
141 // Returns true on success, false on failure.
142 bool CreateNamedDeprecated(
143 const std::string
& name
, bool open_existing
, size_t size
) {
144 SharedMemoryCreateOptions options
;
145 options
.name_deprecated
= &name
;
146 options
.open_existing_deprecated
= open_existing
;
148 return Create(options
);
151 // Deletes resources associated with a shared memory segment based on name.
152 // Not all platforms require this call.
153 bool Delete(const std::string
& name
);
155 // Opens a shared memory segment based on a name.
156 // If read_only is true, opens for read-only access.
157 // Returns true on success, false on failure.
158 bool Open(const std::string
& name
, bool read_only
);
160 // Maps the shared memory into the caller's address space.
161 // Returns true on success, false otherwise. The memory address
162 // is accessed via the memory() accessor. The mapped address is guaranteed to
163 // have an alignment of at least MAP_MINIMUM_ALIGNMENT. This method will fail
164 // if this object is currently mapped.
165 bool Map(size_t bytes
) {
166 return MapAt(0, bytes
);
169 // Same as above, but with |offset| to specify from begining of the shared
170 // memory block to map.
171 // |offset| must be alignent to value of |SysInfo::VMAllocationGranularity()|.
172 bool MapAt(off_t offset
, size_t bytes
);
173 enum { MAP_MINIMUM_ALIGNMENT
= 32 };
175 // Unmaps the shared memory from the caller's address space.
176 // Returns true if successful; returns false on error or if the
177 // memory is not mapped.
180 // The size requested when the map is first created.
181 size_t requested_size() const { return requested_size_
; }
183 // The actual size of the mapped memory (may be larger than requested).
184 size_t mapped_size() const { return mapped_size_
; }
186 // Gets a pointer to the opened memory space if it has been
187 // Mapped via Map(). Returns NULL if it is not mapped.
188 void *memory() const { return memory_
; }
190 // Returns the underlying OS handle for this segment.
191 // Use of this handle for anything other than an opaque
192 // identifier is not portable.
193 SharedMemoryHandle
handle() const;
195 #if defined(OS_POSIX) && !defined(OS_NACL)
196 // Returns a unique identifier for this shared memory segment. Inode numbers
197 // are technically only unique to a single filesystem. However, we always
198 // allocate shared memory backing files from the same directory, so will end
199 // up on the same filesystem.
200 SharedMemoryId
id() const { return inode_
; }
203 // Closes the open shared memory segment.
204 // It is safe to call Close repeatedly.
207 // Shares the shared memory to another process. Attempts to create a
208 // platform-specific new_handle which can be used in a remote process to read
209 // the shared memory file. new_handle is an output parameter to receive the
210 // handle for use in the remote process.
212 // |*this| must have been initialized using one of the Create*() or Open()
213 // methods with share_read_only=true. If it was constructed from a
214 // SharedMemoryHandle, this call will CHECK-fail.
216 // Returns true on success, false otherwise.
217 bool ShareReadOnlyToProcess(ProcessHandle process
,
218 SharedMemoryHandle
* new_handle
) {
219 return ShareToProcessCommon(process
, new_handle
, false, SHARE_READONLY
);
222 // Logically equivalent to:
223 // bool ok = ShareReadOnlyToProcess(process, new_handle);
226 // Note that the memory is unmapped by calling this method, regardless of the
228 bool GiveReadOnlyToProcess(ProcessHandle process
,
229 SharedMemoryHandle
* new_handle
) {
230 return ShareToProcessCommon(process
, new_handle
, true, SHARE_READONLY
);
233 // Shares the shared memory to another process. Attempts
234 // to create a platform-specific new_handle which can be
235 // used in a remote process to access the shared memory
236 // file. new_handle is an output parameter to receive
237 // the handle for use in the remote process.
238 // Returns true on success, false otherwise.
239 bool ShareToProcess(ProcessHandle process
,
240 SharedMemoryHandle
* new_handle
) {
241 return ShareToProcessCommon(process
, new_handle
, false, SHARE_CURRENT_MODE
);
244 // Logically equivalent to:
245 // bool ok = ShareToProcess(process, new_handle);
248 // Note that the memory is unmapped by calling this method, regardless of the
250 bool GiveToProcess(ProcessHandle process
,
251 SharedMemoryHandle
* new_handle
) {
252 return ShareToProcessCommon(process
, new_handle
, true, SHARE_CURRENT_MODE
);
255 // DEPRECATED (crbug.com/345734):
256 // Locks the shared memory.
258 // WARNING: on POSIX the memory locking primitive only works across
259 // processes, not across threads. The LockDeprecated method is not currently
260 // used in inner loops, so we protect against multiple threads in a
261 // critical section using a class global lock.
262 void LockDeprecated();
264 // DEPRECATED (crbug.com/345734):
265 // Releases the shared memory lock.
266 void UnlockDeprecated();
269 #if defined(OS_POSIX) && !defined(OS_NACL)
270 #if !defined(OS_ANDROID)
271 bool PrepareMapFile(ScopedFILE fp
, ScopedFD readonly
);
272 bool FilePathForMemoryName(const std::string
& mem_name
, FilePath
* path
);
274 void LockOrUnlockCommon(int function
);
275 #endif // defined(OS_POSIX) && !defined(OS_NACL)
280 bool ShareToProcessCommon(ProcessHandle process
,
281 SharedMemoryHandle
* new_handle
,
288 #elif defined(OS_POSIX)
290 int readonly_mapped_file_
;
296 size_t requested_size_
;
297 #if !defined(OS_POSIX)
301 DISALLOW_COPY_AND_ASSIGN(SharedMemory
);
304 // DEPRECATED (crbug.com/345734):
305 // A helper class that acquires the shared memory lock while
306 // the SharedMemoryAutoLockDeprecated is in scope.
307 class SharedMemoryAutoLockDeprecated
{
309 explicit SharedMemoryAutoLockDeprecated(SharedMemory
* shared_memory
)
310 : shared_memory_(shared_memory
) {
311 shared_memory_
->LockDeprecated();
314 ~SharedMemoryAutoLockDeprecated() {
315 shared_memory_
->UnlockDeprecated();
319 SharedMemory
* shared_memory_
;
320 DISALLOW_COPY_AND_ASSIGN(SharedMemoryAutoLockDeprecated
);
325 #endif // BASE_MEMORY_SHARED_MEMORY_H_