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/memory/shared_memory_handle.h"
21 #include "base/process/process_handle.h"
24 #include "base/file_descriptor_posix.h"
25 #include "base/files/file_util.h"
26 #include "base/files/scoped_file.h"
33 // Options for creating a shared memory object.
34 struct SharedMemoryCreateOptions
{
35 SharedMemoryCreateOptions()
38 share_read_only(false) {
39 #if !defined(OS_MACOSX)
40 name_deprecated
= nullptr;
41 open_existing_deprecated
= false;
45 #if !defined(OS_MACOSX)
46 // DEPRECATED (crbug.com/345734):
47 // If NULL, the object is anonymous. This pointer is owned by the caller
48 // and must live through the call to Create().
49 const std::string
* name_deprecated
;
52 // Size of the shared memory object to be created.
53 // When opening an existing object, this has no effect.
56 #if !defined(OS_MACOSX)
57 // DEPRECATED (crbug.com/345734):
58 // If true, and the shared memory already exists, Create() will open the
59 // existing shared memory and ignore the size parameter. If false,
60 // shared memory must not exist. This flag is meaningless unless
61 // name_deprecated is non-NULL.
62 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(const 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(const SharedMemoryHandle
& handle
,
99 ProcessHandle process
);
101 // Closes any open files.
104 // Return true iff the given handle is valid (i.e. not the distingished
105 // invalid value; NULL for a HANDLE and -1 for a file descriptor)
106 static bool IsHandleValid(const SharedMemoryHandle
& handle
);
108 // Returns invalid handle (see comment above for exact definition).
109 static SharedMemoryHandle
NULLHandle();
111 // Closes a shared memory handle.
112 static void CloseHandle(const SharedMemoryHandle
& handle
);
114 // Returns the maximum number of handles that can be open at once per process.
115 static size_t GetHandleLimit();
117 // Duplicates The underlying OS primitive. Returns NULLHandle() on failure.
118 // The caller is responsible for destroying the duplicated OS primitive.
119 static SharedMemoryHandle
DuplicateHandle(const SharedMemoryHandle
& handle
);
121 #if defined(OS_POSIX)
122 // This method requires that the SharedMemoryHandle is backed by a POSIX fd.
123 static int GetFdFromSharedMemoryHandle(const SharedMemoryHandle
& handle
);
126 #if defined(OS_POSIX) && !defined(OS_ANDROID)
127 // Returns the size of the shared memory region referred to by |handle|.
128 // Returns '-1' on a failure to determine the size.
129 static int GetSizeFromSharedMemoryHandle(const SharedMemoryHandle
& handle
);
130 #endif // defined(OS_POSIX) && !defined(OS_ANDROID)
132 // Creates a shared memory object as described by the options struct.
133 // Returns true on success and false on failure.
134 bool Create(const SharedMemoryCreateOptions
& options
);
136 // Creates and maps an anonymous shared memory segment of size size.
137 // Returns true on success and false on failure.
138 bool CreateAndMapAnonymous(size_t size
);
140 // Creates an anonymous shared memory segment of size size.
141 // Returns true on success and false on failure.
142 bool CreateAnonymous(size_t size
) {
143 SharedMemoryCreateOptions options
;
145 return Create(options
);
148 #if !defined(OS_MACOSX)
149 // DEPRECATED (crbug.com/345734):
150 // Creates or opens a shared memory segment based on a name.
151 // If open_existing is true, and the shared memory already exists,
152 // opens the existing shared memory and ignores the size parameter.
153 // If open_existing is false, shared memory must not exist.
154 // size is the size of the block to be created.
155 // Returns true on success, false on failure.
156 bool CreateNamedDeprecated(
157 const std::string
& name
, bool open_existing
, size_t size
) {
158 SharedMemoryCreateOptions options
;
159 options
.name_deprecated
= &name
;
160 options
.open_existing_deprecated
= open_existing
;
162 return Create(options
);
165 // Deletes resources associated with a shared memory segment based on name.
166 // Not all platforms require this call.
167 bool Delete(const std::string
& name
);
169 // Opens a shared memory segment based on a name.
170 // If read_only is true, opens for read-only access.
171 // Returns true on success, false on failure.
172 bool Open(const std::string
& name
, bool read_only
);
173 #endif // !defined(OS_MACOSX)
175 // Maps the shared memory into the caller's address space.
176 // Returns true on success, false otherwise. The memory address
177 // is accessed via the memory() accessor. The mapped address is guaranteed to
178 // have an alignment of at least MAP_MINIMUM_ALIGNMENT. This method will fail
179 // if this object is currently mapped.
180 bool Map(size_t bytes
) {
181 return MapAt(0, bytes
);
184 // Same as above, but with |offset| to specify from begining of the shared
185 // memory block to map.
186 // |offset| must be alignent to value of |SysInfo::VMAllocationGranularity()|.
187 bool MapAt(off_t offset
, size_t bytes
);
188 enum { MAP_MINIMUM_ALIGNMENT
= 32 };
190 // Unmaps the shared memory from the caller's address space.
191 // Returns true if successful; returns false on error or if the
192 // memory is not mapped.
195 // The size requested when the map is first created.
196 size_t requested_size() const { return requested_size_
; }
198 // The actual size of the mapped memory (may be larger than requested).
199 size_t mapped_size() const { return mapped_size_
; }
201 // Gets a pointer to the opened memory space if it has been
202 // Mapped via Map(). Returns NULL if it is not mapped.
203 void* memory() const { return memory_
; }
205 // Returns the underlying OS handle for this segment.
206 // Use of this handle for anything other than an opaque
207 // identifier is not portable.
208 SharedMemoryHandle
handle() const;
210 // Closes the open shared memory segment. The memory will remain mapped if
211 // it was previously mapped.
212 // It is safe to call Close repeatedly.
215 // Shares the shared memory to another process. Attempts to create a
216 // platform-specific new_handle which can be used in a remote process to read
217 // the shared memory file. new_handle is an output parameter to receive the
218 // handle for use in the remote process.
220 // |*this| must have been initialized using one of the Create*() or Open()
221 // methods with share_read_only=true. If it was constructed from a
222 // SharedMemoryHandle, this call will CHECK-fail.
224 // Returns true on success, false otherwise.
225 bool ShareReadOnlyToProcess(ProcessHandle process
,
226 SharedMemoryHandle
* new_handle
) {
227 return ShareToProcessCommon(process
, new_handle
, false, SHARE_READONLY
);
230 // Logically equivalent to:
231 // bool ok = ShareReadOnlyToProcess(process, new_handle);
234 // Note that the memory is unmapped by calling this method, regardless of the
236 bool GiveReadOnlyToProcess(ProcessHandle process
,
237 SharedMemoryHandle
* new_handle
) {
238 return ShareToProcessCommon(process
, new_handle
, true, SHARE_READONLY
);
241 // Shares the shared memory to another process. Attempts
242 // to create a platform-specific new_handle which can be
243 // used in a remote process to access the shared memory
244 // file. new_handle is an output parameter to receive
245 // the handle for use in the remote process.
246 // Returns true on success, false otherwise.
247 bool ShareToProcess(ProcessHandle process
,
248 SharedMemoryHandle
* new_handle
) {
249 return ShareToProcessCommon(process
, new_handle
, false, SHARE_CURRENT_MODE
);
252 // Logically equivalent to:
253 // bool ok = ShareToProcess(process, new_handle);
256 // Note that the memory is unmapped by calling this method, regardless of the
258 bool GiveToProcess(ProcessHandle process
,
259 SharedMemoryHandle
* new_handle
) {
260 return ShareToProcessCommon(process
, new_handle
, true, SHARE_CURRENT_MODE
);
264 #if defined(OS_POSIX) && !defined(OS_NACL) && !defined(OS_ANDROID)
265 bool PrepareMapFile(ScopedFILE fp
, ScopedFD readonly
);
266 bool FilePathForMemoryName(const std::string
& mem_name
, FilePath
* path
);
267 #endif // defined(OS_POSIX) && !defined(OS_NACL) && !defined(OS_ANDROID)
272 bool ShareToProcessCommon(ProcessHandle process
,
273 SharedMemoryHandle
* new_handle
,
280 #elif defined(OS_POSIX)
282 int readonly_mapped_file_
;
287 size_t requested_size_
;
289 DISALLOW_COPY_AND_ASSIGN(SharedMemory
);
293 #endif // BASE_MEMORY_SHARED_MEMORY_H_