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 // Q: Why not use the shm_open() etc. APIs?
57 // A: Because they're limited to 4mb on OS X. FFFFFFFUUUUUUUUUUU
59 ScopedPathUnlinker path_unlinker
;
60 if (GetShmemTempDir(options
.executable
, &directory
)) {
61 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466437
63 tracked_objects::ScopedTracker
tracking_profile(
64 FROM_HERE_WITH_EXPLICIT_FUNCTION(
65 "466437 SharedMemory::Create::OpenTemporaryFile"));
66 fp
->reset(CreateAndOpenTemporaryFileInDir(directory
, path
));
68 // Deleting the file prevents anyone else from mapping it in (making it
69 // private), and prevents the need for cleanup (once the last fd is
70 // closed, it is truly freed).
72 path_unlinker
.reset(path
);
76 if (options
.share_read_only
) {
77 // TODO(erikchen): Remove ScopedTracker below once
78 // http://crbug.com/466437 is fixed.
79 tracked_objects::ScopedTracker
tracking_profile(
80 FROM_HERE_WITH_EXPLICIT_FUNCTION(
81 "466437 SharedMemory::Create::OpenReadonly"));
82 // Also open as readonly so that we can ShareReadOnlyToProcess.
83 readonly_fd
->reset(HANDLE_EINTR(open(path
->value().c_str(), O_RDONLY
)));
84 if (!readonly_fd
->is_valid()) {
85 DPLOG(ERROR
) << "open(\"" << path
->value() << "\", O_RDONLY) failed";
96 SharedMemory::SharedMemory()
98 readonly_mapped_file_(-1),
105 SharedMemory::SharedMemory(const SharedMemoryHandle
& handle
, bool read_only
)
106 : mapped_file_(GetFdFromSharedMemoryHandle(handle
)),
107 readonly_mapped_file_(-1),
110 read_only_(read_only
),
114 SharedMemory::SharedMemory(const SharedMemoryHandle
& handle
,
116 ProcessHandle process
)
117 : mapped_file_(GetFdFromSharedMemoryHandle(handle
)),
118 readonly_mapped_file_(-1),
121 read_only_(read_only
),
123 // We don't handle this case yet (note the ignored parameter); let's die if
124 // someone comes calling.
128 SharedMemory::~SharedMemory() {
134 bool SharedMemory::IsHandleValid(const SharedMemoryHandle
& handle
) {
135 return handle
.IsValid();
139 SharedMemoryHandle
SharedMemory::NULLHandle() {
140 return SharedMemoryHandle();
144 void SharedMemory::CloseHandle(const SharedMemoryHandle
& handle
) {
145 DCHECK_GE(GetFdFromSharedMemoryHandle(handle
), 0);
146 if (close(GetFdFromSharedMemoryHandle(handle
)) < 0)
147 DPLOG(ERROR
) << "close";
151 size_t SharedMemory::GetHandleLimit() {
156 SharedMemoryHandle
SharedMemory::DuplicateHandle(
157 const SharedMemoryHandle
& handle
) {
158 return handle
.Duplicate();
162 int SharedMemory::GetFdFromSharedMemoryHandle(
163 const SharedMemoryHandle
& handle
) {
164 return handle
.GetFileDescriptor().fd
;
167 bool SharedMemory::CreateAndMapAnonymous(size_t size
) {
168 return CreateAnonymous(size
) && Map(size
);
172 int SharedMemory::GetSizeFromSharedMemoryHandle(
173 const SharedMemoryHandle
& handle
) {
175 if (fstat(GetFdFromSharedMemoryHandle(handle
), &st
) != 0)
180 // Chromium mostly only uses the unique/private shmem as specified by
181 // "name == L"". The exception is in the StatsTable.
182 // TODO(jrg): there is no way to "clean up" all unused named shmem if
183 // we restart from a crash. (That isn't a new problem, but it is a problem.)
184 // In case we want to delete it later, it may be useful to save the value
185 // of mem_filename after FilePathForMemoryName().
186 bool SharedMemory::Create(const SharedMemoryCreateOptions
& options
) {
187 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466437
189 tracked_objects::ScopedTracker
tracking_profile1(
190 FROM_HERE_WITH_EXPLICIT_FUNCTION(
191 "466437 SharedMemory::Create::Start"));
192 DCHECK_EQ(-1, mapped_file_
);
193 if (options
.size
== 0) return false;
195 if (options
.size
> static_cast<size_t>(std::numeric_limits
<int>::max()))
198 // This function theoretically can block on the disk, but realistically
199 // the temporary files we create will just go into the buffer cache
200 // and be deleted before they ever make it out to disk.
201 base::ThreadRestrictions::ScopedAllowIO allow_io
;
204 ScopedFD readonly_fd
;
207 bool result
= CreateAnonymousSharedMemory(options
, &fp
, &readonly_fd
, &path
);
212 PLOG(ERROR
) << "Creating shared memory in " << path
.value() << " failed";
218 if (fstat(fileno(fp
.get()), &stat
) != 0)
220 const size_t current_size
= stat
.st_size
;
221 if (current_size
!= options
.size
) {
222 if (HANDLE_EINTR(ftruncate(fileno(fp
.get()), options
.size
)) != 0)
225 requested_size_
= options
.size
;
227 return PrepareMapFile(fp
.Pass(), readonly_fd
.Pass());
230 bool SharedMemory::MapAt(off_t offset
, size_t bytes
) {
231 if (mapped_file_
== -1)
234 if (bytes
> static_cast<size_t>(std::numeric_limits
<int>::max()))
240 memory_
= mmap(NULL
, bytes
, PROT_READ
| (read_only_
? 0 : PROT_WRITE
),
241 MAP_SHARED
, mapped_file_
, offset
);
243 bool mmap_succeeded
= memory_
&& memory_
!= reinterpret_cast<void*>(-1);
244 if (mmap_succeeded
) {
245 mapped_size_
= bytes
;
246 DCHECK_EQ(0U, reinterpret_cast<uintptr_t>(memory_
) &
247 (SharedMemory::MAP_MINIMUM_ALIGNMENT
- 1));
252 return mmap_succeeded
;
255 bool SharedMemory::Unmap() {
259 munmap(memory_
, mapped_size_
);
265 SharedMemoryHandle
SharedMemory::handle() const {
266 return SharedMemoryHandle(mapped_file_
, false);
269 void SharedMemory::Close() {
270 if (mapped_file_
> 0) {
271 if (close(mapped_file_
) < 0)
272 PLOG(ERROR
) << "close";
275 if (readonly_mapped_file_
> 0) {
276 if (close(readonly_mapped_file_
) < 0)
277 PLOG(ERROR
) << "close";
278 readonly_mapped_file_
= -1;
282 bool SharedMemory::PrepareMapFile(ScopedFILE fp
, ScopedFD readonly_fd
) {
283 DCHECK_EQ(-1, mapped_file_
);
284 DCHECK_EQ(-1, readonly_mapped_file_
);
288 // This function theoretically can block on the disk, but realistically
289 // the temporary files we create will just go into the buffer cache
290 // and be deleted before they ever make it out to disk.
291 base::ThreadRestrictions::ScopedAllowIO allow_io
;
294 if (fstat(fileno(fp
.get()), &st
))
296 if (readonly_fd
.is_valid()) {
297 struct stat readonly_st
= {};
298 if (fstat(readonly_fd
.get(), &readonly_st
))
300 if (st
.st_dev
!= readonly_st
.st_dev
|| st
.st_ino
!= readonly_st
.st_ino
) {
301 LOG(ERROR
) << "writable and read-only inodes don't match; bailing";
306 mapped_file_
= HANDLE_EINTR(dup(fileno(fp
.get())));
307 if (mapped_file_
== -1) {
308 if (errno
== EMFILE
) {
309 LOG(WARNING
) << "Shared memory creation failed; out of file descriptors";
312 NOTREACHED() << "Call to dup failed, errno=" << errno
;
315 readonly_mapped_file_
= readonly_fd
.release();
320 // For the given shmem named |mem_name|, return a filename to mmap()
321 // (and possibly create). Modifies |filename|. Return false on
322 // error, or true of we are happy.
323 bool SharedMemory::FilePathForMemoryName(const std::string
& mem_name
,
325 // mem_name will be used for a filename; make sure it doesn't
326 // contain anything which will confuse us.
327 DCHECK_EQ(std::string::npos
, mem_name
.find('/'));
328 DCHECK_EQ(std::string::npos
, mem_name
.find('\0'));
331 if (!GetShmemTempDir(false, &temp_dir
))
334 std::string name_base
= std::string(mac::BaseBundleID());
335 *path
= temp_dir
.AppendASCII(name_base
+ ".shmem." + mem_name
);
339 bool SharedMemory::ShareToProcessCommon(ProcessHandle process
,
340 SharedMemoryHandle
* new_handle
,
342 ShareMode share_mode
) {
343 int handle_to_dup
= -1;
344 switch (share_mode
) {
345 case SHARE_CURRENT_MODE
:
346 handle_to_dup
= mapped_file_
;
349 // We could imagine re-opening the file from /dev/fd, but that can't make
350 // it readonly on Mac: https://codereview.chromium.org/27265002/#msg10
351 CHECK_GE(readonly_mapped_file_
, 0);
352 handle_to_dup
= readonly_mapped_file_
;
356 const int new_fd
= HANDLE_EINTR(dup(handle_to_dup
));
358 DPLOG(ERROR
) << "dup() failed.";
362 new_handle
->SetFileHandle(new_fd
, true);