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_MACOSX)
23 #include "base/mac/foundation_util.h"
30 struct ScopedPathUnlinkerTraits
{
31 static FilePath
* InvalidValue() { return nullptr; }
33 static void Free(FilePath
* path
) {
34 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466437
36 tracked_objects::ScopedTracker
tracking_profile(
37 FROM_HERE_WITH_EXPLICIT_FUNCTION(
38 "466437 SharedMemory::Create::Unlink"));
39 if (unlink(path
->value().c_str()))
40 PLOG(WARNING
) << "unlink";
44 // Unlinks the FilePath when the object is destroyed.
45 typedef ScopedGeneric
<FilePath
*, ScopedPathUnlinkerTraits
> ScopedPathUnlinker
;
47 // Makes a temporary file, fdopens it, and then unlinks it. |fp| is populated
48 // with the fdopened FILE. |readonly_fd| is populated with the opened fd if
49 // options.share_read_only is true. |path| is populated with the location of
50 // the file before it was unlinked.
51 // Returns false if there's an unhandled failure.
52 bool CreateAnonymousSharedMemory(const SharedMemoryCreateOptions
& options
,
54 ScopedFD
* readonly_fd
,
56 // It doesn't make sense to have a open-existing private piece of shmem
57 DCHECK(!options
.open_existing_deprecated
);
58 // Q: Why not use the shm_open() etc. APIs?
59 // A: Because they're limited to 4mb on OS X. FFFFFFFUUUUUUUUUUU
61 ScopedPathUnlinker path_unlinker
;
62 if (GetShmemTempDir(options
.executable
, &directory
)) {
63 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466437
65 tracked_objects::ScopedTracker
tracking_profile(
66 FROM_HERE_WITH_EXPLICIT_FUNCTION(
67 "466437 SharedMemory::Create::OpenTemporaryFile"));
68 fp
->reset(base::CreateAndOpenTemporaryFileInDir(directory
, path
));
70 // Deleting the file prevents anyone else from mapping it in (making it
71 // private), and prevents the need for cleanup (once the last fd is
72 // closed, it is truly freed).
74 path_unlinker
.reset(path
);
78 if (options
.share_read_only
) {
79 // TODO(erikchen): Remove ScopedTracker below once
80 // http://crbug.com/466437 is fixed.
81 tracked_objects::ScopedTracker
tracking_profile(
82 FROM_HERE_WITH_EXPLICIT_FUNCTION(
83 "466437 SharedMemory::Create::OpenReadonly"));
84 // Also open as readonly so that we can ShareReadOnlyToProcess.
85 readonly_fd
->reset(HANDLE_EINTR(open(path
->value().c_str(), O_RDONLY
)));
86 if (!readonly_fd
->is_valid()) {
87 DPLOG(ERROR
) << "open(\"" << path
->value() << "\", O_RDONLY) failed";
97 SharedMemory::SharedMemory()
99 readonly_mapped_file_(-1),
106 SharedMemory::SharedMemory(const SharedMemoryHandle
& handle
, bool read_only
)
107 : mapped_file_(GetFdFromSharedMemoryHandle(handle
)),
108 readonly_mapped_file_(-1),
111 read_only_(read_only
),
115 SharedMemory::SharedMemory(const SharedMemoryHandle
& handle
,
117 ProcessHandle process
)
118 : mapped_file_(GetFdFromSharedMemoryHandle(handle
)),
119 readonly_mapped_file_(-1),
122 read_only_(read_only
),
124 // We don't handle this case yet (note the ignored parameter); let's die if
125 // someone comes calling.
129 SharedMemory::~SharedMemory() {
135 bool SharedMemory::IsHandleValid(const SharedMemoryHandle
& handle
) {
136 return handle
.IsValid();
140 SharedMemoryHandle
SharedMemory::NULLHandle() {
141 return SharedMemoryHandle();
145 void SharedMemory::CloseHandle(const SharedMemoryHandle
& handle
) {
146 DCHECK_GE(GetFdFromSharedMemoryHandle(handle
), 0);
147 if (close(GetFdFromSharedMemoryHandle(handle
)) < 0)
148 DPLOG(ERROR
) << "close";
152 size_t SharedMemory::GetHandleLimit() {
153 return base::GetMaxFds();
157 SharedMemoryHandle
SharedMemory::DuplicateHandle(
158 const SharedMemoryHandle
& handle
) {
159 return handle
.Duplicate();
163 int SharedMemory::GetFdFromSharedMemoryHandle(
164 const SharedMemoryHandle
& handle
) {
165 return handle
.GetFileDescriptor().fd
;
168 bool SharedMemory::CreateAndMapAnonymous(size_t size
) {
169 return CreateAnonymous(size
) && Map(size
);
173 int SharedMemory::GetSizeFromSharedMemoryHandle(
174 const SharedMemoryHandle
& handle
) {
176 if (fstat(GetFdFromSharedMemoryHandle(handle
), &st
) != 0)
181 // Chromium mostly only uses the unique/private shmem as specified by
182 // "name == L"". The exception is in the StatsTable.
183 // TODO(jrg): there is no way to "clean up" all unused named shmem if
184 // we restart from a crash. (That isn't a new problem, but it is a problem.)
185 // In case we want to delete it later, it may be useful to save the value
186 // of mem_filename after FilePathForMemoryName().
187 bool SharedMemory::Create(const SharedMemoryCreateOptions
& options
) {
188 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466437
190 tracked_objects::ScopedTracker
tracking_profile1(
191 FROM_HERE_WITH_EXPLICIT_FUNCTION(
192 "466437 SharedMemory::Create::Start"));
193 DCHECK_EQ(-1, mapped_file_
);
194 if (options
.size
== 0) return false;
196 if (options
.size
> static_cast<size_t>(std::numeric_limits
<int>::max()))
199 // This function theoretically can block on the disk, but realistically
200 // the temporary files we create will just go into the buffer cache
201 // and be deleted before they ever make it out to disk.
202 base::ThreadRestrictions::ScopedAllowIO allow_io
;
205 bool fix_size
= true;
206 ScopedFD readonly_fd
;
209 if (options
.name_deprecated
== NULL
|| options
.name_deprecated
->empty()) {
211 CreateAnonymousSharedMemory(options
, &fp
, &readonly_fd
, &path
);
215 if (!FilePathForMemoryName(*options
.name_deprecated
, &path
))
218 // Make sure that the file is opened without any permission
219 // to other users on the system.
220 const mode_t kOwnerOnly
= S_IRUSR
| S_IWUSR
;
222 // First, try to create the file.
223 int fd
= HANDLE_EINTR(
224 open(path
.value().c_str(), O_RDWR
| O_CREAT
| O_EXCL
, kOwnerOnly
));
225 if (fd
== -1 && options
.open_existing_deprecated
) {
226 // If this doesn't work, try and open an existing file in append mode.
227 // Opening an existing file in a world writable directory has two main
228 // security implications:
229 // - Attackers could plant a file under their control, so ownership of
230 // the file is checked below.
231 // - Attackers could plant a symbolic link so that an unexpected file
232 // is opened, so O_NOFOLLOW is passed to open().
234 open(path
.value().c_str(), O_RDWR
| O_APPEND
| O_NOFOLLOW
));
236 // Check that the current user owns the file.
237 // If uid != euid, then a more complex permission model is used and this
238 // API is not appropriate.
239 const uid_t real_uid
= getuid();
240 const uid_t effective_uid
= geteuid();
243 (fstat(fd
, &sb
) != 0 || sb
.st_uid
!= real_uid
||
244 sb
.st_uid
!= effective_uid
)) {
246 "Invalid owner when opening existing shared memory file.";
251 // An existing file was opened, so its size should not be fixed.
255 if (options
.share_read_only
) {
256 // Also open as readonly so that we can ShareReadOnlyToProcess.
257 readonly_fd
.reset(HANDLE_EINTR(open(path
.value().c_str(), O_RDONLY
)));
258 if (!readonly_fd
.is_valid()) {
259 DPLOG(ERROR
) << "open(\"" << path
.value() << "\", O_RDONLY) failed";
266 // "a+" is always appropriate: if it's a new file, a+ is similar to w+.
267 fp
.reset(fdopen(fd
, "a+"));
270 if (fp
&& fix_size
) {
273 if (fstat(fileno(fp
.get()), &stat
) != 0)
275 const size_t current_size
= stat
.st_size
;
276 if (current_size
!= options
.size
) {
277 if (HANDLE_EINTR(ftruncate(fileno(fp
.get()), options
.size
)) != 0)
280 requested_size_
= options
.size
;
283 PLOG(ERROR
) << "Creating shared memory in " << path
.value() << " failed";
287 return PrepareMapFile(fp
.Pass(), readonly_fd
.Pass());
290 // Our current implementation of shmem is with mmap()ing of files.
291 // These files need to be deleted explicitly.
292 // In practice this call is only needed for unit tests.
293 bool SharedMemory::Delete(const std::string
& name
) {
295 if (!FilePathForMemoryName(name
, &path
))
298 if (PathExists(path
))
299 return base::DeleteFile(path
, false);
301 // Doesn't exist, so success.
305 bool SharedMemory::Open(const std::string
& name
, bool read_only
) {
307 if (!FilePathForMemoryName(name
, &path
))
310 read_only_
= read_only
;
312 const char *mode
= read_only
? "r" : "r+";
313 ScopedFILE
fp(base::OpenFile(path
, mode
));
314 ScopedFD
readonly_fd(HANDLE_EINTR(open(path
.value().c_str(), O_RDONLY
)));
315 if (!readonly_fd
.is_valid()) {
316 DPLOG(ERROR
) << "open(\"" << path
.value() << "\", O_RDONLY) failed";
319 return PrepareMapFile(fp
.Pass(), readonly_fd
.Pass());
322 bool SharedMemory::MapAt(off_t offset
, size_t bytes
) {
323 if (mapped_file_
== -1)
326 if (bytes
> static_cast<size_t>(std::numeric_limits
<int>::max()))
332 memory_
= mmap(NULL
, bytes
, PROT_READ
| (read_only_
? 0 : PROT_WRITE
),
333 MAP_SHARED
, mapped_file_
, offset
);
335 bool mmap_succeeded
= memory_
!= (void*)-1 && memory_
!= NULL
;
336 if (mmap_succeeded
) {
337 mapped_size_
= bytes
;
338 DCHECK_EQ(0U, reinterpret_cast<uintptr_t>(memory_
) &
339 (SharedMemory::MAP_MINIMUM_ALIGNMENT
- 1));
344 return mmap_succeeded
;
347 bool SharedMemory::Unmap() {
351 munmap(memory_
, mapped_size_
);
357 SharedMemoryHandle
SharedMemory::handle() const {
358 return SharedMemoryHandle(mapped_file_
, false);
361 void SharedMemory::Close() {
362 if (mapped_file_
> 0) {
363 if (close(mapped_file_
) < 0)
364 PLOG(ERROR
) << "close";
367 if (readonly_mapped_file_
> 0) {
368 if (close(readonly_mapped_file_
) < 0)
369 PLOG(ERROR
) << "close";
370 readonly_mapped_file_
= -1;
374 bool SharedMemory::PrepareMapFile(ScopedFILE fp
, ScopedFD readonly_fd
) {
375 DCHECK_EQ(-1, mapped_file_
);
376 DCHECK_EQ(-1, readonly_mapped_file_
);
380 // This function theoretically can block on the disk, but realistically
381 // the temporary files we create will just go into the buffer cache
382 // and be deleted before they ever make it out to disk.
383 base::ThreadRestrictions::ScopedAllowIO allow_io
;
386 if (fstat(fileno(fp
.get()), &st
))
388 if (readonly_fd
.is_valid()) {
389 struct stat readonly_st
= {};
390 if (fstat(readonly_fd
.get(), &readonly_st
))
392 if (st
.st_dev
!= readonly_st
.st_dev
|| st
.st_ino
!= readonly_st
.st_ino
) {
393 LOG(ERROR
) << "writable and read-only inodes don't match; bailing";
398 mapped_file_
= HANDLE_EINTR(dup(fileno(fp
.get())));
399 if (mapped_file_
== -1) {
400 if (errno
== EMFILE
) {
401 LOG(WARNING
) << "Shared memory creation failed; out of file descriptors";
404 NOTREACHED() << "Call to dup failed, errno=" << errno
;
407 readonly_mapped_file_
= readonly_fd
.release();
412 // For the given shmem named |mem_name|, return a filename to mmap()
413 // (and possibly create). Modifies |filename|. Return false on
414 // error, or true of we are happy.
415 bool SharedMemory::FilePathForMemoryName(const std::string
& mem_name
,
417 // mem_name will be used for a filename; make sure it doesn't
418 // contain anything which will confuse us.
419 DCHECK_EQ(std::string::npos
, mem_name
.find('/'));
420 DCHECK_EQ(std::string::npos
, mem_name
.find('\0'));
423 if (!GetShmemTempDir(false, &temp_dir
))
426 std::string name_base
= std::string(base::mac::BaseBundleID());
427 *path
= temp_dir
.AppendASCII(name_base
+ ".shmem." + mem_name
);
431 bool SharedMemory::ShareToProcessCommon(ProcessHandle process
,
432 SharedMemoryHandle
* new_handle
,
434 ShareMode share_mode
) {
435 int handle_to_dup
= -1;
437 case SHARE_CURRENT_MODE
:
438 handle_to_dup
= mapped_file_
;
441 // We could imagine re-opening the file from /dev/fd, but that can't make
442 // it readonly on Mac: https://codereview.chromium.org/27265002/#msg10
443 CHECK_GE(readonly_mapped_file_
, 0);
444 handle_to_dup
= readonly_mapped_file_
;
448 const int new_fd
= HANDLE_EINTR(dup(handle_to_dup
));
450 DPLOG(ERROR
) << "dup() failed.";
454 new_handle
->SetFileHandle(new_fd
, true);