Add ICU message format support
[chromium-blink-merge.git] / base / memory / shared_memory_posix.cc
blob2e66b34cfcd7b5d3bcf8c0a10c90ea02e6dd28db
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 <fcntl.h>
8 #include <sys/mman.h>
9 #include <sys/stat.h>
10 #include <unistd.h>
12 #include "base/files/file_util.h"
13 #include "base/files/scoped_file.h"
14 #include "base/logging.h"
15 #include "base/posix/eintr_wrapper.h"
16 #include "base/posix/safe_strerror.h"
17 #include "base/process/process_metrics.h"
18 #include "base/profiler/scoped_tracker.h"
19 #include "base/scoped_generic.h"
20 #include "base/strings/utf_string_conversions.h"
22 #if defined(OS_ANDROID)
23 #include "base/os_compat_android.h"
24 #include "third_party/ashmem/ashmem.h"
25 #endif
27 namespace base {
29 namespace {
31 struct ScopedPathUnlinkerTraits {
32 static FilePath* InvalidValue() { return nullptr; }
34 static void Free(FilePath* path) {
35 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466437
36 // is fixed.
37 tracked_objects::ScopedTracker tracking_profile(
38 FROM_HERE_WITH_EXPLICIT_FUNCTION(
39 "466437 SharedMemory::Create::Unlink"));
40 if (unlink(path->value().c_str()))
41 PLOG(WARNING) << "unlink";
45 // Unlinks the FilePath when the object is destroyed.
46 typedef ScopedGeneric<FilePath*, ScopedPathUnlinkerTraits> ScopedPathUnlinker;
48 #if !defined(OS_ANDROID)
49 // Makes a temporary file, fdopens it, and then unlinks it. |fp| is populated
50 // with the fdopened FILE. |readonly_fd| is populated with the opened fd if
51 // options.share_read_only is true. |path| is populated with the location of
52 // the file before it was unlinked.
53 // Returns false if there's an unhandled failure.
54 bool CreateAnonymousSharedMemory(const SharedMemoryCreateOptions& options,
55 ScopedFILE* fp,
56 ScopedFD* readonly_fd,
57 FilePath* path) {
58 // It doesn't make sense to have a open-existing private piece of shmem
59 DCHECK(!options.open_existing_deprecated);
60 // Q: Why not use the shm_open() etc. APIs?
61 // A: Because they're limited to 4mb on OS X. FFFFFFFUUUUUUUUUUU
62 FilePath directory;
63 ScopedPathUnlinker path_unlinker;
64 if (GetShmemTempDir(options.executable, &directory)) {
65 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466437
66 // is fixed.
67 tracked_objects::ScopedTracker tracking_profile(
68 FROM_HERE_WITH_EXPLICIT_FUNCTION(
69 "466437 SharedMemory::Create::OpenTemporaryFile"));
70 fp->reset(base::CreateAndOpenTemporaryFileInDir(directory, path));
72 // Deleting the file prevents anyone else from mapping it in (making it
73 // private), and prevents the need for cleanup (once the last fd is
74 // closed, it is truly freed).
75 if (*fp)
76 path_unlinker.reset(path);
79 if (*fp) {
80 if (options.share_read_only) {
81 // TODO(erikchen): Remove ScopedTracker below once
82 // http://crbug.com/466437 is fixed.
83 tracked_objects::ScopedTracker tracking_profile(
84 FROM_HERE_WITH_EXPLICIT_FUNCTION(
85 "466437 SharedMemory::Create::OpenReadonly"));
86 // Also open as readonly so that we can ShareReadOnlyToProcess.
87 readonly_fd->reset(HANDLE_EINTR(open(path->value().c_str(), O_RDONLY)));
88 if (!readonly_fd->is_valid()) {
89 DPLOG(ERROR) << "open(\"" << path->value() << "\", O_RDONLY) failed";
90 fp->reset();
91 return false;
95 return true;
97 #endif // !defined(OS_ANDROID)
100 SharedMemory::SharedMemory()
101 : mapped_file_(-1),
102 readonly_mapped_file_(-1),
103 mapped_size_(0),
104 memory_(NULL),
105 read_only_(false),
106 requested_size_(0) {
109 SharedMemory::SharedMemory(const SharedMemoryHandle& handle, bool read_only)
110 : mapped_file_(handle.fd),
111 readonly_mapped_file_(-1),
112 mapped_size_(0),
113 memory_(NULL),
114 read_only_(read_only),
115 requested_size_(0) {
118 SharedMemory::SharedMemory(const SharedMemoryHandle& handle,
119 bool read_only,
120 ProcessHandle process)
121 : mapped_file_(handle.fd),
122 readonly_mapped_file_(-1),
123 mapped_size_(0),
124 memory_(NULL),
125 read_only_(read_only),
126 requested_size_(0) {
127 // We don't handle this case yet (note the ignored parameter); let's die if
128 // someone comes calling.
129 NOTREACHED();
132 SharedMemory::~SharedMemory() {
133 Unmap();
134 Close();
137 // static
138 bool SharedMemory::IsHandleValid(const SharedMemoryHandle& handle) {
139 return handle.fd >= 0;
142 // static
143 SharedMemoryHandle SharedMemory::NULLHandle() {
144 return SharedMemoryHandle();
147 // static
148 void SharedMemory::CloseHandle(const SharedMemoryHandle& handle) {
149 DCHECK_GE(handle.fd, 0);
150 if (close(handle.fd) < 0)
151 DPLOG(ERROR) << "close";
154 // static
155 size_t SharedMemory::GetHandleLimit() {
156 return base::GetMaxFds();
159 // static
160 SharedMemoryHandle SharedMemory::DuplicateHandle(
161 const SharedMemoryHandle& handle) {
162 int duped_handle = HANDLE_EINTR(dup(handle.fd));
163 if (duped_handle < 0)
164 return base::SharedMemory::NULLHandle();
165 return base::FileDescriptor(duped_handle, true);
168 // static
169 int SharedMemory::GetFdFromSharedMemoryHandle(
170 const SharedMemoryHandle& handle) {
171 return handle.fd;
174 bool SharedMemory::CreateAndMapAnonymous(size_t size) {
175 return CreateAnonymous(size) && Map(size);
178 #if !defined(OS_ANDROID)
179 // static
180 int SharedMemory::GetSizeFromSharedMemoryHandle(
181 const SharedMemoryHandle& handle) {
182 struct stat st;
183 if (fstat(handle.fd, &st) != 0)
184 return -1;
185 return st.st_size;
188 // Chromium mostly only uses the unique/private shmem as specified by
189 // "name == L"". The exception is in the StatsTable.
190 // TODO(jrg): there is no way to "clean up" all unused named shmem if
191 // we restart from a crash. (That isn't a new problem, but it is a problem.)
192 // In case we want to delete it later, it may be useful to save the value
193 // of mem_filename after FilePathForMemoryName().
194 bool SharedMemory::Create(const SharedMemoryCreateOptions& options) {
195 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466437
196 // is fixed.
197 tracked_objects::ScopedTracker tracking_profile1(
198 FROM_HERE_WITH_EXPLICIT_FUNCTION(
199 "466437 SharedMemory::Create::Start"));
200 DCHECK_EQ(-1, mapped_file_);
201 if (options.size == 0) return false;
203 if (options.size > static_cast<size_t>(std::numeric_limits<int>::max()))
204 return false;
206 // This function theoretically can block on the disk, but realistically
207 // the temporary files we create will just go into the buffer cache
208 // and be deleted before they ever make it out to disk.
209 base::ThreadRestrictions::ScopedAllowIO allow_io;
211 ScopedFILE fp;
212 bool fix_size = true;
213 ScopedFD readonly_fd;
215 FilePath path;
216 if (options.name_deprecated == NULL || options.name_deprecated->empty()) {
217 bool result =
218 CreateAnonymousSharedMemory(options, &fp, &readonly_fd, &path);
219 if (!result)
220 return false;
221 } else {
222 if (!FilePathForMemoryName(*options.name_deprecated, &path))
223 return false;
225 // Make sure that the file is opened without any permission
226 // to other users on the system.
227 const mode_t kOwnerOnly = S_IRUSR | S_IWUSR;
229 // First, try to create the file.
230 int fd = HANDLE_EINTR(
231 open(path.value().c_str(), O_RDWR | O_CREAT | O_EXCL, kOwnerOnly));
232 if (fd == -1 && options.open_existing_deprecated) {
233 // If this doesn't work, try and open an existing file in append mode.
234 // Opening an existing file in a world writable directory has two main
235 // security implications:
236 // - Attackers could plant a file under their control, so ownership of
237 // the file is checked below.
238 // - Attackers could plant a symbolic link so that an unexpected file
239 // is opened, so O_NOFOLLOW is passed to open().
240 fd = HANDLE_EINTR(
241 open(path.value().c_str(), O_RDWR | O_APPEND | O_NOFOLLOW));
243 // Check that the current user owns the file.
244 // If uid != euid, then a more complex permission model is used and this
245 // API is not appropriate.
246 const uid_t real_uid = getuid();
247 const uid_t effective_uid = geteuid();
248 struct stat sb;
249 if (fd >= 0 &&
250 (fstat(fd, &sb) != 0 || sb.st_uid != real_uid ||
251 sb.st_uid != effective_uid)) {
252 LOG(ERROR) <<
253 "Invalid owner when opening existing shared memory file.";
254 close(fd);
255 return false;
258 // An existing file was opened, so its size should not be fixed.
259 fix_size = false;
262 if (options.share_read_only) {
263 // Also open as readonly so that we can ShareReadOnlyToProcess.
264 readonly_fd.reset(HANDLE_EINTR(open(path.value().c_str(), O_RDONLY)));
265 if (!readonly_fd.is_valid()) {
266 DPLOG(ERROR) << "open(\"" << path.value() << "\", O_RDONLY) failed";
267 close(fd);
268 fd = -1;
269 return false;
272 if (fd >= 0) {
273 // "a+" is always appropriate: if it's a new file, a+ is similar to w+.
274 fp.reset(fdopen(fd, "a+"));
277 if (fp && fix_size) {
278 // Get current size.
279 struct stat stat;
280 if (fstat(fileno(fp.get()), &stat) != 0)
281 return false;
282 const size_t current_size = stat.st_size;
283 if (current_size != options.size) {
284 if (HANDLE_EINTR(ftruncate(fileno(fp.get()), options.size)) != 0)
285 return false;
287 requested_size_ = options.size;
289 if (fp == NULL) {
290 PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed";
291 FilePath dir = path.DirName();
292 if (access(dir.value().c_str(), W_OK | X_OK) < 0) {
293 PLOG(ERROR) << "Unable to access(W_OK|X_OK) " << dir.value();
294 if (dir.value() == "/dev/shm") {
295 LOG(FATAL) << "This is frequently caused by incorrect permissions on "
296 << "/dev/shm. Try 'sudo chmod 1777 /dev/shm' to fix.";
299 return false;
302 return PrepareMapFile(fp.Pass(), readonly_fd.Pass());
305 // Our current implementation of shmem is with mmap()ing of files.
306 // These files need to be deleted explicitly.
307 // In practice this call is only needed for unit tests.
308 bool SharedMemory::Delete(const std::string& name) {
309 FilePath path;
310 if (!FilePathForMemoryName(name, &path))
311 return false;
313 if (PathExists(path))
314 return base::DeleteFile(path, false);
316 // Doesn't exist, so success.
317 return true;
320 bool SharedMemory::Open(const std::string& name, bool read_only) {
321 FilePath path;
322 if (!FilePathForMemoryName(name, &path))
323 return false;
325 read_only_ = read_only;
327 const char *mode = read_only ? "r" : "r+";
328 ScopedFILE fp(base::OpenFile(path, mode));
329 ScopedFD readonly_fd(HANDLE_EINTR(open(path.value().c_str(), O_RDONLY)));
330 if (!readonly_fd.is_valid()) {
331 DPLOG(ERROR) << "open(\"" << path.value() << "\", O_RDONLY) failed";
332 return false;
334 return PrepareMapFile(fp.Pass(), readonly_fd.Pass());
336 #endif // !defined(OS_ANDROID)
338 bool SharedMemory::MapAt(off_t offset, size_t bytes) {
339 if (mapped_file_ == -1)
340 return false;
342 if (bytes > static_cast<size_t>(std::numeric_limits<int>::max()))
343 return false;
345 if (memory_)
346 return false;
348 #if defined(OS_ANDROID)
349 // On Android, Map can be called with a size and offset of zero to use the
350 // ashmem-determined size.
351 if (bytes == 0) {
352 DCHECK_EQ(0, offset);
353 int ashmem_bytes = ashmem_get_size_region(mapped_file_);
354 if (ashmem_bytes < 0)
355 return false;
356 bytes = ashmem_bytes;
358 #endif
360 memory_ = mmap(NULL, bytes, PROT_READ | (read_only_ ? 0 : PROT_WRITE),
361 MAP_SHARED, mapped_file_, offset);
363 bool mmap_succeeded = memory_ != (void*)-1 && memory_ != NULL;
364 if (mmap_succeeded) {
365 mapped_size_ = bytes;
366 DCHECK_EQ(0U, reinterpret_cast<uintptr_t>(memory_) &
367 (SharedMemory::MAP_MINIMUM_ALIGNMENT - 1));
368 } else {
369 memory_ = NULL;
372 return mmap_succeeded;
375 bool SharedMemory::Unmap() {
376 if (memory_ == NULL)
377 return false;
379 munmap(memory_, mapped_size_);
380 memory_ = NULL;
381 mapped_size_ = 0;
382 return true;
385 SharedMemoryHandle SharedMemory::handle() const {
386 return FileDescriptor(mapped_file_, false);
389 void SharedMemory::Close() {
390 if (mapped_file_ > 0) {
391 if (close(mapped_file_) < 0)
392 PLOG(ERROR) << "close";
393 mapped_file_ = -1;
395 if (readonly_mapped_file_ > 0) {
396 if (close(readonly_mapped_file_) < 0)
397 PLOG(ERROR) << "close";
398 readonly_mapped_file_ = -1;
402 #if !defined(OS_ANDROID)
403 bool SharedMemory::PrepareMapFile(ScopedFILE fp, ScopedFD readonly_fd) {
404 DCHECK_EQ(-1, mapped_file_);
405 DCHECK_EQ(-1, readonly_mapped_file_);
406 if (fp == NULL)
407 return false;
409 // This function theoretically can block on the disk, but realistically
410 // the temporary files we create will just go into the buffer cache
411 // and be deleted before they ever make it out to disk.
412 base::ThreadRestrictions::ScopedAllowIO allow_io;
414 struct stat st = {};
415 if (fstat(fileno(fp.get()), &st))
416 NOTREACHED();
417 if (readonly_fd.is_valid()) {
418 struct stat readonly_st = {};
419 if (fstat(readonly_fd.get(), &readonly_st))
420 NOTREACHED();
421 if (st.st_dev != readonly_st.st_dev || st.st_ino != readonly_st.st_ino) {
422 LOG(ERROR) << "writable and read-only inodes don't match; bailing";
423 return false;
427 mapped_file_ = HANDLE_EINTR(dup(fileno(fp.get())));
428 if (mapped_file_ == -1) {
429 if (errno == EMFILE) {
430 LOG(WARNING) << "Shared memory creation failed; out of file descriptors";
431 return false;
432 } else {
433 NOTREACHED() << "Call to dup failed, errno=" << errno;
436 readonly_mapped_file_ = readonly_fd.release();
438 return true;
441 // For the given shmem named |mem_name|, return a filename to mmap()
442 // (and possibly create). Modifies |filename|. Return false on
443 // error, or true of we are happy.
444 bool SharedMemory::FilePathForMemoryName(const std::string& mem_name,
445 FilePath* path) {
446 // mem_name will be used for a filename; make sure it doesn't
447 // contain anything which will confuse us.
448 DCHECK_EQ(std::string::npos, mem_name.find('/'));
449 DCHECK_EQ(std::string::npos, mem_name.find('\0'));
451 FilePath temp_dir;
452 if (!GetShmemTempDir(false, &temp_dir))
453 return false;
455 #if defined(GOOGLE_CHROME_BUILD)
456 std::string name_base = std::string("com.google.Chrome");
457 #else
458 std::string name_base = std::string("org.chromium.Chromium");
459 #endif
460 *path = temp_dir.AppendASCII(name_base + ".shmem." + mem_name);
461 return true;
463 #endif // !defined(OS_ANDROID)
465 bool SharedMemory::ShareToProcessCommon(ProcessHandle process,
466 SharedMemoryHandle* new_handle,
467 bool close_self,
468 ShareMode share_mode) {
469 int handle_to_dup = -1;
470 switch(share_mode) {
471 case SHARE_CURRENT_MODE:
472 handle_to_dup = mapped_file_;
473 break;
474 case SHARE_READONLY:
475 // We could imagine re-opening the file from /dev/fd, but that can't make
476 // it readonly on Mac: https://codereview.chromium.org/27265002/#msg10
477 CHECK_GE(readonly_mapped_file_, 0);
478 handle_to_dup = readonly_mapped_file_;
479 break;
482 const int new_fd = HANDLE_EINTR(dup(handle_to_dup));
483 if (new_fd < 0) {
484 DPLOG(ERROR) << "dup() failed.";
485 return false;
488 new_handle->fd = new_fd;
489 new_handle->auto_close = true;
491 if (close_self) {
492 Unmap();
493 Close();
496 return true;
499 } // namespace base