Switch TestFrameNavigationObserver to DidCommitProvisionalLoadForFrame.
[chromium-blink-merge.git] / base / memory / shared_memory_posix.cc
blob2dc08a14ca24ec2c441173b639dd2b5030264389
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/files/file_util.h"
15 #include "base/files/scoped_file.h"
16 #include "base/lazy_instance.h"
17 #include "base/logging.h"
18 #include "base/posix/eintr_wrapper.h"
19 #include "base/process/process_metrics.h"
20 #include "base/profiler/scoped_tracker.h"
21 #include "base/safe_strerror_posix.h"
22 #include "base/strings/utf_string_conversions.h"
23 #include "base/synchronization/lock.h"
24 #include "base/threading/platform_thread.h"
25 #include "base/threading/thread_restrictions.h"
27 #if defined(OS_MACOSX)
28 #include "base/mac/foundation_util.h"
29 #endif // OS_MACOSX
31 #if defined(OS_ANDROID)
32 #include "base/os_compat_android.h"
33 #include "third_party/ashmem/ashmem.h"
34 #endif
36 namespace base {
38 namespace {
40 LazyInstance<Lock>::Leaky g_thread_lock_ = LAZY_INSTANCE_INITIALIZER;
44 SharedMemory::SharedMemory()
45 : mapped_file_(-1),
46 readonly_mapped_file_(-1),
47 inode_(0),
48 mapped_size_(0),
49 memory_(NULL),
50 read_only_(false),
51 requested_size_(0) {
54 SharedMemory::SharedMemory(SharedMemoryHandle handle, bool read_only)
55 : mapped_file_(handle.fd),
56 readonly_mapped_file_(-1),
57 inode_(0),
58 mapped_size_(0),
59 memory_(NULL),
60 read_only_(read_only),
61 requested_size_(0) {
62 struct stat st;
63 if (fstat(handle.fd, &st) == 0) {
64 // If fstat fails, then the file descriptor is invalid and we'll learn this
65 // fact when Map() fails.
66 inode_ = st.st_ino;
70 SharedMemory::SharedMemory(SharedMemoryHandle handle, bool read_only,
71 ProcessHandle process)
72 : mapped_file_(handle.fd),
73 readonly_mapped_file_(-1),
74 inode_(0),
75 mapped_size_(0),
76 memory_(NULL),
77 read_only_(read_only),
78 requested_size_(0) {
79 // We don't handle this case yet (note the ignored parameter); let's die if
80 // someone comes calling.
81 NOTREACHED();
84 SharedMemory::~SharedMemory() {
85 Unmap();
86 Close();
89 // static
90 bool SharedMemory::IsHandleValid(const SharedMemoryHandle& handle) {
91 return handle.fd >= 0;
94 // static
95 SharedMemoryHandle SharedMemory::NULLHandle() {
96 return SharedMemoryHandle();
99 // static
100 void SharedMemory::CloseHandle(const SharedMemoryHandle& handle) {
101 DCHECK_GE(handle.fd, 0);
102 if (close(handle.fd) < 0)
103 DPLOG(ERROR) << "close";
106 // static
107 size_t SharedMemory::GetHandleLimit() {
108 return base::GetMaxFds();
111 bool SharedMemory::CreateAndMapAnonymous(size_t size) {
112 return CreateAnonymous(size) && Map(size);
115 #if !defined(OS_ANDROID)
116 // Chromium mostly only uses the unique/private shmem as specified by
117 // "name == L"". The exception is in the StatsTable.
118 // TODO(jrg): there is no way to "clean up" all unused named shmem if
119 // we restart from a crash. (That isn't a new problem, but it is a problem.)
120 // In case we want to delete it later, it may be useful to save the value
121 // of mem_filename after FilePathForMemoryName().
122 bool SharedMemory::Create(const SharedMemoryCreateOptions& options) {
123 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466437
124 // is fixed.
125 tracked_objects::ScopedTracker tracking_profile1(
126 FROM_HERE_WITH_EXPLICIT_FUNCTION(
127 "466437 SharedMemory::Create::Start"));
128 DCHECK_EQ(-1, mapped_file_);
129 if (options.size == 0) return false;
131 if (options.size > static_cast<size_t>(std::numeric_limits<int>::max()))
132 return false;
134 // This function theoretically can block on the disk, but realistically
135 // the temporary files we create will just go into the buffer cache
136 // and be deleted before they ever make it out to disk.
137 base::ThreadRestrictions::ScopedAllowIO allow_io;
139 ScopedFILE fp;
140 bool fix_size = true;
141 ScopedFD readonly_fd;
143 FilePath path;
144 if (options.name_deprecated == NULL || options.name_deprecated->empty()) {
145 // It doesn't make sense to have a open-existing private piece of shmem
146 DCHECK(!options.open_existing_deprecated);
147 // Q: Why not use the shm_open() etc. APIs?
148 // A: Because they're limited to 4mb on OS X. FFFFFFFUUUUUUUUUUU
149 FilePath directory;
150 if (GetShmemTempDir(options.executable, &directory)) {
151 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466437
152 // is fixed.
153 tracked_objects::ScopedTracker tracking_profile2(
154 FROM_HERE_WITH_EXPLICIT_FUNCTION(
155 "466437 SharedMemory::Create::OpenTemporaryFile"));
156 fp.reset(CreateAndOpenTemporaryFileInDir(directory, &path));
159 if (fp) {
160 if (options.share_read_only) {
161 // TODO(erikchen): Remove ScopedTracker below once
162 // http://crbug.com/466437 is fixed.
163 tracked_objects::ScopedTracker tracking_profile3(
164 FROM_HERE_WITH_EXPLICIT_FUNCTION(
165 "466437 SharedMemory::Create::OpenReadonly"));
166 // Also open as readonly so that we can ShareReadOnlyToProcess.
167 readonly_fd.reset(HANDLE_EINTR(open(path.value().c_str(), O_RDONLY)));
168 if (!readonly_fd.is_valid()) {
169 DPLOG(ERROR) << "open(\"" << path.value() << "\", O_RDONLY) failed";
170 fp.reset();
171 return false;
175 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466437
176 // is fixed.
177 tracked_objects::ScopedTracker tracking_profile4(
178 FROM_HERE_WITH_EXPLICIT_FUNCTION(
179 "466437 SharedMemory::Create::Unlink"));
180 // Deleting the file prevents anyone else from mapping it in (making it
181 // private), and prevents the need for cleanup (once the last fd is
182 // closed, it is truly freed).
183 if (unlink(path.value().c_str()))
184 PLOG(WARNING) << "unlink";
186 } else {
187 if (!FilePathForMemoryName(*options.name_deprecated, &path))
188 return false;
190 // Make sure that the file is opened without any permission
191 // to other users on the system.
192 const mode_t kOwnerOnly = S_IRUSR | S_IWUSR;
194 // First, try to create the file.
195 int fd = HANDLE_EINTR(
196 open(path.value().c_str(), O_RDWR | O_CREAT | O_EXCL, kOwnerOnly));
197 if (fd == -1 && options.open_existing_deprecated) {
198 // If this doesn't work, try and open an existing file in append mode.
199 // Opening an existing file in a world writable directory has two main
200 // security implications:
201 // - Attackers could plant a file under their control, so ownership of
202 // the file is checked below.
203 // - Attackers could plant a symbolic link so that an unexpected file
204 // is opened, so O_NOFOLLOW is passed to open().
205 fd = HANDLE_EINTR(
206 open(path.value().c_str(), O_RDWR | O_APPEND | O_NOFOLLOW));
208 // Check that the current user owns the file.
209 // If uid != euid, then a more complex permission model is used and this
210 // API is not appropriate.
211 const uid_t real_uid = getuid();
212 const uid_t effective_uid = geteuid();
213 struct stat sb;
214 if (fd >= 0 &&
215 (fstat(fd, &sb) != 0 || sb.st_uid != real_uid ||
216 sb.st_uid != effective_uid)) {
217 LOG(ERROR) <<
218 "Invalid owner when opening existing shared memory file.";
219 close(fd);
220 return false;
223 // An existing file was opened, so its size should not be fixed.
224 fix_size = false;
227 if (options.share_read_only) {
228 // Also open as readonly so that we can ShareReadOnlyToProcess.
229 readonly_fd.reset(HANDLE_EINTR(open(path.value().c_str(), O_RDONLY)));
230 if (!readonly_fd.is_valid()) {
231 DPLOG(ERROR) << "open(\"" << path.value() << "\", O_RDONLY) failed";
232 close(fd);
233 fd = -1;
234 return false;
237 if (fd >= 0) {
238 // "a+" is always appropriate: if it's a new file, a+ is similar to w+.
239 fp.reset(fdopen(fd, "a+"));
242 if (fp && fix_size) {
243 // Get current size.
244 struct stat stat;
245 if (fstat(fileno(fp.get()), &stat) != 0)
246 return false;
247 const size_t current_size = stat.st_size;
248 if (current_size != options.size) {
249 if (HANDLE_EINTR(ftruncate(fileno(fp.get()), options.size)) != 0)
250 return false;
252 requested_size_ = options.size;
254 if (fp == NULL) {
255 #if !defined(OS_MACOSX)
256 PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed";
257 FilePath dir = path.DirName();
258 if (access(dir.value().c_str(), W_OK | X_OK) < 0) {
259 PLOG(ERROR) << "Unable to access(W_OK|X_OK) " << dir.value();
260 if (dir.value() == "/dev/shm") {
261 LOG(FATAL) << "This is frequently caused by incorrect permissions on "
262 << "/dev/shm. Try 'sudo chmod 1777 /dev/shm' to fix.";
265 #else
266 PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed";
267 #endif
268 return false;
271 return PrepareMapFile(fp.Pass(), readonly_fd.Pass());
274 // Our current implementation of shmem is with mmap()ing of files.
275 // These files need to be deleted explicitly.
276 // In practice this call is only needed for unit tests.
277 bool SharedMemory::Delete(const std::string& name) {
278 FilePath path;
279 if (!FilePathForMemoryName(name, &path))
280 return false;
282 if (PathExists(path))
283 return base::DeleteFile(path, false);
285 // Doesn't exist, so success.
286 return true;
289 bool SharedMemory::Open(const std::string& name, bool read_only) {
290 FilePath path;
291 if (!FilePathForMemoryName(name, &path))
292 return false;
294 read_only_ = read_only;
296 const char *mode = read_only ? "r" : "r+";
297 ScopedFILE fp(base::OpenFile(path, mode));
298 ScopedFD readonly_fd(HANDLE_EINTR(open(path.value().c_str(), O_RDONLY)));
299 if (!readonly_fd.is_valid()) {
300 DPLOG(ERROR) << "open(\"" << path.value() << "\", O_RDONLY) failed";
301 return false;
303 return PrepareMapFile(fp.Pass(), readonly_fd.Pass());
305 #endif // !defined(OS_ANDROID)
307 bool SharedMemory::MapAt(off_t offset, size_t bytes) {
308 if (mapped_file_ == -1)
309 return false;
311 if (bytes > static_cast<size_t>(std::numeric_limits<int>::max()))
312 return false;
314 if (memory_)
315 return false;
317 #if defined(OS_ANDROID)
318 // On Android, Map can be called with a size and offset of zero to use the
319 // ashmem-determined size.
320 if (bytes == 0) {
321 DCHECK_EQ(0, offset);
322 int ashmem_bytes = ashmem_get_size_region(mapped_file_);
323 if (ashmem_bytes < 0)
324 return false;
325 bytes = ashmem_bytes;
327 #endif
329 memory_ = mmap(NULL, bytes, PROT_READ | (read_only_ ? 0 : PROT_WRITE),
330 MAP_SHARED, mapped_file_, offset);
332 bool mmap_succeeded = memory_ != (void*)-1 && memory_ != NULL;
333 if (mmap_succeeded) {
334 mapped_size_ = bytes;
335 DCHECK_EQ(0U, reinterpret_cast<uintptr_t>(memory_) &
336 (SharedMemory::MAP_MINIMUM_ALIGNMENT - 1));
337 } else {
338 memory_ = NULL;
341 return mmap_succeeded;
344 bool SharedMemory::Unmap() {
345 if (memory_ == NULL)
346 return false;
348 munmap(memory_, mapped_size_);
349 memory_ = NULL;
350 mapped_size_ = 0;
351 return true;
354 SharedMemoryHandle SharedMemory::handle() const {
355 return FileDescriptor(mapped_file_, false);
358 void SharedMemory::Close() {
359 if (mapped_file_ > 0) {
360 if (close(mapped_file_) < 0)
361 PLOG(ERROR) << "close";
362 mapped_file_ = -1;
364 if (readonly_mapped_file_ > 0) {
365 if (close(readonly_mapped_file_) < 0)
366 PLOG(ERROR) << "close";
367 readonly_mapped_file_ = -1;
371 void SharedMemory::LockDeprecated() {
372 g_thread_lock_.Get().Acquire();
373 LockOrUnlockCommon(F_LOCK);
376 void SharedMemory::UnlockDeprecated() {
377 LockOrUnlockCommon(F_ULOCK);
378 g_thread_lock_.Get().Release();
381 #if !defined(OS_ANDROID)
382 bool SharedMemory::PrepareMapFile(ScopedFILE fp, ScopedFD readonly_fd) {
383 DCHECK_EQ(-1, mapped_file_);
384 DCHECK_EQ(-1, readonly_mapped_file_);
385 if (fp == NULL)
386 return false;
388 // This function theoretically can block on the disk, but realistically
389 // the temporary files we create will just go into the buffer cache
390 // and be deleted before they ever make it out to disk.
391 base::ThreadRestrictions::ScopedAllowIO allow_io;
393 struct stat st = {};
394 if (fstat(fileno(fp.get()), &st))
395 NOTREACHED();
396 if (readonly_fd.is_valid()) {
397 struct stat readonly_st = {};
398 if (fstat(readonly_fd.get(), &readonly_st))
399 NOTREACHED();
400 if (st.st_dev != readonly_st.st_dev || st.st_ino != readonly_st.st_ino) {
401 LOG(ERROR) << "writable and read-only inodes don't match; bailing";
402 return false;
406 mapped_file_ = HANDLE_EINTR(dup(fileno(fp.get())));
407 if (mapped_file_ == -1) {
408 if (errno == EMFILE) {
409 LOG(WARNING) << "Shared memory creation failed; out of file descriptors";
410 return false;
411 } else {
412 NOTREACHED() << "Call to dup failed, errno=" << errno;
415 inode_ = st.st_ino;
416 readonly_mapped_file_ = readonly_fd.release();
418 return true;
421 // For the given shmem named |mem_name|, return a filename to mmap()
422 // (and possibly create). Modifies |filename|. Return false on
423 // error, or true of we are happy.
424 bool SharedMemory::FilePathForMemoryName(const std::string& mem_name,
425 FilePath* path) {
426 // mem_name will be used for a filename; make sure it doesn't
427 // contain anything which will confuse us.
428 DCHECK_EQ(std::string::npos, mem_name.find('/'));
429 DCHECK_EQ(std::string::npos, mem_name.find('\0'));
431 FilePath temp_dir;
432 if (!GetShmemTempDir(false, &temp_dir))
433 return false;
435 #if !defined(OS_MACOSX)
436 #if defined(GOOGLE_CHROME_BUILD)
437 std::string name_base = std::string("com.google.Chrome");
438 #else
439 std::string name_base = std::string("org.chromium.Chromium");
440 #endif
441 #else // OS_MACOSX
442 std::string name_base = std::string(base::mac::BaseBundleID());
443 #endif // OS_MACOSX
444 *path = temp_dir.AppendASCII(name_base + ".shmem." + mem_name);
445 return true;
447 #endif // !defined(OS_ANDROID)
449 void SharedMemory::LockOrUnlockCommon(int function) {
450 DCHECK_GE(mapped_file_, 0);
451 while (lockf(mapped_file_, function, 0) < 0) {
452 if (errno == EINTR) {
453 continue;
454 } else if (errno == ENOLCK) {
455 // temporary kernel resource exaustion
456 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(500));
457 continue;
458 } else {
459 NOTREACHED() << "lockf() failed."
460 << " function:" << function
461 << " fd:" << mapped_file_
462 << " errno:" << errno
463 << " msg:" << safe_strerror(errno);
468 bool SharedMemory::ShareToProcessCommon(ProcessHandle process,
469 SharedMemoryHandle* new_handle,
470 bool close_self,
471 ShareMode share_mode) {
472 int handle_to_dup = -1;
473 switch(share_mode) {
474 case SHARE_CURRENT_MODE:
475 handle_to_dup = mapped_file_;
476 break;
477 case SHARE_READONLY:
478 // We could imagine re-opening the file from /dev/fd, but that can't make
479 // it readonly on Mac: https://codereview.chromium.org/27265002/#msg10
480 CHECK_GE(readonly_mapped_file_, 0);
481 handle_to_dup = readonly_mapped_file_;
482 break;
485 const int new_fd = HANDLE_EINTR(dup(handle_to_dup));
486 if (new_fd < 0) {
487 DPLOG(ERROR) << "dup() failed.";
488 return false;
491 new_handle->fd = new_fd;
492 new_handle->auto_close = true;
494 if (close_self) {
495 Unmap();
496 Close();
499 return true;
502 } // namespace base