Cleanup setting of 'sysroot' in common.gypi
[chromium-blink-merge.git] / base / memory / shared_memory_mac.cc
blobab53f015cd1c142eb5cdf51ee4358c9a9bd869f3
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"
7 #include <fcntl.h>
8 #include <sys/mman.h>
9 #include <sys/stat.h>
10 #include <unistd.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"
24 #endif // OS_MACOSX
26 namespace base {
28 namespace {
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
35 // is fixed.
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,
53 ScopedFILE* fp,
54 ScopedFD* readonly_fd,
55 FilePath* path) {
56 // Q: Why not use the shm_open() etc. APIs?
57 // A: Because they're limited to 4mb on OS X. FFFFFFFUUUUUUUUUUU
58 FilePath directory;
59 ScopedPathUnlinker path_unlinker;
60 if (GetShmemTempDir(options.executable, &directory)) {
61 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466437
62 // is fixed.
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).
71 if (*fp)
72 path_unlinker.reset(path);
75 if (*fp) {
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";
86 fp->reset();
87 return false;
91 return true;
94 } // namespace
96 SharedMemory::SharedMemory()
97 : mapped_file_(-1),
98 readonly_mapped_file_(-1),
99 mapped_size_(0),
100 memory_(NULL),
101 read_only_(false),
102 requested_size_(0) {
105 SharedMemory::SharedMemory(const SharedMemoryHandle& handle, bool read_only)
106 : mapped_file_(GetFdFromSharedMemoryHandle(handle)),
107 readonly_mapped_file_(-1),
108 mapped_size_(0),
109 memory_(NULL),
110 read_only_(read_only),
111 requested_size_(0) {
114 SharedMemory::SharedMemory(const SharedMemoryHandle& handle,
115 bool read_only,
116 ProcessHandle process)
117 : mapped_file_(GetFdFromSharedMemoryHandle(handle)),
118 readonly_mapped_file_(-1),
119 mapped_size_(0),
120 memory_(NULL),
121 read_only_(read_only),
122 requested_size_(0) {
123 // We don't handle this case yet (note the ignored parameter); let's die if
124 // someone comes calling.
125 NOTREACHED();
128 SharedMemory::~SharedMemory() {
129 Unmap();
130 Close();
133 // static
134 bool SharedMemory::IsHandleValid(const SharedMemoryHandle& handle) {
135 return handle.IsValid();
138 // static
139 SharedMemoryHandle SharedMemory::NULLHandle() {
140 return SharedMemoryHandle();
143 // static
144 void SharedMemory::CloseHandle(const SharedMemoryHandle& handle) {
145 DCHECK_GE(GetFdFromSharedMemoryHandle(handle), 0);
146 if (close(GetFdFromSharedMemoryHandle(handle)) < 0)
147 DPLOG(ERROR) << "close";
150 // static
151 size_t SharedMemory::GetHandleLimit() {
152 return GetMaxFds();
155 // static
156 SharedMemoryHandle SharedMemory::DuplicateHandle(
157 const SharedMemoryHandle& handle) {
158 return handle.Duplicate();
161 // static
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);
171 // static
172 int SharedMemory::GetSizeFromSharedMemoryHandle(
173 const SharedMemoryHandle& handle) {
174 struct stat st;
175 if (fstat(GetFdFromSharedMemoryHandle(handle), &st) != 0)
176 return -1;
177 return st.st_size;
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
188 // is fixed.
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()))
196 return false;
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;
203 ScopedFILE fp;
204 ScopedFD readonly_fd;
206 FilePath path;
207 bool result = CreateAnonymousSharedMemory(options, &fp, &readonly_fd, &path);
208 if (!result)
209 return false;
211 if (!fp) {
212 PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed";
213 return false;
216 // Get current size.
217 struct stat stat;
218 if (fstat(fileno(fp.get()), &stat) != 0)
219 return false;
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)
223 return false;
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)
232 return false;
234 if (bytes > static_cast<size_t>(std::numeric_limits<int>::max()))
235 return false;
237 if (memory_)
238 return false;
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));
248 } else {
249 memory_ = NULL;
252 return mmap_succeeded;
255 bool SharedMemory::Unmap() {
256 if (memory_ == NULL)
257 return false;
259 munmap(memory_, mapped_size_);
260 memory_ = NULL;
261 mapped_size_ = 0;
262 return true;
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";
273 mapped_file_ = -1;
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_);
285 if (fp == NULL)
286 return false;
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;
293 struct stat st = {};
294 if (fstat(fileno(fp.get()), &st))
295 NOTREACHED();
296 if (readonly_fd.is_valid()) {
297 struct stat readonly_st = {};
298 if (fstat(readonly_fd.get(), &readonly_st))
299 NOTREACHED();
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";
302 return false;
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";
310 return false;
311 } else {
312 NOTREACHED() << "Call to dup failed, errno=" << errno;
315 readonly_mapped_file_ = readonly_fd.release();
317 return true;
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,
324 FilePath* path) {
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'));
330 FilePath temp_dir;
331 if (!GetShmemTempDir(false, &temp_dir))
332 return false;
334 std::string name_base = std::string(mac::BaseBundleID());
335 *path = temp_dir.AppendASCII(name_base + ".shmem." + mem_name);
336 return true;
339 bool SharedMemory::ShareToProcessCommon(ProcessHandle process,
340 SharedMemoryHandle* new_handle,
341 bool close_self,
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_;
347 break;
348 case SHARE_READONLY:
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_;
353 break;
356 const int new_fd = HANDLE_EINTR(dup(handle_to_dup));
357 if (new_fd < 0) {
358 DPLOG(ERROR) << "dup() failed.";
359 return false;
362 new_handle->SetFileHandle(new_fd, true);
364 if (close_self) {
365 Unmap();
366 Close();
369 return true;
372 } // namespace base