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/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() : name_deprecated(NULL), size(0),
46 open_existing_deprecated(false),
49 // DEPRECATED (crbug.com/345734):
50 // If NULL, the object is anonymous. This pointer is owned by the caller
51 // and must live through the call to Create().
52 const std::string* name_deprecated;
54 // Size of the shared memory object to be created.
55 // When opening an existing object, this has no effect.
58 // DEPRECATED (crbug.com/345734):
59 // If true, and the shared memory already exists, Create() will open the
60 // existing shared memory and ignore the size parameter. If false,
61 // shared memory must not exist. This flag is meaningless unless
62 // name_deprecated is non-NULL.
63 bool open_existing_deprecated;
65 // If true, mappings might need to be made executable later.
69 // Platform abstraction for shared memory. Provides a C++ wrapper
70 // around the OS primitive for a memory mapped file.
71 class BASE_EXPORT SharedMemory {
76 // Similar to the default constructor, except that this allows for
77 // calling LockDeprecated() to acquire the named mutex before either Create or
78 // Open are called on Windows.
79 explicit SharedMemory(const std::wstring& name);
82 // Create a new SharedMemory object from an existing, open
83 // shared memory file.
85 // WARNING: This does not reduce the OS-level permissions on the handle; it
86 // only affects how the SharedMemory will be mmapped. Use
87 // ShareReadOnlyToProcess to drop permissions. TODO(jln,jyasskin): DCHECK
88 // that |read_only| matches the permissions of the handle.
89 SharedMemory(SharedMemoryHandle handle, bool read_only);
91 // Create a new SharedMemory object from an existing, open
92 // shared memory file that was created by a remote process and not shared
93 // to the current process.
94 SharedMemory(SharedMemoryHandle handle, bool read_only,
95 ProcessHandle process);
97 // Closes any open files.
100 // Return true iff the given handle is valid (i.e. not the distingished
101 // invalid value; NULL for a HANDLE and -1 for a file descriptor)
102 static bool IsHandleValid(const SharedMemoryHandle& handle);
104 // Returns invalid handle (see comment above for exact definition).
105 static SharedMemoryHandle NULLHandle();
107 // Closes a shared memory handle.
108 static void CloseHandle(const SharedMemoryHandle& handle);
110 // Returns the maximum number of handles that can be open at once per process.
111 static size_t GetHandleLimit();
113 // Creates a shared memory object as described by the options struct.
114 // Returns true on success and false on failure.
115 bool Create(const SharedMemoryCreateOptions& options);
117 // Creates and maps an anonymous shared memory segment of size size.
118 // Returns true on success and false on failure.
119 bool CreateAndMapAnonymous(size_t size);
121 // Creates an anonymous shared memory segment of size size.
122 // Returns true on success and false on failure.
123 bool CreateAnonymous(size_t size) {
124 SharedMemoryCreateOptions options;
126 return Create(options);
129 // DEPRECATED (crbug.com/345734):
130 // Creates or opens a shared memory segment based on a name.
131 // If open_existing is true, and the shared memory already exists,
132 // opens the existing shared memory and ignores the size parameter.
133 // If open_existing is false, shared memory must not exist.
134 // size is the size of the block to be created.
135 // Returns true on success, false on failure.
136 bool CreateNamedDeprecated(
137 const std::string& name, bool open_existing, size_t size) {
138 SharedMemoryCreateOptions options;
139 options.name_deprecated = &name;
140 options.open_existing_deprecated = open_existing;
142 return Create(options);
145 // Deletes resources associated with a shared memory segment based on name.
146 // Not all platforms require this call.
147 bool Delete(const std::string& name);
149 // Opens a shared memory segment based on a name.
150 // If read_only is true, opens for read-only access.
151 // Returns true on success, false on failure.
152 bool Open(const std::string& name, bool read_only);
154 // Maps the shared memory into the caller's address space.
155 // Returns true on success, false otherwise. The memory address
156 // is accessed via the memory() accessor. The mapped address is guaranteed to
157 // have an alignment of at least MAP_MINIMUM_ALIGNMENT. This method will fail
158 // if this object is currently mapped.
159 bool Map(size_t bytes) {
160 return MapAt(0, bytes);
163 // Same as above, but with |offset| to specify from begining of the shared
164 // memory block to map.
165 // |offset| must be alignent to value of |SysInfo::VMAllocationGranularity()|.
166 bool MapAt(off_t offset, size_t bytes);
167 enum { MAP_MINIMUM_ALIGNMENT = 32 };
169 // Unmaps the shared memory from the caller's address space.
170 // Returns true if successful; returns false on error or if the
171 // memory is not mapped.
174 // The size requested when the map is first created.
175 size_t requested_size() const { return requested_size_; }
177 // The actual size of the mapped memory (may be larger than requested).
178 size_t mapped_size() const { return mapped_size_; }
180 // Gets a pointer to the opened memory space if it has been
181 // Mapped via Map(). Returns NULL if it is not mapped.
182 void *memory() const { return memory_; }
184 // Returns the underlying OS handle for this segment.
185 // Use of this handle for anything other than an opaque
186 // identifier is not portable.
187 SharedMemoryHandle handle() const;
189 #if defined(OS_POSIX) && !defined(OS_NACL)
190 // Returns a unique identifier for this shared memory segment. Inode numbers
191 // are technically only unique to a single filesystem. However, we always
192 // allocate shared memory backing files from the same directory, so will end
193 // up on the same filesystem.
194 SharedMemoryId id() const { return inode_; }
197 // Closes the open shared memory segment.
198 // It is safe to call Close repeatedly.
201 // Shares the shared memory to another process. Attempts to create a
202 // platform-specific new_handle which can be used in a remote process to read
203 // the shared memory file. new_handle is an output parameter to receive the
204 // handle for use in the remote process.
206 // |*this| must have been initialized using one of the Create*() or Open()
207 // methods. If it was constructed from a SharedMemoryHandle, this call will
210 // Returns true on success, false otherwise.
211 bool ShareReadOnlyToProcess(ProcessHandle process,
212 SharedMemoryHandle* new_handle) {
213 return ShareToProcessCommon(process, new_handle, false, SHARE_READONLY);
216 // Logically equivalent to:
217 // bool ok = ShareReadOnlyToProcess(process, new_handle);
220 // Note that the memory is unmapped by calling this method, regardless of the
222 bool GiveReadOnlyToProcess(ProcessHandle process,
223 SharedMemoryHandle* new_handle) {
224 return ShareToProcessCommon(process, new_handle, true, SHARE_READONLY);
227 // Shares the shared memory to another process. Attempts
228 // to create a platform-specific new_handle which can be
229 // used in a remote process to access the shared memory
230 // file. new_handle is an output parameter to receive
231 // the handle for use in the remote process.
232 // Returns true on success, false otherwise.
233 bool ShareToProcess(ProcessHandle process,
234 SharedMemoryHandle* new_handle) {
235 return ShareToProcessCommon(process, new_handle, false, SHARE_CURRENT_MODE);
238 // Logically equivalent to:
239 // bool ok = ShareToProcess(process, new_handle);
242 // Note that the memory is unmapped by calling this method, regardless of the
244 bool GiveToProcess(ProcessHandle process,
245 SharedMemoryHandle* new_handle) {
246 return ShareToProcessCommon(process, new_handle, true, SHARE_CURRENT_MODE);
249 // DEPRECATED (crbug.com/345734):
250 // Locks the shared memory.
252 // WARNING: on POSIX the memory locking primitive only works across
253 // processes, not across threads. The LockDeprecated method is not currently
254 // used in inner loops, so we protect against multiple threads in a
255 // critical section using a class global lock.
256 void LockDeprecated();
258 // DEPRECATED (crbug.com/345734):
259 // Releases the shared memory lock.
260 void UnlockDeprecated();
263 #if defined(OS_POSIX) && !defined(OS_NACL)
264 #if !defined(OS_ANDROID)
265 bool PrepareMapFile(ScopedFILE fp, ScopedFD readonly);
266 bool FilePathForMemoryName(const std::string& mem_name, FilePath* path);
268 void LockOrUnlockCommon(int function);
269 #endif // defined(OS_POSIX) && !defined(OS_NACL)
274 bool ShareToProcessCommon(ProcessHandle process,
275 SharedMemoryHandle* new_handle,
282 #elif defined(OS_POSIX)
284 int readonly_mapped_file_;
290 size_t requested_size_;
291 #if !defined(OS_POSIX)
295 DISALLOW_COPY_AND_ASSIGN(SharedMemory);
298 // DEPRECATED (crbug.com/345734):
299 // A helper class that acquires the shared memory lock while
300 // the SharedMemoryAutoLockDeprecated is in scope.
301 class SharedMemoryAutoLockDeprecated {
303 explicit SharedMemoryAutoLockDeprecated(SharedMemory* shared_memory)
304 : shared_memory_(shared_memory) {
305 shared_memory_->LockDeprecated();
308 ~SharedMemoryAutoLockDeprecated() {
309 shared_memory_->UnlockDeprecated();
313 SharedMemory* shared_memory_;
314 DISALLOW_COPY_AND_ASSIGN(SharedMemoryAutoLockDeprecated);
319 #endif // BASE_MEMORY_SHARED_MEMORY_H_