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"
11 #include <sys/types.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"
31 #if defined(OS_ANDROID)
32 #include "base/os_compat_android.h"
33 #include "third_party/ashmem/ashmem.h"
40 LazyInstance
<Lock
>::Leaky g_thread_lock_
= LAZY_INSTANCE_INITIALIZER
;
44 SharedMemory::SharedMemory()
46 readonly_mapped_file_(-1),
54 SharedMemory::SharedMemory(SharedMemoryHandle handle
, bool read_only
)
55 : mapped_file_(handle
.fd
),
56 readonly_mapped_file_(-1),
60 read_only_(read_only
),
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.
70 SharedMemory::SharedMemory(SharedMemoryHandle handle
, bool read_only
,
71 ProcessHandle process
)
72 : mapped_file_(handle
.fd
),
73 readonly_mapped_file_(-1),
77 read_only_(read_only
),
79 // We don't handle this case yet (note the ignored parameter); let's die if
80 // someone comes calling.
84 SharedMemory::~SharedMemory() {
90 bool SharedMemory::IsHandleValid(const SharedMemoryHandle
& handle
) {
91 return handle
.fd
>= 0;
95 SharedMemoryHandle
SharedMemory::NULLHandle() {
96 return SharedMemoryHandle();
100 void SharedMemory::CloseHandle(const SharedMemoryHandle
& handle
) {
101 DCHECK_GE(handle
.fd
, 0);
102 if (close(handle
.fd
) < 0)
103 DPLOG(ERROR
) << "close";
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
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()))
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
;
140 bool fix_size
= true;
141 ScopedFD readonly_fd
;
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
150 if (GetShmemTempDir(options
.executable
, &directory
)) {
151 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466437
153 tracked_objects::ScopedTracker
tracking_profile2(
154 FROM_HERE_WITH_EXPLICIT_FUNCTION(
155 "466437 SharedMemory::Create::OpenTemporaryFile"));
156 fp
.reset(CreateAndOpenTemporaryFileInDir(directory
, &path
));
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";
175 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466437
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";
187 if (!FilePathForMemoryName(*options
.name_deprecated
, &path
))
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().
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();
215 (fstat(fd
, &sb
) != 0 || sb
.st_uid
!= real_uid
||
216 sb
.st_uid
!= effective_uid
)) {
218 "Invalid owner when opening existing shared memory file.";
223 // An existing file was opened, so its size should not be fixed.
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";
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
) {
245 if (fstat(fileno(fp
.get()), &stat
) != 0)
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)
252 requested_size_
= options
.size
;
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.";
266 PLOG(ERROR
) << "Creating shared memory in " << path
.value() << " failed";
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
) {
279 if (!FilePathForMemoryName(name
, &path
))
282 if (PathExists(path
))
283 return base::DeleteFile(path
, false);
285 // Doesn't exist, so success.
289 bool SharedMemory::Open(const std::string
& name
, bool read_only
) {
291 if (!FilePathForMemoryName(name
, &path
))
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";
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)
311 if (bytes
> static_cast<size_t>(std::numeric_limits
<int>::max()))
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.
321 DCHECK_EQ(0, offset
);
322 int ashmem_bytes
= ashmem_get_size_region(mapped_file_
);
323 if (ashmem_bytes
< 0)
325 bytes
= ashmem_bytes
;
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));
341 return mmap_succeeded
;
344 bool SharedMemory::Unmap() {
348 munmap(memory_
, mapped_size_
);
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";
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_
);
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
;
394 if (fstat(fileno(fp
.get()), &st
))
396 if (readonly_fd
.is_valid()) {
397 struct stat readonly_st
= {};
398 if (fstat(readonly_fd
.get(), &readonly_st
))
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";
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";
412 NOTREACHED() << "Call to dup failed, errno=" << errno
;
416 readonly_mapped_file_
= readonly_fd
.release();
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
,
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'));
432 if (!GetShmemTempDir(false, &temp_dir
))
435 #if !defined(OS_MACOSX)
436 #if defined(GOOGLE_CHROME_BUILD)
437 std::string name_base
= std::string("com.google.Chrome");
439 std::string name_base
= std::string("org.chromium.Chromium");
442 std::string name_base
= std::string(base::mac::BaseBundleID());
444 *path
= temp_dir
.AppendASCII(name_base
+ ".shmem." + mem_name
);
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
) {
454 } else if (errno
== ENOLCK
) {
455 // temporary kernel resource exaustion
456 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(500));
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
,
471 ShareMode share_mode
) {
472 int handle_to_dup
= -1;
474 case SHARE_CURRENT_MODE
:
475 handle_to_dup
= mapped_file_
;
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_
;
485 const int new_fd
= HANDLE_EINTR(dup(handle_to_dup
));
487 DPLOG(ERROR
) << "dup() failed.";
491 new_handle
->fd
= new_fd
;
492 new_handle
->auto_close
= true;