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"
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"
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
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
,
56 ScopedFD
* readonly_fd
,
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
63 ScopedPathUnlinker path_unlinker
;
64 if (GetShmemTempDir(options
.executable
, &directory
)) {
65 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466437
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).
76 path_unlinker
.reset(path
);
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";
97 #endif // !defined(OS_ANDROID)
100 SharedMemory::SharedMemory()
102 readonly_mapped_file_(-1),
109 SharedMemory::SharedMemory(const SharedMemoryHandle
& handle
, bool read_only
)
110 : mapped_file_(handle
.fd
),
111 readonly_mapped_file_(-1),
114 read_only_(read_only
),
118 SharedMemory::SharedMemory(const SharedMemoryHandle
& handle
,
120 ProcessHandle process
)
121 : mapped_file_(handle
.fd
),
122 readonly_mapped_file_(-1),
125 read_only_(read_only
),
127 // We don't handle this case yet (note the ignored parameter); let's die if
128 // someone comes calling.
132 SharedMemory::~SharedMemory() {
138 bool SharedMemory::IsHandleValid(const SharedMemoryHandle
& handle
) {
139 return handle
.fd
>= 0;
143 SharedMemoryHandle
SharedMemory::NULLHandle() {
144 return SharedMemoryHandle();
148 void SharedMemory::CloseHandle(const SharedMemoryHandle
& handle
) {
149 DCHECK_GE(handle
.fd
, 0);
150 if (close(handle
.fd
) < 0)
151 DPLOG(ERROR
) << "close";
155 size_t SharedMemory::GetHandleLimit() {
156 return base::GetMaxFds();
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);
169 int SharedMemory::GetFdFromSharedMemoryHandle(
170 const SharedMemoryHandle
& handle
) {
174 bool SharedMemory::CreateAndMapAnonymous(size_t size
) {
175 return CreateAnonymous(size
) && Map(size
);
178 #if !defined(OS_ANDROID)
180 int SharedMemory::GetSizeFromSharedMemoryHandle(
181 const SharedMemoryHandle
& handle
) {
183 if (fstat(handle
.fd
, &st
) != 0)
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
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()))
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
;
212 bool fix_size
= true;
213 ScopedFD readonly_fd
;
216 if (options
.name_deprecated
== NULL
|| options
.name_deprecated
->empty()) {
218 CreateAnonymousSharedMemory(options
, &fp
, &readonly_fd
, &path
);
222 if (!FilePathForMemoryName(*options
.name_deprecated
, &path
))
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().
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();
250 (fstat(fd
, &sb
) != 0 || sb
.st_uid
!= real_uid
||
251 sb
.st_uid
!= effective_uid
)) {
253 "Invalid owner when opening existing shared memory file.";
258 // An existing file was opened, so its size should not be fixed.
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";
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
) {
280 if (fstat(fileno(fp
.get()), &stat
) != 0)
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)
287 requested_size_
= options
.size
;
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.";
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
) {
310 if (!FilePathForMemoryName(name
, &path
))
313 if (PathExists(path
))
314 return base::DeleteFile(path
, false);
316 // Doesn't exist, so success.
320 bool SharedMemory::Open(const std::string
& name
, bool read_only
) {
322 if (!FilePathForMemoryName(name
, &path
))
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";
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)
342 if (bytes
> static_cast<size_t>(std::numeric_limits
<int>::max()))
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.
352 DCHECK_EQ(0, offset
);
353 int ashmem_bytes
= ashmem_get_size_region(mapped_file_
);
354 if (ashmem_bytes
< 0)
356 bytes
= ashmem_bytes
;
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));
372 return mmap_succeeded
;
375 bool SharedMemory::Unmap() {
379 munmap(memory_
, mapped_size_
);
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";
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_
);
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
;
415 if (fstat(fileno(fp
.get()), &st
))
417 if (readonly_fd
.is_valid()) {
418 struct stat readonly_st
= {};
419 if (fstat(readonly_fd
.get(), &readonly_st
))
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";
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";
433 NOTREACHED() << "Call to dup failed, errno=" << errno
;
436 readonly_mapped_file_
= readonly_fd
.release();
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
,
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'));
452 if (!GetShmemTempDir(false, &temp_dir
))
455 #if defined(GOOGLE_CHROME_BUILD)
456 std::string name_base
= std::string("com.google.Chrome");
458 std::string name_base
= std::string("org.chromium.Chromium");
460 *path
= temp_dir
.AppendASCII(name_base
+ ".shmem." + mem_name
);
463 #endif // !defined(OS_ANDROID)
465 bool SharedMemory::ShareToProcessCommon(ProcessHandle process
,
466 SharedMemoryHandle
* new_handle
,
468 ShareMode share_mode
) {
469 int handle_to_dup
= -1;
471 case SHARE_CURRENT_MODE
:
472 handle_to_dup
= mapped_file_
;
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_
;
482 const int new_fd
= HANDLE_EINTR(dup(handle_to_dup
));
484 DPLOG(ERROR
) << "dup() failed.";
488 new_handle
->fd
= new_fd
;
489 new_handle
->auto_close
= true;