Invoke the iOS hook from TestSuite so each run_all_unittests.cc file does not
[chromium-blink-merge.git] / base / shared_memory_posix.cc
blob25d141fc054d41a1613c8166d8585d3e19205806
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 #include "base/shared_memory.h"
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <sys/mman.h>
10 #include <sys/stat.h>
11 #include <unistd.h>
13 #include "base/file_util.h"
14 #include "base/lazy_instance.h"
15 #include "base/logging.h"
16 #include "base/threading/platform_thread.h"
17 #include "base/safe_strerror_posix.h"
18 #include "base/synchronization/lock.h"
19 #include "base/threading/thread_restrictions.h"
20 #include "base/utf_string_conversions.h"
22 #if defined(OS_MACOSX)
23 #include "base/mac/foundation_util.h"
24 #endif // OS_MACOSX
26 #if defined(OS_ANDROID)
27 #include "base/os_compat_android.h"
28 #include "third_party/ashmem/ashmem.h"
29 #endif
31 namespace base {
33 namespace {
35 // Paranoia. Semaphores and shared memory segments should live in different
36 // namespaces, but who knows what's out there.
37 const char kSemaphoreSuffix[] = "-sem";
39 LazyInstance<Lock>::Leaky g_thread_lock_ = LAZY_INSTANCE_INITIALIZER;
43 SharedMemory::SharedMemory()
44 : mapped_file_(-1),
45 mapped_size_(0),
46 inode_(0),
47 memory_(NULL),
48 read_only_(false),
49 created_size_(0) {
52 SharedMemory::SharedMemory(SharedMemoryHandle handle, bool read_only)
53 : mapped_file_(handle.fd),
54 mapped_size_(0),
55 inode_(0),
56 memory_(NULL),
57 read_only_(read_only),
58 created_size_(0) {
59 struct stat st;
60 if (fstat(handle.fd, &st) == 0) {
61 // If fstat fails, then the file descriptor is invalid and we'll learn this
62 // fact when Map() fails.
63 inode_ = st.st_ino;
67 SharedMemory::SharedMemory(SharedMemoryHandle handle, bool read_only,
68 ProcessHandle process)
69 : mapped_file_(handle.fd),
70 mapped_size_(0),
71 inode_(0),
72 memory_(NULL),
73 read_only_(read_only),
74 created_size_(0) {
75 // We don't handle this case yet (note the ignored parameter); let's die if
76 // someone comes calling.
77 NOTREACHED();
80 SharedMemory::~SharedMemory() {
81 Close();
84 // static
85 bool SharedMemory::IsHandleValid(const SharedMemoryHandle& handle) {
86 return handle.fd >= 0;
89 // static
90 SharedMemoryHandle SharedMemory::NULLHandle() {
91 return SharedMemoryHandle();
94 // static
95 void SharedMemory::CloseHandle(const SharedMemoryHandle& handle) {
96 DCHECK_GE(handle.fd, 0);
97 if (HANDLE_EINTR(close(handle.fd)) < 0)
98 DPLOG(ERROR) << "close";
101 bool SharedMemory::CreateAndMapAnonymous(size_t size) {
102 return CreateAnonymous(size) && Map(size);
105 #if !defined(OS_ANDROID)
106 // Chromium mostly only uses the unique/private shmem as specified by
107 // "name == L"". The exception is in the StatsTable.
108 // TODO(jrg): there is no way to "clean up" all unused named shmem if
109 // we restart from a crash. (That isn't a new problem, but it is a problem.)
110 // In case we want to delete it later, it may be useful to save the value
111 // of mem_filename after FilePathForMemoryName().
112 bool SharedMemory::Create(const SharedMemoryCreateOptions& options) {
113 DCHECK_EQ(-1, mapped_file_);
114 if (options.size == 0) return false;
116 if (options.size > static_cast<size_t>(std::numeric_limits<int>::max()))
117 return false;
119 // This function theoretically can block on the disk, but realistically
120 // the temporary files we create will just go into the buffer cache
121 // and be deleted before they ever make it out to disk.
122 base::ThreadRestrictions::ScopedAllowIO allow_io;
124 FILE *fp;
125 bool fix_size = true;
127 FilePath path;
128 if (options.name == NULL || options.name->empty()) {
129 // It doesn't make sense to have a open-existing private piece of shmem
130 DCHECK(!options.open_existing);
131 // Q: Why not use the shm_open() etc. APIs?
132 // A: Because they're limited to 4mb on OS X. FFFFFFFUUUUUUUUUUU
133 fp = file_util::CreateAndOpenTemporaryShmemFile(&path, options.executable);
135 // Deleting the file prevents anyone else from mapping it in (making it
136 // private), and prevents the need for cleanup (once the last fd is closed,
137 // it is truly freed).
138 if (fp) {
139 if (unlink(path.value().c_str()))
140 PLOG(WARNING) << "unlink";
142 } else {
143 if (!FilePathForMemoryName(*options.name, &path))
144 return false;
146 fp = file_util::OpenFile(path, "w+x");
147 if (fp == NULL && options.open_existing) {
148 // "w+" will truncate if it already exists.
149 fp = file_util::OpenFile(path, "a+");
150 fix_size = false;
153 if (fp && fix_size) {
154 // Get current size.
155 struct stat stat;
156 if (fstat(fileno(fp), &stat) != 0) {
157 file_util::CloseFile(fp);
158 return false;
160 const size_t current_size = stat.st_size;
161 if (current_size != options.size) {
162 if (HANDLE_EINTR(ftruncate(fileno(fp), options.size)) != 0) {
163 file_util::CloseFile(fp);
164 return false;
167 created_size_ = options.size;
169 if (fp == NULL) {
170 #if !defined(OS_MACOSX)
171 PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed";
172 FilePath dir = path.DirName();
173 if (access(dir.value().c_str(), W_OK | X_OK) < 0) {
174 PLOG(ERROR) << "Unable to access(W_OK|X_OK) " << dir.value();
175 if (dir.value() == "/dev/shm") {
176 LOG(FATAL) << "This is frequently caused by incorrect permissions on "
177 << "/dev/shm. Try 'sudo chmod 1777 /dev/shm' to fix.";
180 #else
181 PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed";
182 #endif
183 return false;
186 return PrepareMapFile(fp);
189 // Our current implementation of shmem is with mmap()ing of files.
190 // These files need to be deleted explicitly.
191 // In practice this call is only needed for unit tests.
192 bool SharedMemory::Delete(const std::string& name) {
193 FilePath path;
194 if (!FilePathForMemoryName(name, &path))
195 return false;
197 if (file_util::PathExists(path)) {
198 return file_util::Delete(path, false);
201 // Doesn't exist, so success.
202 return true;
205 bool SharedMemory::Open(const std::string& name, bool read_only) {
206 FilePath path;
207 if (!FilePathForMemoryName(name, &path))
208 return false;
210 read_only_ = read_only;
212 const char *mode = read_only ? "r" : "r+";
213 FILE *fp = file_util::OpenFile(path, mode);
214 return PrepareMapFile(fp);
217 #endif // !defined(OS_ANDROID)
219 bool SharedMemory::MapAt(off_t offset, size_t bytes) {
220 if (mapped_file_ == -1)
221 return false;
223 if (bytes > static_cast<size_t>(std::numeric_limits<int>::max()))
224 return false;
226 #if defined(OS_ANDROID)
227 if (bytes == 0) {
228 int ashmem_bytes = ashmem_get_size_region(mapped_file_);
229 if (ashmem_bytes < 0)
230 return false;
232 DCHECK_GE(static_cast<uint32>(ashmem_bytes), bytes);
233 // The caller wants to determine the map region size from ashmem.
234 bytes = ashmem_bytes - offset;
235 // TODO(port): we set the created size here so that it is available in
236 // transport_dib_android.cc. We should use ashmem_get_size_region()
237 // in transport_dib_android.cc.
238 created_size_ = ashmem_bytes;
240 #endif
242 memory_ = mmap(NULL, bytes, PROT_READ | (read_only_ ? 0 : PROT_WRITE),
243 MAP_SHARED, mapped_file_, offset);
245 bool mmap_succeeded = memory_ != (void*)-1 && memory_ != NULL;
246 if (mmap_succeeded) {
247 mapped_size_ = bytes;
248 DCHECK_EQ(0U, reinterpret_cast<uintptr_t>(memory_) &
249 (SharedMemory::MAP_MINIMUM_ALIGNMENT - 1));
250 } else {
251 memory_ = NULL;
254 return mmap_succeeded;
257 bool SharedMemory::Unmap() {
258 if (memory_ == NULL)
259 return false;
261 munmap(memory_, mapped_size_);
262 memory_ = NULL;
263 mapped_size_ = 0;
264 return true;
267 SharedMemoryHandle SharedMemory::handle() const {
268 return FileDescriptor(mapped_file_, false);
271 void SharedMemory::Close() {
272 Unmap();
274 if (mapped_file_ > 0) {
275 if (HANDLE_EINTR(close(mapped_file_)) < 0)
276 PLOG(ERROR) << "close";
277 mapped_file_ = -1;
281 void SharedMemory::Lock() {
282 g_thread_lock_.Get().Acquire();
283 LockOrUnlockCommon(F_LOCK);
286 void SharedMemory::Unlock() {
287 LockOrUnlockCommon(F_ULOCK);
288 g_thread_lock_.Get().Release();
291 #if !defined(OS_ANDROID)
292 bool SharedMemory::PrepareMapFile(FILE *fp) {
293 DCHECK_EQ(-1, mapped_file_);
294 if (fp == NULL) return false;
296 // This function theoretically can block on the disk, but realistically
297 // the temporary files we create will just go into the buffer cache
298 // and be deleted before they ever make it out to disk.
299 base::ThreadRestrictions::ScopedAllowIO allow_io;
301 file_util::ScopedFILE file_closer(fp);
303 mapped_file_ = dup(fileno(fp));
304 if (mapped_file_ == -1) {
305 if (errno == EMFILE) {
306 LOG(WARNING) << "Shared memory creation failed; out of file descriptors";
307 return false;
308 } else {
309 NOTREACHED() << "Call to dup failed, errno=" << errno;
313 struct stat st;
314 if (fstat(mapped_file_, &st))
315 NOTREACHED();
316 inode_ = st.st_ino;
318 return true;
320 #endif
322 // For the given shmem named |mem_name|, return a filename to mmap()
323 // (and possibly create). Modifies |filename|. Return false on
324 // error, or true of we are happy.
325 bool SharedMemory::FilePathForMemoryName(const std::string& mem_name,
326 FilePath* path) {
327 // mem_name will be used for a filename; make sure it doesn't
328 // contain anything which will confuse us.
329 DCHECK_EQ(std::string::npos, mem_name.find('/'));
330 DCHECK_EQ(std::string::npos, mem_name.find('\0'));
332 FilePath temp_dir;
333 if (!file_util::GetShmemTempDir(&temp_dir, false))
334 return false;
336 #if !defined(OS_MACOSX)
337 #if defined(GOOGLE_CHROME_BUILD)
338 std::string name_base = std::string("com.google.Chrome");
339 #else
340 std::string name_base = std::string("org.chromium.Chromium");
341 #endif
342 #else // OS_MACOSX
343 std::string name_base = std::string(base::mac::BaseBundleID());
344 #endif // OS_MACOSX
345 *path = temp_dir.AppendASCII(name_base + ".shmem." + mem_name);
346 return true;
349 void SharedMemory::LockOrUnlockCommon(int function) {
350 DCHECK_GE(mapped_file_, 0);
351 while (lockf(mapped_file_, function, 0) < 0) {
352 if (errno == EINTR) {
353 continue;
354 } else if (errno == ENOLCK) {
355 // temporary kernel resource exaustion
356 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(500));
357 continue;
358 } else {
359 NOTREACHED() << "lockf() failed."
360 << " function:" << function
361 << " fd:" << mapped_file_
362 << " errno:" << errno
363 << " msg:" << safe_strerror(errno);
368 bool SharedMemory::ShareToProcessCommon(ProcessHandle process,
369 SharedMemoryHandle *new_handle,
370 bool close_self) {
371 const int new_fd = dup(mapped_file_);
372 if (new_fd < 0) {
373 DPLOG(ERROR) << "dup() failed.";
374 return false;
377 new_handle->fd = new_fd;
378 new_handle->auto_close = true;
380 if (close_self)
381 Close();
383 return true;
386 } // namespace base