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/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/safe_strerror_posix.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/synchronization/lock.h"
22 #include "base/threading/platform_thread.h"
23 #include "base/threading/thread_restrictions.h"
25 #if defined(OS_MACOSX)
26 #include "base/mac/foundation_util.h"
29 #if defined(OS_ANDROID)
30 #include "base/os_compat_android.h"
31 #include "third_party/ashmem/ashmem.h"
38 LazyInstance
<Lock
>::Leaky g_thread_lock_
= LAZY_INSTANCE_INITIALIZER
;
42 SharedMemory::SharedMemory()
44 readonly_mapped_file_(-1),
52 SharedMemory::SharedMemory(SharedMemoryHandle handle
, bool read_only
)
53 : mapped_file_(handle
.fd
),
54 readonly_mapped_file_(-1),
58 read_only_(read_only
),
61 if (fstat(handle
.fd
, &st
) == 0) {
62 // If fstat fails, then the file descriptor is invalid and we'll learn this
63 // fact when Map() fails.
68 SharedMemory::SharedMemory(SharedMemoryHandle handle
, bool read_only
,
69 ProcessHandle process
)
70 : mapped_file_(handle
.fd
),
71 readonly_mapped_file_(-1),
75 read_only_(read_only
),
77 // We don't handle this case yet (note the ignored parameter); let's die if
78 // someone comes calling.
82 SharedMemory::~SharedMemory() {
87 bool SharedMemory::IsHandleValid(const SharedMemoryHandle
& handle
) {
88 return handle
.fd
>= 0;
92 SharedMemoryHandle
SharedMemory::NULLHandle() {
93 return SharedMemoryHandle();
97 void SharedMemory::CloseHandle(const SharedMemoryHandle
& handle
) {
98 DCHECK_GE(handle
.fd
, 0);
99 if (close(handle
.fd
) < 0)
100 DPLOG(ERROR
) << "close";
104 size_t SharedMemory::GetHandleLimit() {
105 return base::GetMaxFds();
108 bool SharedMemory::CreateAndMapAnonymous(size_t size
) {
109 return CreateAnonymous(size
) && Map(size
);
112 #if !defined(OS_ANDROID)
113 // Chromium mostly only uses the unique/private shmem as specified by
114 // "name == L"". The exception is in the StatsTable.
115 // TODO(jrg): there is no way to "clean up" all unused named shmem if
116 // we restart from a crash. (That isn't a new problem, but it is a problem.)
117 // In case we want to delete it later, it may be useful to save the value
118 // of mem_filename after FilePathForMemoryName().
119 bool SharedMemory::Create(const SharedMemoryCreateOptions
& options
) {
120 DCHECK_EQ(-1, mapped_file_
);
121 if (options
.size
== 0) return false;
123 if (options
.size
> static_cast<size_t>(std::numeric_limits
<int>::max()))
126 // This function theoretically can block on the disk, but realistically
127 // the temporary files we create will just go into the buffer cache
128 // and be deleted before they ever make it out to disk.
129 base::ThreadRestrictions::ScopedAllowIO allow_io
;
132 bool fix_size
= true;
133 ScopedFD readonly_fd
;
136 if (options
.name_deprecated
== NULL
|| options
.name_deprecated
->empty()) {
137 // It doesn't make sense to have a open-existing private piece of shmem
138 DCHECK(!options
.open_existing_deprecated
);
139 // Q: Why not use the shm_open() etc. APIs?
140 // A: Because they're limited to 4mb on OS X. FFFFFFFUUUUUUUUUUU
142 if (GetShmemTempDir(options
.executable
, &directory
))
143 fp
.reset(CreateAndOpenTemporaryFileInDir(directory
, &path
));
146 // Also open as readonly so that we can ShareReadOnlyToProcess.
147 readonly_fd
.reset(HANDLE_EINTR(open(path
.value().c_str(), O_RDONLY
)));
148 if (!readonly_fd
.is_valid()) {
149 DPLOG(ERROR
) << "open(\"" << path
.value() << "\", O_RDONLY) failed";
152 // Deleting the file prevents anyone else from mapping it in (making it
153 // private), and prevents the need for cleanup (once the last fd is
154 // closed, it is truly freed).
155 if (unlink(path
.value().c_str()))
156 PLOG(WARNING
) << "unlink";
159 if (!FilePathForMemoryName(*options
.name_deprecated
, &path
))
162 // Make sure that the file is opened without any permission
163 // to other users on the system.
164 const mode_t kOwnerOnly
= S_IRUSR
| S_IWUSR
;
166 // First, try to create the file.
167 int fd
= HANDLE_EINTR(
168 open(path
.value().c_str(), O_RDWR
| O_CREAT
| O_EXCL
, kOwnerOnly
));
169 if (fd
== -1 && options
.open_existing_deprecated
) {
170 // If this doesn't work, try and open an existing file in append mode.
171 // Opening an existing file in a world writable directory has two main
172 // security implications:
173 // - Attackers could plant a file under their control, so ownership of
174 // the file is checked below.
175 // - Attackers could plant a symbolic link so that an unexpected file
176 // is opened, so O_NOFOLLOW is passed to open().
178 open(path
.value().c_str(), O_RDWR
| O_APPEND
| O_NOFOLLOW
));
180 // Check that the current user owns the file.
181 // If uid != euid, then a more complex permission model is used and this
182 // API is not appropriate.
183 const uid_t real_uid
= getuid();
184 const uid_t effective_uid
= geteuid();
187 (fstat(fd
, &sb
) != 0 || sb
.st_uid
!= real_uid
||
188 sb
.st_uid
!= effective_uid
)) {
190 "Invalid owner when opening existing shared memory file.";
195 // An existing file was opened, so its size should not be fixed.
199 // Also open as readonly so that we can ShareReadOnlyToProcess.
200 readonly_fd
.reset(HANDLE_EINTR(open(path
.value().c_str(), O_RDONLY
)));
201 if (!readonly_fd
.is_valid()) {
202 DPLOG(ERROR
) << "open(\"" << path
.value() << "\", O_RDONLY) failed";
207 // "a+" is always appropriate: if it's a new file, a+ is similar to w+.
208 fp
.reset(fdopen(fd
, "a+"));
211 if (fp
&& fix_size
) {
214 if (fstat(fileno(fp
.get()), &stat
) != 0)
216 const size_t current_size
= stat
.st_size
;
217 if (current_size
!= options
.size
) {
218 if (HANDLE_EINTR(ftruncate(fileno(fp
.get()), options
.size
)) != 0)
221 requested_size_
= options
.size
;
224 #if !defined(OS_MACOSX)
225 PLOG(ERROR
) << "Creating shared memory in " << path
.value() << " failed";
226 FilePath dir
= path
.DirName();
227 if (access(dir
.value().c_str(), W_OK
| X_OK
) < 0) {
228 PLOG(ERROR
) << "Unable to access(W_OK|X_OK) " << dir
.value();
229 if (dir
.value() == "/dev/shm") {
230 LOG(FATAL
) << "This is frequently caused by incorrect permissions on "
231 << "/dev/shm. Try 'sudo chmod 1777 /dev/shm' to fix.";
235 PLOG(ERROR
) << "Creating shared memory in " << path
.value() << " failed";
240 return PrepareMapFile(fp
.Pass(), readonly_fd
.Pass());
243 // Our current implementation of shmem is with mmap()ing of files.
244 // These files need to be deleted explicitly.
245 // In practice this call is only needed for unit tests.
246 bool SharedMemory::Delete(const std::string
& name
) {
248 if (!FilePathForMemoryName(name
, &path
))
251 if (PathExists(path
))
252 return base::DeleteFile(path
, false);
254 // Doesn't exist, so success.
258 bool SharedMemory::Open(const std::string
& name
, bool read_only
) {
260 if (!FilePathForMemoryName(name
, &path
))
263 read_only_
= read_only
;
265 const char *mode
= read_only
? "r" : "r+";
266 ScopedFILE
fp(base::OpenFile(path
, mode
));
267 ScopedFD
readonly_fd(HANDLE_EINTR(open(path
.value().c_str(), O_RDONLY
)));
268 if (!readonly_fd
.is_valid()) {
269 DPLOG(ERROR
) << "open(\"" << path
.value() << "\", O_RDONLY) failed";
271 return PrepareMapFile(fp
.Pass(), readonly_fd
.Pass());
273 #endif // !defined(OS_ANDROID)
275 bool SharedMemory::MapAt(off_t offset
, size_t bytes
) {
276 if (mapped_file_
== -1)
279 if (bytes
> static_cast<size_t>(std::numeric_limits
<int>::max()))
285 #if defined(OS_ANDROID)
286 // On Android, Map can be called with a size and offset of zero to use the
287 // ashmem-determined size.
289 DCHECK_EQ(0, offset
);
290 int ashmem_bytes
= ashmem_get_size_region(mapped_file_
);
291 if (ashmem_bytes
< 0)
293 bytes
= ashmem_bytes
;
297 memory_
= mmap(NULL
, bytes
, PROT_READ
| (read_only_
? 0 : PROT_WRITE
),
298 MAP_SHARED
, mapped_file_
, offset
);
300 bool mmap_succeeded
= memory_
!= (void*)-1 && memory_
!= NULL
;
301 if (mmap_succeeded
) {
302 mapped_size_
= bytes
;
303 DCHECK_EQ(0U, reinterpret_cast<uintptr_t>(memory_
) &
304 (SharedMemory::MAP_MINIMUM_ALIGNMENT
- 1));
309 return mmap_succeeded
;
312 bool SharedMemory::Unmap() {
316 munmap(memory_
, mapped_size_
);
322 SharedMemoryHandle
SharedMemory::handle() const {
323 return FileDescriptor(mapped_file_
, false);
326 void SharedMemory::Close() {
329 if (mapped_file_
> 0) {
330 if (close(mapped_file_
) < 0)
331 PLOG(ERROR
) << "close";
334 if (readonly_mapped_file_
> 0) {
335 if (close(readonly_mapped_file_
) < 0)
336 PLOG(ERROR
) << "close";
337 readonly_mapped_file_
= -1;
341 void SharedMemory::LockDeprecated() {
342 g_thread_lock_
.Get().Acquire();
343 LockOrUnlockCommon(F_LOCK
);
346 void SharedMemory::UnlockDeprecated() {
347 LockOrUnlockCommon(F_ULOCK
);
348 g_thread_lock_
.Get().Release();
351 #if !defined(OS_ANDROID)
352 bool SharedMemory::PrepareMapFile(ScopedFILE fp
, ScopedFD readonly_fd
) {
353 DCHECK_EQ(-1, mapped_file_
);
354 DCHECK_EQ(-1, readonly_mapped_file_
);
355 if (fp
== NULL
|| !readonly_fd
.is_valid()) return false;
357 // This function theoretically can block on the disk, but realistically
358 // the temporary files we create will just go into the buffer cache
359 // and be deleted before they ever make it out to disk.
360 base::ThreadRestrictions::ScopedAllowIO allow_io
;
363 struct stat readonly_st
= {};
364 if (fstat(fileno(fp
.get()), &st
))
366 if (fstat(readonly_fd
.get(), &readonly_st
))
368 if (st
.st_dev
!= readonly_st
.st_dev
|| st
.st_ino
!= readonly_st
.st_ino
) {
369 LOG(ERROR
) << "writable and read-only inodes don't match; bailing";
373 mapped_file_
= dup(fileno(fp
.get()));
374 if (mapped_file_
== -1) {
375 if (errno
== EMFILE
) {
376 LOG(WARNING
) << "Shared memory creation failed; out of file descriptors";
379 NOTREACHED() << "Call to dup failed, errno=" << errno
;
383 readonly_mapped_file_
= readonly_fd
.release();
388 // For the given shmem named |mem_name|, return a filename to mmap()
389 // (and possibly create). Modifies |filename|. Return false on
390 // error, or true of we are happy.
391 bool SharedMemory::FilePathForMemoryName(const std::string
& mem_name
,
393 // mem_name will be used for a filename; make sure it doesn't
394 // contain anything which will confuse us.
395 DCHECK_EQ(std::string::npos
, mem_name
.find('/'));
396 DCHECK_EQ(std::string::npos
, mem_name
.find('\0'));
399 if (!GetShmemTempDir(false, &temp_dir
))
402 #if !defined(OS_MACOSX)
403 #if defined(GOOGLE_CHROME_BUILD)
404 std::string name_base
= std::string("com.google.Chrome");
406 std::string name_base
= std::string("org.chromium.Chromium");
409 std::string name_base
= std::string(base::mac::BaseBundleID());
411 *path
= temp_dir
.AppendASCII(name_base
+ ".shmem." + mem_name
);
414 #endif // !defined(OS_ANDROID)
416 void SharedMemory::LockOrUnlockCommon(int function
) {
417 DCHECK_GE(mapped_file_
, 0);
418 while (lockf(mapped_file_
, function
, 0) < 0) {
419 if (errno
== EINTR
) {
421 } else if (errno
== ENOLCK
) {
422 // temporary kernel resource exaustion
423 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(500));
426 NOTREACHED() << "lockf() failed."
427 << " function:" << function
428 << " fd:" << mapped_file_
429 << " errno:" << errno
430 << " msg:" << safe_strerror(errno
);
435 bool SharedMemory::ShareToProcessCommon(ProcessHandle process
,
436 SharedMemoryHandle
* new_handle
,
438 ShareMode share_mode
) {
439 int handle_to_dup
= -1;
441 case SHARE_CURRENT_MODE
:
442 handle_to_dup
= mapped_file_
;
445 // We could imagine re-opening the file from /dev/fd, but that can't make
446 // it readonly on Mac: https://codereview.chromium.org/27265002/#msg10
447 CHECK(readonly_mapped_file_
>= 0);
448 handle_to_dup
= readonly_mapped_file_
;
452 const int new_fd
= dup(handle_to_dup
);
454 DPLOG(ERROR
) << "dup() failed.";
458 new_handle
->fd
= new_fd
;
459 new_handle
->auto_close
= true;