Update Chrome code to use new WebScreenOrientation types.
[chromium-blink-merge.git] / base / memory / shared_memory_posix.cc
blob2afe450d93ac6af6ee1f95ef9be419471263eb2c
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/memory/shared_memory.h"
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <sys/mman.h>
10 #include <sys/stat.h>
11 #include <sys/types.h>
12 #include <unistd.h>
14 #include "base/file_util.h"
15 #include "base/files/scoped_file.h"
16 #include "base/lazy_instance.h"
17 #include "base/logging.h"
18 #include "base/process/process_metrics.h"
19 #include "base/safe_strerror_posix.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/synchronization/lock.h"
22 #include "base/threading/platform_thread.h"
23 #include "base/threading/thread_restrictions.h"
25 #if defined(OS_MACOSX)
26 #include "base/mac/foundation_util.h"
27 #endif // OS_MACOSX
29 #if defined(OS_ANDROID)
30 #include "base/os_compat_android.h"
31 #include "third_party/ashmem/ashmem.h"
32 #endif
34 namespace base {
36 namespace {
38 LazyInstance<Lock>::Leaky g_thread_lock_ = LAZY_INSTANCE_INITIALIZER;
42 SharedMemory::SharedMemory()
43 : mapped_file_(-1),
44 readonly_mapped_file_(-1),
45 inode_(0),
46 mapped_size_(0),
47 memory_(NULL),
48 read_only_(false),
49 requested_size_(0) {
52 SharedMemory::SharedMemory(SharedMemoryHandle handle, bool read_only)
53 : mapped_file_(handle.fd),
54 readonly_mapped_file_(-1),
55 inode_(0),
56 mapped_size_(0),
57 memory_(NULL),
58 read_only_(read_only),
59 requested_size_(0) {
60 struct stat st;
61 if (fstat(handle.fd, &st) == 0) {
62 // If fstat fails, then the file descriptor is invalid and we'll learn this
63 // fact when Map() fails.
64 inode_ = st.st_ino;
68 SharedMemory::SharedMemory(SharedMemoryHandle handle, bool read_only,
69 ProcessHandle process)
70 : mapped_file_(handle.fd),
71 readonly_mapped_file_(-1),
72 inode_(0),
73 mapped_size_(0),
74 memory_(NULL),
75 read_only_(read_only),
76 requested_size_(0) {
77 // We don't handle this case yet (note the ignored parameter); let's die if
78 // someone comes calling.
79 NOTREACHED();
82 SharedMemory::~SharedMemory() {
83 Close();
86 // static
87 bool SharedMemory::IsHandleValid(const SharedMemoryHandle& handle) {
88 return handle.fd >= 0;
91 // static
92 SharedMemoryHandle SharedMemory::NULLHandle() {
93 return SharedMemoryHandle();
96 // static
97 void SharedMemory::CloseHandle(const SharedMemoryHandle& handle) {
98 DCHECK_GE(handle.fd, 0);
99 if (close(handle.fd) < 0)
100 DPLOG(ERROR) << "close";
103 // static
104 size_t SharedMemory::GetHandleLimit() {
105 return base::GetMaxFds();
108 bool SharedMemory::CreateAndMapAnonymous(size_t size) {
109 return CreateAnonymous(size) && Map(size);
112 #if !defined(OS_ANDROID)
113 // Chromium mostly only uses the unique/private shmem as specified by
114 // "name == L"". The exception is in the StatsTable.
115 // TODO(jrg): there is no way to "clean up" all unused named shmem if
116 // we restart from a crash. (That isn't a new problem, but it is a problem.)
117 // In case we want to delete it later, it may be useful to save the value
118 // of mem_filename after FilePathForMemoryName().
119 bool SharedMemory::Create(const SharedMemoryCreateOptions& options) {
120 DCHECK_EQ(-1, mapped_file_);
121 if (options.size == 0) return false;
123 if (options.size > static_cast<size_t>(std::numeric_limits<int>::max()))
124 return false;
126 // This function theoretically can block on the disk, but realistically
127 // the temporary files we create will just go into the buffer cache
128 // and be deleted before they ever make it out to disk.
129 base::ThreadRestrictions::ScopedAllowIO allow_io;
131 ScopedFILE fp;
132 bool fix_size = true;
133 ScopedFD readonly_fd;
135 FilePath path;
136 if (options.name_deprecated == NULL || options.name_deprecated->empty()) {
137 // It doesn't make sense to have a open-existing private piece of shmem
138 DCHECK(!options.open_existing_deprecated);
139 // Q: Why not use the shm_open() etc. APIs?
140 // A: Because they're limited to 4mb on OS X. FFFFFFFUUUUUUUUUUU
141 FilePath directory;
142 if (GetShmemTempDir(options.executable, &directory))
143 fp.reset(CreateAndOpenTemporaryFileInDir(directory, &path));
145 if (fp) {
146 // Also open as readonly so that we can ShareReadOnlyToProcess.
147 readonly_fd.reset(HANDLE_EINTR(open(path.value().c_str(), O_RDONLY)));
148 if (!readonly_fd.is_valid()) {
149 DPLOG(ERROR) << "open(\"" << path.value() << "\", O_RDONLY) failed";
150 fp.reset();
152 // Deleting the file prevents anyone else from mapping it in (making it
153 // private), and prevents the need for cleanup (once the last fd is
154 // closed, it is truly freed).
155 if (unlink(path.value().c_str()))
156 PLOG(WARNING) << "unlink";
158 } else {
159 if (!FilePathForMemoryName(*options.name_deprecated, &path))
160 return false;
162 // Make sure that the file is opened without any permission
163 // to other users on the system.
164 const mode_t kOwnerOnly = S_IRUSR | S_IWUSR;
166 // First, try to create the file.
167 int fd = HANDLE_EINTR(
168 open(path.value().c_str(), O_RDWR | O_CREAT | O_EXCL, kOwnerOnly));
169 if (fd == -1 && options.open_existing_deprecated) {
170 // If this doesn't work, try and open an existing file in append mode.
171 // Opening an existing file in a world writable directory has two main
172 // security implications:
173 // - Attackers could plant a file under their control, so ownership of
174 // the file is checked below.
175 // - Attackers could plant a symbolic link so that an unexpected file
176 // is opened, so O_NOFOLLOW is passed to open().
177 fd = HANDLE_EINTR(
178 open(path.value().c_str(), O_RDWR | O_APPEND | O_NOFOLLOW));
180 // Check that the current user owns the file.
181 // If uid != euid, then a more complex permission model is used and this
182 // API is not appropriate.
183 const uid_t real_uid = getuid();
184 const uid_t effective_uid = geteuid();
185 struct stat sb;
186 if (fd >= 0 &&
187 (fstat(fd, &sb) != 0 || sb.st_uid != real_uid ||
188 sb.st_uid != effective_uid)) {
189 LOG(ERROR) <<
190 "Invalid owner when opening existing shared memory file.";
191 close(fd);
192 return false;
195 // An existing file was opened, so its size should not be fixed.
196 fix_size = false;
199 // Also open as readonly so that we can ShareReadOnlyToProcess.
200 readonly_fd.reset(HANDLE_EINTR(open(path.value().c_str(), O_RDONLY)));
201 if (!readonly_fd.is_valid()) {
202 DPLOG(ERROR) << "open(\"" << path.value() << "\", O_RDONLY) failed";
203 close(fd);
204 fd = -1;
206 if (fd >= 0) {
207 // "a+" is always appropriate: if it's a new file, a+ is similar to w+.
208 fp.reset(fdopen(fd, "a+"));
211 if (fp && fix_size) {
212 // Get current size.
213 struct stat stat;
214 if (fstat(fileno(fp.get()), &stat) != 0)
215 return false;
216 const size_t current_size = stat.st_size;
217 if (current_size != options.size) {
218 if (HANDLE_EINTR(ftruncate(fileno(fp.get()), options.size)) != 0)
219 return false;
221 requested_size_ = options.size;
223 if (fp == NULL) {
224 #if !defined(OS_MACOSX)
225 PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed";
226 FilePath dir = path.DirName();
227 if (access(dir.value().c_str(), W_OK | X_OK) < 0) {
228 PLOG(ERROR) << "Unable to access(W_OK|X_OK) " << dir.value();
229 if (dir.value() == "/dev/shm") {
230 LOG(FATAL) << "This is frequently caused by incorrect permissions on "
231 << "/dev/shm. Try 'sudo chmod 1777 /dev/shm' to fix.";
234 #else
235 PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed";
236 #endif
237 return false;
240 return PrepareMapFile(fp.Pass(), readonly_fd.Pass());
243 // Our current implementation of shmem is with mmap()ing of files.
244 // These files need to be deleted explicitly.
245 // In practice this call is only needed for unit tests.
246 bool SharedMemory::Delete(const std::string& name) {
247 FilePath path;
248 if (!FilePathForMemoryName(name, &path))
249 return false;
251 if (PathExists(path))
252 return base::DeleteFile(path, false);
254 // Doesn't exist, so success.
255 return true;
258 bool SharedMemory::Open(const std::string& name, bool read_only) {
259 FilePath path;
260 if (!FilePathForMemoryName(name, &path))
261 return false;
263 read_only_ = read_only;
265 const char *mode = read_only ? "r" : "r+";
266 ScopedFILE fp(base::OpenFile(path, mode));
267 ScopedFD readonly_fd(HANDLE_EINTR(open(path.value().c_str(), O_RDONLY)));
268 if (!readonly_fd.is_valid()) {
269 DPLOG(ERROR) << "open(\"" << path.value() << "\", O_RDONLY) failed";
271 return PrepareMapFile(fp.Pass(), readonly_fd.Pass());
273 #endif // !defined(OS_ANDROID)
275 bool SharedMemory::MapAt(off_t offset, size_t bytes) {
276 if (mapped_file_ == -1)
277 return false;
279 if (bytes > static_cast<size_t>(std::numeric_limits<int>::max()))
280 return false;
282 if (memory_)
283 return false;
285 #if defined(OS_ANDROID)
286 // On Android, Map can be called with a size and offset of zero to use the
287 // ashmem-determined size.
288 if (bytes == 0) {
289 DCHECK_EQ(0, offset);
290 int ashmem_bytes = ashmem_get_size_region(mapped_file_);
291 if (ashmem_bytes < 0)
292 return false;
293 bytes = ashmem_bytes;
295 #endif
297 memory_ = mmap(NULL, bytes, PROT_READ | (read_only_ ? 0 : PROT_WRITE),
298 MAP_SHARED, mapped_file_, offset);
300 bool mmap_succeeded = memory_ != (void*)-1 && memory_ != NULL;
301 if (mmap_succeeded) {
302 mapped_size_ = bytes;
303 DCHECK_EQ(0U, reinterpret_cast<uintptr_t>(memory_) &
304 (SharedMemory::MAP_MINIMUM_ALIGNMENT - 1));
305 } else {
306 memory_ = NULL;
309 return mmap_succeeded;
312 bool SharedMemory::Unmap() {
313 if (memory_ == NULL)
314 return false;
316 munmap(memory_, mapped_size_);
317 memory_ = NULL;
318 mapped_size_ = 0;
319 return true;
322 SharedMemoryHandle SharedMemory::handle() const {
323 return FileDescriptor(mapped_file_, false);
326 void SharedMemory::Close() {
327 Unmap();
329 if (mapped_file_ > 0) {
330 if (close(mapped_file_) < 0)
331 PLOG(ERROR) << "close";
332 mapped_file_ = -1;
334 if (readonly_mapped_file_ > 0) {
335 if (close(readonly_mapped_file_) < 0)
336 PLOG(ERROR) << "close";
337 readonly_mapped_file_ = -1;
341 void SharedMemory::LockDeprecated() {
342 g_thread_lock_.Get().Acquire();
343 LockOrUnlockCommon(F_LOCK);
346 void SharedMemory::UnlockDeprecated() {
347 LockOrUnlockCommon(F_ULOCK);
348 g_thread_lock_.Get().Release();
351 #if !defined(OS_ANDROID)
352 bool SharedMemory::PrepareMapFile(ScopedFILE fp, ScopedFD readonly_fd) {
353 DCHECK_EQ(-1, mapped_file_);
354 DCHECK_EQ(-1, readonly_mapped_file_);
355 if (fp == NULL || !readonly_fd.is_valid()) return false;
357 // This function theoretically can block on the disk, but realistically
358 // the temporary files we create will just go into the buffer cache
359 // and be deleted before they ever make it out to disk.
360 base::ThreadRestrictions::ScopedAllowIO allow_io;
362 struct stat st = {};
363 struct stat readonly_st = {};
364 if (fstat(fileno(fp.get()), &st))
365 NOTREACHED();
366 if (fstat(readonly_fd.get(), &readonly_st))
367 NOTREACHED();
368 if (st.st_dev != readonly_st.st_dev || st.st_ino != readonly_st.st_ino) {
369 LOG(ERROR) << "writable and read-only inodes don't match; bailing";
370 return false;
373 mapped_file_ = dup(fileno(fp.get()));
374 if (mapped_file_ == -1) {
375 if (errno == EMFILE) {
376 LOG(WARNING) << "Shared memory creation failed; out of file descriptors";
377 return false;
378 } else {
379 NOTREACHED() << "Call to dup failed, errno=" << errno;
382 inode_ = st.st_ino;
383 readonly_mapped_file_ = readonly_fd.release();
385 return true;
388 // For the given shmem named |mem_name|, return a filename to mmap()
389 // (and possibly create). Modifies |filename|. Return false on
390 // error, or true of we are happy.
391 bool SharedMemory::FilePathForMemoryName(const std::string& mem_name,
392 FilePath* path) {
393 // mem_name will be used for a filename; make sure it doesn't
394 // contain anything which will confuse us.
395 DCHECK_EQ(std::string::npos, mem_name.find('/'));
396 DCHECK_EQ(std::string::npos, mem_name.find('\0'));
398 FilePath temp_dir;
399 if (!GetShmemTempDir(false, &temp_dir))
400 return false;
402 #if !defined(OS_MACOSX)
403 #if defined(GOOGLE_CHROME_BUILD)
404 std::string name_base = std::string("com.google.Chrome");
405 #else
406 std::string name_base = std::string("org.chromium.Chromium");
407 #endif
408 #else // OS_MACOSX
409 std::string name_base = std::string(base::mac::BaseBundleID());
410 #endif // OS_MACOSX
411 *path = temp_dir.AppendASCII(name_base + ".shmem." + mem_name);
412 return true;
414 #endif // !defined(OS_ANDROID)
416 void SharedMemory::LockOrUnlockCommon(int function) {
417 DCHECK_GE(mapped_file_, 0);
418 while (lockf(mapped_file_, function, 0) < 0) {
419 if (errno == EINTR) {
420 continue;
421 } else if (errno == ENOLCK) {
422 // temporary kernel resource exaustion
423 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(500));
424 continue;
425 } else {
426 NOTREACHED() << "lockf() failed."
427 << " function:" << function
428 << " fd:" << mapped_file_
429 << " errno:" << errno
430 << " msg:" << safe_strerror(errno);
435 bool SharedMemory::ShareToProcessCommon(ProcessHandle process,
436 SharedMemoryHandle* new_handle,
437 bool close_self,
438 ShareMode share_mode) {
439 int handle_to_dup = -1;
440 switch(share_mode) {
441 case SHARE_CURRENT_MODE:
442 handle_to_dup = mapped_file_;
443 break;
444 case SHARE_READONLY:
445 // We could imagine re-opening the file from /dev/fd, but that can't make
446 // it readonly on Mac: https://codereview.chromium.org/27265002/#msg10
447 CHECK(readonly_mapped_file_ >= 0);
448 handle_to_dup = readonly_mapped_file_;
449 break;
452 const int new_fd = dup(handle_to_dup);
453 if (new_fd < 0) {
454 DPLOG(ERROR) << "dup() failed.";
455 return false;
458 new_handle->fd = new_fd;
459 new_handle->auto_close = true;
461 if (close_self)
462 Close();
464 return true;
467 } // namespace base