87b923e79efab0cbc3153dd0314f2a4e37edad3f
[platform/framework/web/crosswalk.git] / src / base / memory / shared_memory.h
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.
4
5 #ifndef BASE_MEMORY_SHARED_MEMORY_H_
6 #define BASE_MEMORY_SHARED_MEMORY_H_
7
8 #include "build/build_config.h"
9
10 #include <string>
11
12 #if defined(OS_POSIX)
13 #include <stdio.h>
14 #include <sys/types.h>
15 #include <semaphore.h>
16 #endif
17
18 #include "base/base_export.h"
19 #include "base/basictypes.h"
20 #include "base/process/process_handle.h"
21
22 #if defined(OS_POSIX)
23 #include "base/file_descriptor_posix.h"
24 #include "base/file_util.h"
25 #include "base/files/scoped_file.h"
26 #endif
27
28 namespace base {
29
30 class FilePath;
31
32 // SharedMemoryHandle is a platform specific type which represents
33 // the underlying OS handle to a shared memory segment.
34 #if defined(OS_WIN)
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;
41 #endif
42
43 // Options for creating a shared memory object.
44 struct SharedMemoryCreateOptions {
45   SharedMemoryCreateOptions() : name_deprecated(NULL), size(0),
46                                 open_existing_deprecated(false),
47                                 executable(false) {}
48
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;
53
54   // Size of the shared memory object to be created.
55   // When opening an existing object, this has no effect.
56   size_t size;
57
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;
64
65   // If true, mappings might need to be made executable later.
66   bool executable;
67 };
68
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 {
72  public:
73   SharedMemory();
74
75 #if defined(OS_WIN)
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);
80 #endif
81
82   // Create a new SharedMemory object from an existing, open
83   // shared memory file.
84   //
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);
90
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);
96
97   // Closes any open files.
98   ~SharedMemory();
99
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);
103
104   // Returns invalid handle (see comment above for exact definition).
105   static SharedMemoryHandle NULLHandle();
106
107   // Closes a shared memory handle.
108   static void CloseHandle(const SharedMemoryHandle& handle);
109
110   // Returns the maximum number of handles that can be open at once per process.
111   static size_t GetHandleLimit();
112
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);
116
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);
120
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;
125     options.size = size;
126     return Create(options);
127   }
128
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;
141     options.size = size;
142     return Create(options);
143   }
144
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);
148
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);
153
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);
161   }
162
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 };
168
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.
172   bool Unmap();
173
174   // The size requested when the map is first created.
175   size_t requested_size() const { return requested_size_; }
176
177   // The actual size of the mapped memory (may be larger than requested).
178   size_t mapped_size() const { return mapped_size_; }
179
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_; }
183
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;
188
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_; }
195 #endif
196
197   // Closes the open shared memory segment.
198   // It is safe to call Close repeatedly.
199   void Close();
200
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.
205   //
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
208   // CHECK-fail.
209   //
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);
214   }
215
216   // Logically equivalent to:
217   //   bool ok = ShareReadOnlyToProcess(process, new_handle);
218   //   Close();
219   //   return ok;
220   // Note that the memory is unmapped by calling this method, regardless of the
221   // return value.
222   bool GiveReadOnlyToProcess(ProcessHandle process,
223                              SharedMemoryHandle* new_handle) {
224     return ShareToProcessCommon(process, new_handle, true, SHARE_READONLY);
225   }
226
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);
236   }
237
238   // Logically equivalent to:
239   //   bool ok = ShareToProcess(process, new_handle);
240   //   Close();
241   //   return ok;
242   // Note that the memory is unmapped by calling this method, regardless of the
243   // return value.
244   bool GiveToProcess(ProcessHandle process,
245                      SharedMemoryHandle* new_handle) {
246     return ShareToProcessCommon(process, new_handle, true, SHARE_CURRENT_MODE);
247   }
248
249   // DEPRECATED (crbug.com/345734):
250   // Locks the shared memory.
251   //
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();
257
258   // DEPRECATED (crbug.com/345734):
259   // Releases the shared memory lock.
260   void UnlockDeprecated();
261
262  private:
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);
267 #endif
268   void LockOrUnlockCommon(int function);
269 #endif  // defined(OS_POSIX) && !defined(OS_NACL)
270   enum ShareMode {
271     SHARE_READONLY,
272     SHARE_CURRENT_MODE,
273   };
274   bool ShareToProcessCommon(ProcessHandle process,
275                             SharedMemoryHandle* new_handle,
276                             bool close_self,
277                             ShareMode);
278
279 #if defined(OS_WIN)
280   std::wstring       name_;
281   HANDLE             mapped_file_;
282 #elif defined(OS_POSIX)
283   int                mapped_file_;
284   int                readonly_mapped_file_;
285   ino_t              inode_;
286 #endif
287   size_t             mapped_size_;
288   void*              memory_;
289   bool               read_only_;
290   size_t             requested_size_;
291 #if !defined(OS_POSIX)
292   HANDLE             lock_;
293 #endif
294
295   DISALLOW_COPY_AND_ASSIGN(SharedMemory);
296 };
297
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 {
302  public:
303   explicit SharedMemoryAutoLockDeprecated(SharedMemory* shared_memory)
304       : shared_memory_(shared_memory) {
305     shared_memory_->LockDeprecated();
306   }
307
308   ~SharedMemoryAutoLockDeprecated() {
309     shared_memory_->UnlockDeprecated();
310   }
311
312  private:
313   SharedMemory* shared_memory_;
314   DISALLOW_COPY_AND_ASSIGN(SharedMemoryAutoLockDeprecated);
315 };
316
317 }  // namespace base
318
319 #endif  // BASE_MEMORY_SHARED_MEMORY_H_