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()
36 : name_deprecated(NULL
),
38 open_existing_deprecated(false),
40 share_read_only(false) {}
42 // DEPRECATED (crbug.com/345734):
43 // If NULL, the object is anonymous. This pointer is owned by the caller
44 // and must live through the call to Create().
45 const std::string
* name_deprecated
;
47 // Size of the shared memory object to be created.
48 // When opening an existing object, this has no effect.
51 // DEPRECATED (crbug.com/345734):
52 // If true, and the shared memory already exists, Create() will open the
53 // existing shared memory and ignore the size parameter. If false,
54 // shared memory must not exist. This flag is meaningless unless
55 // name_deprecated is non-NULL.
56 bool open_existing_deprecated
;
58 // If true, mappings might need to be made executable later.
61 // If true, the file can be shared read-only to a process.
65 // Platform abstraction for shared memory. Provides a C++ wrapper
66 // around the OS primitive for a memory mapped file.
67 class BASE_EXPORT SharedMemory
{
72 // Similar to the default constructor, except that this allows for
73 // calling LockDeprecated() to acquire the named mutex before either Create or
74 // Open are called on Windows.
75 explicit SharedMemory(const std::wstring
& name
);
78 // Create a new SharedMemory object from an existing, open
79 // shared memory file.
81 // WARNING: This does not reduce the OS-level permissions on the handle; it
82 // only affects how the SharedMemory will be mmapped. Use
83 // ShareReadOnlyToProcess to drop permissions. TODO(jln,jyasskin): DCHECK
84 // that |read_only| matches the permissions of the handle.
85 SharedMemory(const SharedMemoryHandle
& handle
, bool read_only
);
87 // Create a new SharedMemory object from an existing, open
88 // shared memory file that was created by a remote process and not shared
89 // to the current process.
90 SharedMemory(const SharedMemoryHandle
& handle
,
92 ProcessHandle process
);
94 // Closes any open files.
97 // Return true iff the given handle is valid (i.e. not the distingished
98 // invalid value; NULL for a HANDLE and -1 for a file descriptor)
99 static bool IsHandleValid(const SharedMemoryHandle
& handle
);
101 // Returns invalid handle (see comment above for exact definition).
102 static SharedMemoryHandle
NULLHandle();
104 // Closes a shared memory handle.
105 static void CloseHandle(const SharedMemoryHandle
& handle
);
107 // Returns the maximum number of handles that can be open at once per process.
108 static size_t GetHandleLimit();
110 // Duplicates The underlying OS primitive. Returns NULLHandle() on failure.
111 // The caller is responsible for destroying the duplicated OS primitive.
112 static SharedMemoryHandle
DuplicateHandle(const SharedMemoryHandle
& handle
);
114 #if defined(OS_POSIX)
115 // This method requires that the SharedMemoryHandle is backed by a POSIX fd.
116 static int GetFdFromSharedMemoryHandle(const SharedMemoryHandle
& handle
);
119 #if defined(OS_POSIX) && !defined(OS_ANDROID)
120 // Returns the size of the shared memory region referred to by |handle|.
121 // Returns '-1' on a failure to determine the size.
122 static int GetSizeFromSharedMemoryHandle(const SharedMemoryHandle
& handle
);
123 #endif // defined(OS_POSIX) && !defined(OS_ANDROID)
125 // Creates a shared memory object as described by the options struct.
126 // Returns true on success and false on failure.
127 bool Create(const SharedMemoryCreateOptions
& options
);
129 // Creates and maps an anonymous shared memory segment of size size.
130 // Returns true on success and false on failure.
131 bool CreateAndMapAnonymous(size_t size
);
133 // Creates an anonymous shared memory segment of size size.
134 // Returns true on success and false on failure.
135 bool CreateAnonymous(size_t size
) {
136 SharedMemoryCreateOptions options
;
138 return Create(options
);
141 // DEPRECATED (crbug.com/345734):
142 // Creates or opens a shared memory segment based on a name.
143 // If open_existing is true, and the shared memory already exists,
144 // opens the existing shared memory and ignores the size parameter.
145 // If open_existing is false, shared memory must not exist.
146 // size is the size of the block to be created.
147 // Returns true on success, false on failure.
148 bool CreateNamedDeprecated(
149 const std::string
& name
, bool open_existing
, size_t size
) {
150 SharedMemoryCreateOptions options
;
151 options
.name_deprecated
= &name
;
152 options
.open_existing_deprecated
= open_existing
;
154 return Create(options
);
157 // Deletes resources associated with a shared memory segment based on name.
158 // Not all platforms require this call.
159 bool Delete(const std::string
& name
);
161 // Opens a shared memory segment based on a name.
162 // If read_only is true, opens for read-only access.
163 // Returns true on success, false on failure.
164 bool Open(const std::string
& name
, bool read_only
);
166 // Maps the shared memory into the caller's address space.
167 // Returns true on success, false otherwise. The memory address
168 // is accessed via the memory() accessor. The mapped address is guaranteed to
169 // have an alignment of at least MAP_MINIMUM_ALIGNMENT. This method will fail
170 // if this object is currently mapped.
171 bool Map(size_t bytes
) {
172 return MapAt(0, bytes
);
175 // Same as above, but with |offset| to specify from begining of the shared
176 // memory block to map.
177 // |offset| must be alignent to value of |SysInfo::VMAllocationGranularity()|.
178 bool MapAt(off_t offset
, size_t bytes
);
179 enum { MAP_MINIMUM_ALIGNMENT
= 32 };
181 // Unmaps the shared memory from the caller's address space.
182 // Returns true if successful; returns false on error or if the
183 // memory is not mapped.
186 // The size requested when the map is first created.
187 size_t requested_size() const { return requested_size_
; }
189 // The actual size of the mapped memory (may be larger than requested).
190 size_t mapped_size() const { return mapped_size_
; }
192 // Gets a pointer to the opened memory space if it has been
193 // Mapped via Map(). Returns NULL if it is not mapped.
194 void *memory() const { return memory_
; }
196 // Returns the underlying OS handle for this segment.
197 // Use of this handle for anything other than an opaque
198 // identifier is not portable.
199 SharedMemoryHandle
handle() const;
201 // Closes the open shared memory segment. The memory will remain mapped if
202 // it was previously mapped.
203 // It is safe to call Close repeatedly.
206 // Shares the shared memory to another process. Attempts to create a
207 // platform-specific new_handle which can be used in a remote process to read
208 // the shared memory file. new_handle is an output parameter to receive the
209 // handle for use in the remote process.
211 // |*this| must have been initialized using one of the Create*() or Open()
212 // methods with share_read_only=true. If it was constructed from a
213 // SharedMemoryHandle, this call will CHECK-fail.
215 // Returns true on success, false otherwise.
216 bool ShareReadOnlyToProcess(ProcessHandle process
,
217 SharedMemoryHandle
* new_handle
) {
218 return ShareToProcessCommon(process
, new_handle
, false, SHARE_READONLY
);
221 // Logically equivalent to:
222 // bool ok = ShareReadOnlyToProcess(process, new_handle);
225 // Note that the memory is unmapped by calling this method, regardless of the
227 bool GiveReadOnlyToProcess(ProcessHandle process
,
228 SharedMemoryHandle
* new_handle
) {
229 return ShareToProcessCommon(process
, new_handle
, true, SHARE_READONLY
);
232 // Shares the shared memory to another process. Attempts
233 // to create a platform-specific new_handle which can be
234 // used in a remote process to access the shared memory
235 // file. new_handle is an output parameter to receive
236 // the handle for use in the remote process.
237 // Returns true on success, false otherwise.
238 bool ShareToProcess(ProcessHandle process
,
239 SharedMemoryHandle
* new_handle
) {
240 return ShareToProcessCommon(process
, new_handle
, false, SHARE_CURRENT_MODE
);
243 // Logically equivalent to:
244 // bool ok = ShareToProcess(process, new_handle);
247 // Note that the memory is unmapped by calling this method, regardless of the
249 bool GiveToProcess(ProcessHandle process
,
250 SharedMemoryHandle
* new_handle
) {
251 return ShareToProcessCommon(process
, new_handle
, true, SHARE_CURRENT_MODE
);
255 #if defined(OS_POSIX) && !defined(OS_NACL) && !defined(OS_ANDROID)
256 bool PrepareMapFile(ScopedFILE fp
, ScopedFD readonly
);
257 bool FilePathForMemoryName(const std::string
& mem_name
, FilePath
* path
);
258 #endif // defined(OS_POSIX) && !defined(OS_NACL) && !defined(OS_ANDROID)
263 bool ShareToProcessCommon(ProcessHandle process
,
264 SharedMemoryHandle
* new_handle
,
271 #elif defined(OS_POSIX)
273 int readonly_mapped_file_
;
278 size_t requested_size_
;
280 DISALLOW_COPY_AND_ASSIGN(SharedMemory
);
284 #endif // BASE_MEMORY_SHARED_MEMORY_H_