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_SHARED_MEMORY_H_
6 #define BASE_SHARED_MEMORY_H_
9 #include "build/build_config.h"
15 #include <sys/types.h>
16 #include <semaphore.h>
19 #include "base/base_export.h"
20 #include "base/basictypes.h"
21 #include "base/process.h"
24 #include "base/file_descriptor_posix.h"
31 // SharedMemoryHandle is a platform specific type which represents
32 // the underlying OS handle to a shared memory segment.
34 typedef HANDLE SharedMemoryHandle
;
35 typedef HANDLE SharedMemoryLock
;
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
;
41 // On POSIX, the lock is implemented as a lockf() on the mapped file,
42 // so no additional member (or definition of SharedMemoryLock) is
46 // Options for creating a shared memory object.
47 struct SharedMemoryCreateOptions
{
48 SharedMemoryCreateOptions() : name(NULL
), size(0), open_existing(false),
51 // If NULL, the object is anonymous. This pointer is owned by the caller
52 // and must live through the call to Create().
53 const std::string
* name
;
55 // Size of the shared memory object to be created.
56 // When opening an existing object, this has no effect.
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 name is
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 Lock() to acquire the named mutex before either Create or Open
78 // 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.
84 SharedMemory(SharedMemoryHandle handle
, bool read_only
);
86 // Create a new SharedMemory object from an existing, open
87 // shared memory file that was created by a remote process and not shared
88 // to the current process.
89 SharedMemory(SharedMemoryHandle handle
, bool read_only
,
90 ProcessHandle process
);
92 // Closes any open files.
95 // Return true iff the given handle is valid (i.e. not the distingished
96 // invalid value; NULL for a HANDLE and -1 for a file descriptor)
97 static bool IsHandleValid(const SharedMemoryHandle
& handle
);
99 // Returns invalid handle (see comment above for exact definition).
100 static SharedMemoryHandle
NULLHandle();
102 // Closes a shared memory handle.
103 static void CloseHandle(const SharedMemoryHandle
& handle
);
105 // Creates a shared memory object as described by the options struct.
106 // Returns true on success and false on failure.
107 bool Create(const SharedMemoryCreateOptions
& options
);
109 // Creates and maps an anonymous shared memory segment of size size.
110 // Returns true on success and false on failure.
111 bool CreateAndMapAnonymous(uint32 size
);
113 // Creates an anonymous shared memory segment of size size.
114 // Returns true on success and false on failure.
115 bool CreateAnonymous(uint32 size
) {
116 SharedMemoryCreateOptions options
;
118 return Create(options
);
121 // Creates or opens a shared memory segment based on a name.
122 // If open_existing is true, and the shared memory already exists,
123 // opens the existing shared memory and ignores the size parameter.
124 // If open_existing is false, shared memory must not exist.
125 // size is the size of the block to be created.
126 // Returns true on success, false on failure.
127 bool CreateNamed(const std::string
& name
, bool open_existing
, uint32 size
) {
128 SharedMemoryCreateOptions options
;
129 options
.name
= &name
;
130 options
.open_existing
= open_existing
;
132 return Create(options
);
135 // Deletes resources associated with a shared memory segment based on name.
136 // Not all platforms require this call.
137 bool Delete(const std::string
& name
);
139 // Opens a shared memory segment based on a name.
140 // If read_only is true, opens for read-only access.
141 // Returns true on success, false on failure.
142 bool Open(const std::string
& name
, bool read_only
);
144 // Maps the shared memory into the caller's address space.
145 // Returns true on success, false otherwise. The memory address
146 // is accessed via the memory() accessor.
147 bool Map(uint32 bytes
);
149 // Unmaps the shared memory from the caller's address space.
150 // Returns true if successful; returns false on error or if the
151 // memory is not mapped.
154 // Get the size of the shared memory backing file.
155 // Note: This size is only available to the creator of the
156 // shared memory, and not to those that opened shared memory
157 // created externally.
158 // Returns 0 if not created or unknown.
159 // Deprecated method, please keep track of the size yourself if you created
161 // http://crbug.com/60821
162 uint32
created_size() const { return created_size_
; }
164 // Gets a pointer to the opened memory space if it has been
165 // Mapped via Map(). Returns NULL if it is not mapped.
166 void *memory() const { return memory_
; }
168 // Returns the underlying OS handle for this segment.
169 // Use of this handle for anything other than an opaque
170 // identifier is not portable.
171 SharedMemoryHandle
handle() const;
173 #if defined(OS_POSIX)
174 // Returns a unique identifier for this shared memory segment. Inode numbers
175 // are technically only unique to a single filesystem. However, we always
176 // allocate shared memory backing files from the same directory, so will end
177 // up on the same filesystem.
178 SharedMemoryId
id() const { return inode_
; }
181 // Closes the open shared memory segment.
182 // It is safe to call Close repeatedly.
185 // Shares the shared memory to another process. Attempts
186 // to create a platform-specific new_handle which can be
187 // used in a remote process to access the shared memory
188 // file. new_handle is an ouput parameter to receive
189 // the handle for use in the remote process.
190 // Returns true on success, false otherwise.
191 bool ShareToProcess(ProcessHandle process
,
192 SharedMemoryHandle
* new_handle
) {
193 return ShareToProcessCommon(process
, new_handle
, false);
196 // Logically equivalent to:
197 // bool ok = ShareToProcess(process, new_handle);
200 // Note that the memory is unmapped by calling this method, regardless of the
202 bool GiveToProcess(ProcessHandle process
,
203 SharedMemoryHandle
* new_handle
) {
204 return ShareToProcessCommon(process
, new_handle
, true);
207 // Locks the shared memory.
209 // WARNING: on POSIX the memory locking primitive only works across
210 // processes, not across threads. The Lock method is not currently
211 // used in inner loops, so we protect against multiple threads in a
212 // critical section using a class global lock.
216 // A Lock() implementation with a timeout that also allows setting
217 // security attributes on the mutex. sec_attr may be NULL.
218 // Returns true if the Lock() has been acquired, false if the timeout was
220 bool Lock(uint32 timeout_ms
, SECURITY_ATTRIBUTES
* sec_attr
);
223 // Releases the shared memory lock.
227 #if defined(OS_POSIX)
228 bool PrepareMapFile(FILE *fp
);
229 bool FilePathForMemoryName(const std::string
& mem_name
, FilePath
* path
);
230 void LockOrUnlockCommon(int function
);
232 bool ShareToProcessCommon(ProcessHandle process
,
233 SharedMemoryHandle
* new_handle
,
239 #elif defined(OS_POSIX)
246 uint32 created_size_
;
247 #if !defined(OS_POSIX)
248 SharedMemoryLock lock_
;
251 DISALLOW_COPY_AND_ASSIGN(SharedMemory
);
254 // A helper class that acquires the shared memory lock while
255 // the SharedMemoryAutoLock is in scope.
256 class SharedMemoryAutoLock
{
258 explicit SharedMemoryAutoLock(SharedMemory
* shared_memory
)
259 : shared_memory_(shared_memory
) {
260 shared_memory_
->Lock();
263 ~SharedMemoryAutoLock() {
264 shared_memory_
->Unlock();
268 SharedMemory
* shared_memory_
;
269 DISALLOW_COPY_AND_ASSIGN(SharedMemoryAutoLock
);
274 #endif // BASE_SHARED_MEMORY_H_