rAc - revert invalid suggestions to edit mode
[chromium-blink-merge.git] / base / memory / shared_memory_posix.cc
blob8ef911c23ff35d4523befd2257d5723a90a3aca2
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/lazy_instance.h"
16 #include "base/logging.h"
17 #include "base/process/process_metrics.h"
18 #include "base/safe_strerror_posix.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "base/synchronization/lock.h"
21 #include "base/threading/platform_thread.h"
22 #include "base/threading/thread_restrictions.h"
24 #if defined(OS_MACOSX)
25 #include "base/mac/foundation_util.h"
26 #endif // OS_MACOSX
28 #if defined(OS_ANDROID)
29 #include "base/os_compat_android.h"
30 #include "third_party/ashmem/ashmem.h"
31 #endif
33 using file_util::ScopedFD;
34 using file_util::ScopedFILE;
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 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 DCHECK_EQ(-1, mapped_file_);
123 if (options.size == 0) return false;
125 if (options.size > static_cast<size_t>(std::numeric_limits<int>::max()))
126 return false;
128 // This function theoretically can block on the disk, but realistically
129 // the temporary files we create will just go into the buffer cache
130 // and be deleted before they ever make it out to disk.
131 base::ThreadRestrictions::ScopedAllowIO allow_io;
133 ScopedFILE fp;
134 bool fix_size = true;
135 int readonly_fd_storage = -1;
136 ScopedFD readonly_fd(&readonly_fd_storage);
138 FilePath path;
139 if (options.name == NULL || options.name->empty()) {
140 // It doesn't make sense to have a open-existing private piece of shmem
141 DCHECK(!options.open_existing);
142 // Q: Why not use the shm_open() etc. APIs?
143 // A: Because they're limited to 4mb on OS X. FFFFFFFUUUUUUUUUUU
144 fp.reset(base::CreateAndOpenTemporaryShmemFile(&path, options.executable));
146 if (fp) {
147 // Also open as readonly so that we can ShareReadOnlyToProcess.
148 *readonly_fd = HANDLE_EINTR(open(path.value().c_str(), O_RDONLY));
149 if (*readonly_fd < 0) {
150 DPLOG(ERROR) << "open(\"" << path.value() << "\", O_RDONLY) failed";
151 fp.reset();
153 // Deleting the file prevents anyone else from mapping it in (making it
154 // private), and prevents the need for cleanup (once the last fd is
155 // closed, it is truly freed).
156 if (unlink(path.value().c_str()))
157 PLOG(WARNING) << "unlink";
159 } else {
160 if (!FilePathForMemoryName(*options.name, &path))
161 return false;
163 // Make sure that the file is opened without any permission
164 // to other users on the system.
165 const mode_t kOwnerOnly = S_IRUSR | S_IWUSR;
167 // First, try to create the file.
168 int fd = HANDLE_EINTR(
169 open(path.value().c_str(), O_RDWR | O_CREAT | O_EXCL, kOwnerOnly));
170 if (fd == -1 && options.open_existing) {
171 // If this doesn't work, try and open an existing file in append mode.
172 // Opening an existing file in a world writable directory has two main
173 // security implications:
174 // - Attackers could plant a file under their control, so ownership of
175 // the file is checked below.
176 // - Attackers could plant a symbolic link so that an unexpected file
177 // is opened, so O_NOFOLLOW is passed to open().
178 fd = HANDLE_EINTR(
179 open(path.value().c_str(), O_RDWR | O_APPEND | O_NOFOLLOW));
181 // Check that the current user owns the file.
182 // If uid != euid, then a more complex permission model is used and this
183 // API is not appropriate.
184 const uid_t real_uid = getuid();
185 const uid_t effective_uid = geteuid();
186 struct stat sb;
187 if (fd >= 0 &&
188 (fstat(fd, &sb) != 0 || sb.st_uid != real_uid ||
189 sb.st_uid != effective_uid)) {
190 LOG(ERROR) <<
191 "Invalid owner when opening existing shared memory file.";
192 close(fd);
193 return false;
196 // An existing file was opened, so its size should not be fixed.
197 fix_size = false;
200 // Also open as readonly so that we can ShareReadOnlyToProcess.
201 *readonly_fd = HANDLE_EINTR(open(path.value().c_str(), O_RDONLY));
202 if (*readonly_fd < 0) {
203 DPLOG(ERROR) << "open(\"" << path.value() << "\", O_RDONLY) failed";
204 close(fd);
205 fd = -1;
207 if (fd >= 0) {
208 // "a+" is always appropriate: if it's a new file, a+ is similar to w+.
209 fp.reset(fdopen(fd, "a+"));
212 if (fp && fix_size) {
213 // Get current size.
214 struct stat stat;
215 if (fstat(fileno(fp.get()), &stat) != 0)
216 return false;
217 const size_t current_size = stat.st_size;
218 if (current_size != options.size) {
219 if (HANDLE_EINTR(ftruncate(fileno(fp.get()), options.size)) != 0)
220 return false;
222 requested_size_ = options.size;
224 if (fp == NULL) {
225 #if !defined(OS_MACOSX)
226 PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed";
227 FilePath dir = path.DirName();
228 if (access(dir.value().c_str(), W_OK | X_OK) < 0) {
229 PLOG(ERROR) << "Unable to access(W_OK|X_OK) " << dir.value();
230 if (dir.value() == "/dev/shm") {
231 LOG(FATAL) << "This is frequently caused by incorrect permissions on "
232 << "/dev/shm. Try 'sudo chmod 1777 /dev/shm' to fix.";
235 #else
236 PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed";
237 #endif
238 return false;
241 return PrepareMapFile(fp.Pass(), readonly_fd.Pass());
244 // Our current implementation of shmem is with mmap()ing of files.
245 // These files need to be deleted explicitly.
246 // In practice this call is only needed for unit tests.
247 bool SharedMemory::Delete(const std::string& name) {
248 FilePath path;
249 if (!FilePathForMemoryName(name, &path))
250 return false;
252 if (PathExists(path))
253 return base::DeleteFile(path, false);
255 // Doesn't exist, so success.
256 return true;
259 bool SharedMemory::Open(const std::string& name, bool read_only) {
260 FilePath path;
261 if (!FilePathForMemoryName(name, &path))
262 return false;
264 read_only_ = read_only;
266 const char *mode = read_only ? "r" : "r+";
267 ScopedFILE fp(base::OpenFile(path, mode));
268 int readonly_fd_storage = -1;
269 ScopedFD readonly_fd(&readonly_fd_storage);
270 *readonly_fd = HANDLE_EINTR(open(path.value().c_str(), O_RDONLY));
271 if (*readonly_fd < 0) {
272 DPLOG(ERROR) << "open(\"" << path.value() << "\", O_RDONLY) failed";
274 return PrepareMapFile(fp.Pass(), readonly_fd.Pass());
277 #endif // !defined(OS_ANDROID)
279 bool SharedMemory::MapAt(off_t offset, size_t bytes) {
280 if (mapped_file_ == -1)
281 return false;
283 if (bytes > static_cast<size_t>(std::numeric_limits<int>::max()))
284 return false;
286 #if defined(OS_ANDROID)
287 // On Android, Map can be called with a size and offset of zero to use the
288 // ashmem-determined size.
289 if (bytes == 0) {
290 DCHECK_EQ(0, offset);
291 int ashmem_bytes = ashmem_get_size_region(mapped_file_);
292 if (ashmem_bytes < 0)
293 return false;
294 bytes = ashmem_bytes;
296 #endif
298 memory_ = mmap(NULL, bytes, PROT_READ | (read_only_ ? 0 : PROT_WRITE),
299 MAP_SHARED, mapped_file_, offset);
301 bool mmap_succeeded = memory_ != (void*)-1 && memory_ != NULL;
302 if (mmap_succeeded) {
303 mapped_size_ = bytes;
304 DCHECK_EQ(0U, reinterpret_cast<uintptr_t>(memory_) &
305 (SharedMemory::MAP_MINIMUM_ALIGNMENT - 1));
306 } else {
307 memory_ = NULL;
310 return mmap_succeeded;
313 bool SharedMemory::Unmap() {
314 if (memory_ == NULL)
315 return false;
317 munmap(memory_, mapped_size_);
318 memory_ = NULL;
319 mapped_size_ = 0;
320 return true;
323 SharedMemoryHandle SharedMemory::handle() const {
324 return FileDescriptor(mapped_file_, false);
327 void SharedMemory::Close() {
328 Unmap();
330 if (mapped_file_ > 0) {
331 if (close(mapped_file_) < 0)
332 PLOG(ERROR) << "close";
333 mapped_file_ = -1;
335 if (readonly_mapped_file_ > 0) {
336 if (close(readonly_mapped_file_) < 0)
337 PLOG(ERROR) << "close";
338 readonly_mapped_file_ = -1;
342 void SharedMemory::LockDeprecated() {
343 g_thread_lock_.Get().Acquire();
344 LockOrUnlockCommon(F_LOCK);
347 void SharedMemory::UnlockDeprecated() {
348 LockOrUnlockCommon(F_ULOCK);
349 g_thread_lock_.Get().Release();
352 #if !defined(OS_ANDROID)
353 bool SharedMemory::PrepareMapFile(ScopedFILE fp, ScopedFD readonly_fd) {
354 DCHECK_EQ(-1, mapped_file_);
355 DCHECK_EQ(-1, readonly_mapped_file_);
356 if (fp == NULL || *readonly_fd < 0) return false;
358 // This function theoretically can block on the disk, but realistically
359 // the temporary files we create will just go into the buffer cache
360 // and be deleted before they ever make it out to disk.
361 base::ThreadRestrictions::ScopedAllowIO allow_io;
363 struct stat st = {};
364 struct stat readonly_st = {};
365 if (fstat(fileno(fp.get()), &st))
366 NOTREACHED();
367 if (fstat(*readonly_fd, &readonly_st))
368 NOTREACHED();
369 if (st.st_dev != readonly_st.st_dev || st.st_ino != readonly_st.st_ino) {
370 LOG(ERROR) << "writable and read-only inodes don't match; bailing";
371 return false;
374 mapped_file_ = dup(fileno(fp.get()));
375 if (mapped_file_ == -1) {
376 if (errno == EMFILE) {
377 LOG(WARNING) << "Shared memory creation failed; out of file descriptors";
378 return false;
379 } else {
380 NOTREACHED() << "Call to dup failed, errno=" << errno;
383 inode_ = st.st_ino;
384 readonly_mapped_file_ = *readonly_fd.release();
386 return true;
388 #endif
390 // For the given shmem named |mem_name|, return a filename to mmap()
391 // (and possibly create). Modifies |filename|. Return false on
392 // error, or true of we are happy.
393 bool SharedMemory::FilePathForMemoryName(const std::string& mem_name,
394 FilePath* path) {
395 // mem_name will be used for a filename; make sure it doesn't
396 // contain anything which will confuse us.
397 DCHECK_EQ(std::string::npos, mem_name.find('/'));
398 DCHECK_EQ(std::string::npos, mem_name.find('\0'));
400 FilePath temp_dir;
401 if (!GetShmemTempDir(false, &temp_dir))
402 return false;
404 #if !defined(OS_MACOSX)
405 #if defined(GOOGLE_CHROME_BUILD)
406 std::string name_base = std::string("com.google.Chrome");
407 #else
408 std::string name_base = std::string("org.chromium.Chromium");
409 #endif
410 #else // OS_MACOSX
411 std::string name_base = std::string(base::mac::BaseBundleID());
412 #endif // OS_MACOSX
413 *path = temp_dir.AppendASCII(name_base + ".shmem." + mem_name);
414 return true;
417 void SharedMemory::LockOrUnlockCommon(int function) {
418 DCHECK_GE(mapped_file_, 0);
419 while (lockf(mapped_file_, function, 0) < 0) {
420 if (errno == EINTR) {
421 continue;
422 } else if (errno == ENOLCK) {
423 // temporary kernel resource exaustion
424 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(500));
425 continue;
426 } else {
427 NOTREACHED() << "lockf() failed."
428 << " function:" << function
429 << " fd:" << mapped_file_
430 << " errno:" << errno
431 << " msg:" << safe_strerror(errno);
436 bool SharedMemory::ShareToProcessCommon(ProcessHandle process,
437 SharedMemoryHandle* new_handle,
438 bool close_self,
439 ShareMode share_mode) {
440 int handle_to_dup = -1;
441 switch(share_mode) {
442 case SHARE_CURRENT_MODE:
443 handle_to_dup = mapped_file_;
444 break;
445 case SHARE_READONLY:
446 // We could imagine re-opening the file from /dev/fd, but that can't make
447 // it readonly on Mac: https://codereview.chromium.org/27265002/#msg10
448 CHECK(readonly_mapped_file_ >= 0);
449 handle_to_dup = readonly_mapped_file_;
450 break;
453 const int new_fd = dup(handle_to_dup);
454 if (new_fd < 0) {
455 DPLOG(ERROR) << "dup() failed.";
456 return false;
459 new_handle->fd = new_fd;
460 new_handle->auto_close = true;
462 if (close_self)
463 Close();
465 return true;
468 } // namespace base