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 typedef FileDescriptor SharedMemoryHandle
;
40 // Options for creating a shared memory object.
41 struct SharedMemoryCreateOptions
{
42 SharedMemoryCreateOptions()
43 : name_deprecated(NULL
),
45 open_existing_deprecated(false),
47 share_read_only(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.
68 // If true, the file can be shared read-only to a process.
72 // Platform abstraction for shared memory. Provides a C++ wrapper
73 // around the OS primitive for a memory mapped file.
74 class BASE_EXPORT SharedMemory
{
79 // Similar to the default constructor, except that this allows for
80 // calling LockDeprecated() to acquire the named mutex before either Create or
81 // Open are called on Windows.
82 explicit SharedMemory(const std::wstring
& name
);
85 // Create a new SharedMemory object from an existing, open
86 // shared memory file.
88 // WARNING: This does not reduce the OS-level permissions on the handle; it
89 // only affects how the SharedMemory will be mmapped. Use
90 // ShareReadOnlyToProcess to drop permissions. TODO(jln,jyasskin): DCHECK
91 // that |read_only| matches the permissions of the handle.
92 SharedMemory(SharedMemoryHandle handle
, bool read_only
);
94 // Create a new SharedMemory object from an existing, open
95 // shared memory file that was created by a remote process and not shared
96 // to the current process.
97 SharedMemory(SharedMemoryHandle handle
, bool read_only
,
98 ProcessHandle process
);
100 // Closes any open files.
103 // Return true iff the given handle is valid (i.e. not the distingished
104 // invalid value; NULL for a HANDLE and -1 for a file descriptor)
105 static bool IsHandleValid(const SharedMemoryHandle
& handle
);
107 // Returns invalid handle (see comment above for exact definition).
108 static SharedMemoryHandle
NULLHandle();
110 // Closes a shared memory handle.
111 static void CloseHandle(const SharedMemoryHandle
& handle
);
113 // Returns the maximum number of handles that can be open at once per process.
114 static size_t GetHandleLimit();
116 // Duplicates The underlying OS primitive. Returns NULLHandle() on failure.
117 // The caller is responsible for destroying the duplicated OS primitive.
118 static SharedMemoryHandle
DuplicateHandle(const SharedMemoryHandle
& handle
);
120 #if defined(OS_POSIX)
121 // This method requires that the SharedMemoryHandle is backed by a POSIX fd.
122 static int GetFdFromSharedMemoryHandle(const SharedMemoryHandle
& handle
);
125 #if defined(OS_POSIX) && !defined(OS_ANDROID)
126 // Returns the size of the shared memory region referred to by |handle|.
127 // Returns '-1' on a failure to determine the size.
128 static int GetSizeFromSharedMemoryHandle(const SharedMemoryHandle
& handle
);
129 #endif // defined(OS_POSIX) && !defined(OS_ANDROID)
131 // Creates a shared memory object as described by the options struct.
132 // Returns true on success and false on failure.
133 bool Create(const SharedMemoryCreateOptions
& options
);
135 // Creates and maps an anonymous shared memory segment of size size.
136 // Returns true on success and false on failure.
137 bool CreateAndMapAnonymous(size_t size
);
139 // Creates an anonymous shared memory segment of size size.
140 // Returns true on success and false on failure.
141 bool CreateAnonymous(size_t size
) {
142 SharedMemoryCreateOptions options
;
144 return Create(options
);
147 // DEPRECATED (crbug.com/345734):
148 // Creates or opens a shared memory segment based on a name.
149 // If open_existing is true, and the shared memory already exists,
150 // opens the existing shared memory and ignores the size parameter.
151 // If open_existing is false, shared memory must not exist.
152 // size is the size of the block to be created.
153 // Returns true on success, false on failure.
154 bool CreateNamedDeprecated(
155 const std::string
& name
, bool open_existing
, size_t size
) {
156 SharedMemoryCreateOptions options
;
157 options
.name_deprecated
= &name
;
158 options
.open_existing_deprecated
= open_existing
;
160 return Create(options
);
163 // Deletes resources associated with a shared memory segment based on name.
164 // Not all platforms require this call.
165 bool Delete(const std::string
& name
);
167 // Opens a shared memory segment based on a name.
168 // If read_only is true, opens for read-only access.
169 // Returns true on success, false on failure.
170 bool Open(const std::string
& name
, bool read_only
);
172 // Maps the shared memory into the caller's address space.
173 // Returns true on success, false otherwise. The memory address
174 // is accessed via the memory() accessor. The mapped address is guaranteed to
175 // have an alignment of at least MAP_MINIMUM_ALIGNMENT. This method will fail
176 // if this object is currently mapped.
177 bool Map(size_t bytes
) {
178 return MapAt(0, bytes
);
181 // Same as above, but with |offset| to specify from begining of the shared
182 // memory block to map.
183 // |offset| must be alignent to value of |SysInfo::VMAllocationGranularity()|.
184 bool MapAt(off_t offset
, size_t bytes
);
185 enum { MAP_MINIMUM_ALIGNMENT
= 32 };
187 // Unmaps the shared memory from the caller's address space.
188 // Returns true if successful; returns false on error or if the
189 // memory is not mapped.
192 // The size requested when the map is first created.
193 size_t requested_size() const { return requested_size_
; }
195 // The actual size of the mapped memory (may be larger than requested).
196 size_t mapped_size() const { return mapped_size_
; }
198 // Gets a pointer to the opened memory space if it has been
199 // Mapped via Map(). Returns NULL if it is not mapped.
200 void *memory() const { return memory_
; }
202 // Returns the underlying OS handle for this segment.
203 // Use of this handle for anything other than an opaque
204 // identifier is not portable.
205 SharedMemoryHandle
handle() const;
207 // Closes the open shared memory segment. The memory will remain mapped if
208 // it was previously mapped.
209 // It is safe to call Close repeatedly.
212 // Shares the shared memory to another process. Attempts to create a
213 // platform-specific new_handle which can be used in a remote process to read
214 // the shared memory file. new_handle is an output parameter to receive the
215 // handle for use in the remote process.
217 // |*this| must have been initialized using one of the Create*() or Open()
218 // methods with share_read_only=true. If it was constructed from a
219 // SharedMemoryHandle, this call will CHECK-fail.
221 // Returns true on success, false otherwise.
222 bool ShareReadOnlyToProcess(ProcessHandle process
,
223 SharedMemoryHandle
* new_handle
) {
224 return ShareToProcessCommon(process
, new_handle
, false, SHARE_READONLY
);
227 // Logically equivalent to:
228 // bool ok = ShareReadOnlyToProcess(process, new_handle);
231 // Note that the memory is unmapped by calling this method, regardless of the
233 bool GiveReadOnlyToProcess(ProcessHandle process
,
234 SharedMemoryHandle
* new_handle
) {
235 return ShareToProcessCommon(process
, new_handle
, true, SHARE_READONLY
);
238 // Shares the shared memory to another process. Attempts
239 // to create a platform-specific new_handle which can be
240 // used in a remote process to access the shared memory
241 // file. new_handle is an output parameter to receive
242 // the handle for use in the remote process.
243 // Returns true on success, false otherwise.
244 bool ShareToProcess(ProcessHandle process
,
245 SharedMemoryHandle
* new_handle
) {
246 return ShareToProcessCommon(process
, new_handle
, false, SHARE_CURRENT_MODE
);
249 // Logically equivalent to:
250 // bool ok = ShareToProcess(process, new_handle);
253 // Note that the memory is unmapped by calling this method, regardless of the
255 bool GiveToProcess(ProcessHandle process
,
256 SharedMemoryHandle
* new_handle
) {
257 return ShareToProcessCommon(process
, new_handle
, true, SHARE_CURRENT_MODE
);
261 #if defined(OS_POSIX) && !defined(OS_NACL) && !defined(OS_ANDROID)
262 bool PrepareMapFile(ScopedFILE fp
, ScopedFD readonly
);
263 bool FilePathForMemoryName(const std::string
& mem_name
, FilePath
* path
);
264 #endif // defined(OS_POSIX) && !defined(OS_NACL) && !defined(OS_ANDROID)
269 bool ShareToProcessCommon(ProcessHandle process
,
270 SharedMemoryHandle
* new_handle
,
277 #elif defined(OS_POSIX)
279 int readonly_mapped_file_
;
284 size_t requested_size_
;
286 DISALLOW_COPY_AND_ASSIGN(SharedMemory
);
290 #endif // BASE_MEMORY_SHARED_MEMORY_H_