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/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"
28 #if defined(OS_ANDROID)
29 #include "base/os_compat_android.h"
30 #include "third_party/ashmem/ashmem.h"
33 using file_util::ScopedFD
;
34 using file_util::ScopedFILE
;
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() {
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 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()))
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
;
134 bool fix_size
= true;
135 int readonly_fd_storage
= -1;
136 ScopedFD
readonly_fd(&readonly_fd_storage
);
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
));
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";
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";
160 if (!FilePathForMemoryName(*options
.name
, &path
))
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().
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();
188 (fstat(fd
, &sb
) != 0 || sb
.st_uid
!= real_uid
||
189 sb
.st_uid
!= effective_uid
)) {
191 "Invalid owner when opening existing shared memory file.";
196 // An existing file was opened, so its size should not be fixed.
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";
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
) {
215 if (fstat(fileno(fp
.get()), &stat
) != 0)
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)
222 requested_size_
= options
.size
;
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.";
236 PLOG(ERROR
) << "Creating shared memory in " << path
.value() << " failed";
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
) {
249 if (!FilePathForMemoryName(name
, &path
))
252 if (PathExists(path
))
253 return base::DeleteFile(path
, false);
255 // Doesn't exist, so success.
259 bool SharedMemory::Open(const std::string
& name
, bool read_only
) {
261 if (!FilePathForMemoryName(name
, &path
))
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)
283 if (bytes
> static_cast<size_t>(std::numeric_limits
<int>::max()))
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.
290 DCHECK_EQ(0, offset
);
291 int ashmem_bytes
= ashmem_get_size_region(mapped_file_
);
292 if (ashmem_bytes
< 0)
294 bytes
= ashmem_bytes
;
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));
310 return mmap_succeeded
;
313 bool SharedMemory::Unmap() {
317 munmap(memory_
, mapped_size_
);
323 SharedMemoryHandle
SharedMemory::handle() const {
324 return FileDescriptor(mapped_file_
, false);
327 void SharedMemory::Close() {
330 if (mapped_file_
> 0) {
331 if (close(mapped_file_
) < 0)
332 PLOG(ERROR
) << "close";
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
;
364 struct stat readonly_st
= {};
365 if (fstat(fileno(fp
.get()), &st
))
367 if (fstat(*readonly_fd
, &readonly_st
))
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";
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";
380 NOTREACHED() << "Call to dup failed, errno=" << errno
;
384 readonly_mapped_file_
= *readonly_fd
.release();
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
,
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'));
401 if (!GetShmemTempDir(false, &temp_dir
))
404 #if !defined(OS_MACOSX)
405 #if defined(GOOGLE_CHROME_BUILD)
406 std::string name_base
= std::string("com.google.Chrome");
408 std::string name_base
= std::string("org.chromium.Chromium");
411 std::string name_base
= std::string(base::mac::BaseBundleID());
413 *path
= temp_dir
.AppendASCII(name_base
+ ".shmem." + mem_name
);
417 void SharedMemory::LockOrUnlockCommon(int function
) {
418 DCHECK_GE(mapped_file_
, 0);
419 while (lockf(mapped_file_
, function
, 0) < 0) {
420 if (errno
== EINTR
) {
422 } else if (errno
== ENOLCK
) {
423 // temporary kernel resource exaustion
424 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(500));
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
,
439 ShareMode share_mode
) {
440 int handle_to_dup
= -1;
442 case SHARE_CURRENT_MODE
:
443 handle_to_dup
= mapped_file_
;
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_
;
453 const int new_fd
= dup(handle_to_dup
);
455 DPLOG(ERROR
) << "dup() failed.";
459 new_handle
->fd
= new_fd
;
460 new_handle
->auto_close
= true;