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