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/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"
30 #if defined(OS_ANDROID)
31 #include "base/os_compat_android.h"
32 #include "third_party/ashmem/ashmem.h"
39 LazyInstance
<Lock
>::Leaky g_thread_lock_
= LAZY_INSTANCE_INITIALIZER
;
43 SharedMemory::SharedMemory()
45 readonly_mapped_file_(-1),
53 SharedMemory::SharedMemory(SharedMemoryHandle handle
, bool read_only
)
54 : mapped_file_(handle
.fd
),
55 readonly_mapped_file_(-1),
59 read_only_(read_only
),
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.
69 SharedMemory::SharedMemory(SharedMemoryHandle handle
, bool read_only
,
70 ProcessHandle process
)
71 : mapped_file_(handle
.fd
),
72 readonly_mapped_file_(-1),
76 read_only_(read_only
),
78 // We don't handle this case yet (note the ignored parameter); let's die if
79 // someone comes calling.
83 SharedMemory::~SharedMemory() {
89 bool SharedMemory::IsHandleValid(const SharedMemoryHandle
& handle
) {
90 return handle
.fd
>= 0;
94 SharedMemoryHandle
SharedMemory::NULLHandle() {
95 return SharedMemoryHandle();
99 void SharedMemory::CloseHandle(const SharedMemoryHandle
& handle
) {
100 DCHECK_GE(handle
.fd
, 0);
101 if (close(handle
.fd
) < 0)
102 DPLOG(ERROR
) << "close";
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
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()))
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
;
139 bool fix_size
= true;
140 ScopedFD readonly_fd
;
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
149 if (GetShmemTempDir(options
.executable
, &directory
)) {
150 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466437
152 tracked_objects::ScopedTracker
tracking_profile2(
153 FROM_HERE_WITH_EXPLICIT_FUNCTION(
154 "466437 SharedMemory::Create::OpenTemporaryFile"));
155 fp
.reset(CreateAndOpenTemporaryFileInDir(directory
, &path
));
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";
174 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466437
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";
186 if (!FilePathForMemoryName(*options
.name_deprecated
, &path
))
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().
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();
214 (fstat(fd
, &sb
) != 0 || sb
.st_uid
!= real_uid
||
215 sb
.st_uid
!= effective_uid
)) {
217 "Invalid owner when opening existing shared memory file.";
222 // An existing file was opened, so its size should not be fixed.
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";
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
) {
244 if (fstat(fileno(fp
.get()), &stat
) != 0)
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)
251 requested_size_
= options
.size
;
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.";
265 PLOG(ERROR
) << "Creating shared memory in " << path
.value() << " failed";
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
) {
278 if (!FilePathForMemoryName(name
, &path
))
281 if (PathExists(path
))
282 return base::DeleteFile(path
, false);
284 // Doesn't exist, so success.
288 bool SharedMemory::Open(const std::string
& name
, bool read_only
) {
290 if (!FilePathForMemoryName(name
, &path
))
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";
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)
310 if (bytes
> static_cast<size_t>(std::numeric_limits
<int>::max()))
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.
320 DCHECK_EQ(0, offset
);
321 int ashmem_bytes
= ashmem_get_size_region(mapped_file_
);
322 if (ashmem_bytes
< 0)
324 bytes
= ashmem_bytes
;
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));
340 return mmap_succeeded
;
343 bool SharedMemory::Unmap() {
347 munmap(memory_
, mapped_size_
);
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";
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_
);
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
;
393 if (fstat(fileno(fp
.get()), &st
))
395 if (readonly_fd
.is_valid()) {
396 struct stat readonly_st
= {};
397 if (fstat(readonly_fd
.get(), &readonly_st
))
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";
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";
411 NOTREACHED() << "Call to dup failed, errno=" << errno
;
415 readonly_mapped_file_
= readonly_fd
.release();
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
,
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'));
431 if (!GetShmemTempDir(false, &temp_dir
))
434 #if !defined(OS_MACOSX)
435 #if defined(GOOGLE_CHROME_BUILD)
436 std::string name_base
= std::string("com.google.Chrome");
438 std::string name_base
= std::string("org.chromium.Chromium");
441 std::string name_base
= std::string(base::mac::BaseBundleID());
443 *path
= temp_dir
.AppendASCII(name_base
+ ".shmem." + mem_name
);
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
) {
453 } else if (errno
== ENOLCK
) {
454 // temporary kernel resource exaustion
455 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(500));
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
,
470 ShareMode share_mode
) {
471 int handle_to_dup
= -1;
473 case SHARE_CURRENT_MODE
:
474 handle_to_dup
= mapped_file_
;
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_
;
484 const int new_fd
= dup(handle_to_dup
);
486 DPLOG(ERROR
) << "dup() failed.";
490 new_handle
->fd
= new_fd
;
491 new_handle
->auto_close
= true;