OLD | NEW |
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. | 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 | 2 // Use of this source code is governed by a BSD-style license that can be |
3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
4 | 4 |
5 #include "base/memory/shared_memory.h" | 5 #include "base/memory/shared_memory.h" |
6 | 6 |
7 #include <errno.h> | |
8 #include <fcntl.h> | |
9 #include <mach/mach_vm.h> | 7 #include <mach/mach_vm.h> |
10 #include <stddef.h> | |
11 #include <sys/mman.h> | |
12 #include <sys/stat.h> | |
13 #include <unistd.h> | |
14 | 8 |
15 #include "base/files/file_util.h" | 9 #include "base/files/file_util.h" |
16 #include "base/files/scoped_file.h" | 10 #include "base/files/scoped_file.h" |
17 #include "base/logging.h" | 11 #include "base/logging.h" |
| 12 #include "base/mac/foundation_util.h" |
18 #include "base/mac/mac_util.h" | 13 #include "base/mac/mac_util.h" |
19 #include "base/mac/scoped_mach_vm.h" | 14 #include "base/mac/scoped_mach_vm.h" |
20 #include "base/metrics/field_trial.h" | 15 #include "base/metrics/field_trial.h" |
21 #include "base/metrics/histogram_macros.h" | 16 #include "base/metrics/histogram_macros.h" |
22 #include "base/posix/eintr_wrapper.h" | |
23 #include "base/posix/safe_strerror.h" | |
24 #include "base/process/process_metrics.h" | 17 #include "base/process/process_metrics.h" |
25 #include "base/profiler/scoped_tracker.h" | 18 #include "base/profiler/scoped_tracker.h" |
26 #include "base/scoped_generic.h" | 19 #include "base/scoped_generic.h" |
27 #include "base/strings/utf_string_conversions.h" | 20 #include "base/strings/utf_string_conversions.h" |
28 #include "build/build_config.h" | 21 #include "build/build_config.h" |
29 | 22 |
30 #if defined(OS_MACOSX) | |
31 #include "base/mac/foundation_util.h" | |
32 #endif // OS_MACOSX | |
33 | |
34 namespace base { | 23 namespace base { |
35 | 24 |
36 namespace { | 25 namespace { |
37 | 26 |
38 // Returns whether the operation succeeded. | 27 // Returns whether the operation succeeded. |
39 // |new_handle| is an output variable, populated on success. The caller takes | 28 // |new_handle| is an output variable, populated on success. The caller takes |
40 // ownership of the underlying memory object. | 29 // ownership of the underlying memory object. |
41 // |handle| is the handle to copy. | 30 // |handle| is the handle to copy. |
42 // If |handle| is already mapped, |mapped_addr| is its mapped location. | 31 // If |handle| is already mapped, |mapped_addr| is its mapped location. |
43 // Otherwise, |mapped_addr| should be |nullptr|. | 32 // Otherwise, |mapped_addr| should be |nullptr|. |
(...skipping 27 matching lines...) Expand all Loading... |
71 mach_task_self(), reinterpret_cast<memory_object_size_t*>(&size), | 60 mach_task_self(), reinterpret_cast<memory_object_size_t*>(&size), |
72 reinterpret_cast<memory_object_offset_t>(temp_addr), VM_PROT_READ, | 61 reinterpret_cast<memory_object_offset_t>(temp_addr), VM_PROT_READ, |
73 &named_right, MACH_PORT_NULL); | 62 &named_right, MACH_PORT_NULL); |
74 if (kr != KERN_SUCCESS) | 63 if (kr != KERN_SUCCESS) |
75 return false; | 64 return false; |
76 | 65 |
77 *new_handle = SharedMemoryHandle(named_right, size, base::GetCurrentProcId()); | 66 *new_handle = SharedMemoryHandle(named_right, size, base::GetCurrentProcId()); |
78 return true; | 67 return true; |
79 } | 68 } |
80 | 69 |
81 struct ScopedPathUnlinkerTraits { | |
82 static FilePath* InvalidValue() { return nullptr; } | |
83 | |
84 static void Free(FilePath* path) { | |
85 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466437 | |
86 // is fixed. | |
87 tracked_objects::ScopedTracker tracking_profile( | |
88 FROM_HERE_WITH_EXPLICIT_FUNCTION( | |
89 "466437 SharedMemory::Create::Unlink")); | |
90 if (unlink(path->value().c_str())) | |
91 PLOG(WARNING) << "unlink"; | |
92 } | |
93 }; | |
94 | |
95 // Unlinks the FilePath when the object is destroyed. | |
96 typedef ScopedGeneric<FilePath*, ScopedPathUnlinkerTraits> ScopedPathUnlinker; | |
97 | |
98 // Makes a temporary file, fdopens it, and then unlinks it. |fp| is populated | |
99 // with the fdopened FILE. |readonly_fd| is populated with the opened fd if | |
100 // options.share_read_only is true. |path| is populated with the location of | |
101 // the file before it was unlinked. | |
102 // Returns false if there's an unhandled failure. | |
103 bool CreateAnonymousSharedMemory(const SharedMemoryCreateOptions& options, | |
104 ScopedFILE* fp, | |
105 ScopedFD* readonly_fd, | |
106 FilePath* path) { | |
107 // Q: Why not use the shm_open() etc. APIs? | |
108 // A: Because they're limited to 4mb on OS X. FFFFFFFUUUUUUUUUUU | |
109 FilePath directory; | |
110 ScopedPathUnlinker path_unlinker; | |
111 if (GetShmemTempDir(options.executable, &directory)) { | |
112 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466437 | |
113 // is fixed. | |
114 tracked_objects::ScopedTracker tracking_profile( | |
115 FROM_HERE_WITH_EXPLICIT_FUNCTION( | |
116 "466437 SharedMemory::Create::OpenTemporaryFile")); | |
117 fp->reset(CreateAndOpenTemporaryFileInDir(directory, path)); | |
118 | |
119 // Deleting the file prevents anyone else from mapping it in (making it | |
120 // private), and prevents the need for cleanup (once the last fd is | |
121 // closed, it is truly freed). | |
122 if (*fp) | |
123 path_unlinker.reset(path); | |
124 } | |
125 | |
126 if (*fp) { | |
127 if (options.share_read_only) { | |
128 // TODO(erikchen): Remove ScopedTracker below once | |
129 // http://crbug.com/466437 is fixed. | |
130 tracked_objects::ScopedTracker tracking_profile( | |
131 FROM_HERE_WITH_EXPLICIT_FUNCTION( | |
132 "466437 SharedMemory::Create::OpenReadonly")); | |
133 // Also open as readonly so that we can ShareReadOnlyToProcess. | |
134 readonly_fd->reset(HANDLE_EINTR(open(path->value().c_str(), O_RDONLY))); | |
135 if (!readonly_fd->is_valid()) { | |
136 DPLOG(ERROR) << "open(\"" << path->value() << "\", O_RDONLY) failed"; | |
137 fp->reset(); | |
138 return false; | |
139 } | |
140 } | |
141 } | |
142 return true; | |
143 } | |
144 | |
145 } // namespace | 70 } // namespace |
146 | 71 |
147 SharedMemoryCreateOptions::SharedMemoryCreateOptions() | 72 SharedMemoryCreateOptions::SharedMemoryCreateOptions() |
148 : type(SharedMemoryHandle::MACH), | 73 : size(0), |
149 size(0), | |
150 executable(false), | 74 executable(false), |
151 share_read_only(false) {} | 75 share_read_only(false) {} |
152 | 76 |
153 SharedMemory::SharedMemory() | 77 SharedMemory::SharedMemory() |
154 : mapped_memory_mechanism_(SharedMemoryHandle::POSIX), | 78 : readonly_mapped_file_(-1), |
155 readonly_mapped_file_(-1), | |
156 mapped_size_(0), | 79 mapped_size_(0), |
157 memory_(NULL), | 80 memory_(NULL), |
158 read_only_(false), | 81 read_only_(false), |
159 requested_size_(0) {} | 82 requested_size_(0) {} |
160 | 83 |
161 SharedMemory::SharedMemory(const SharedMemoryHandle& handle, bool read_only) | 84 SharedMemory::SharedMemory(const SharedMemoryHandle& handle, bool read_only) |
162 : shm_(handle), | 85 : shm_(handle), |
163 mapped_memory_mechanism_(SharedMemoryHandle::POSIX), | |
164 readonly_mapped_file_(-1), | 86 readonly_mapped_file_(-1), |
165 mapped_size_(0), | 87 mapped_size_(0), |
166 memory_(NULL), | 88 memory_(NULL), |
167 read_only_(read_only), | 89 read_only_(read_only), |
168 requested_size_(0) {} | 90 requested_size_(0) {} |
169 | 91 |
170 SharedMemory::~SharedMemory() { | 92 SharedMemory::~SharedMemory() { |
171 Unmap(); | 93 Unmap(); |
172 Close(); | 94 Close(); |
173 } | 95 } |
174 | 96 |
175 // static | 97 // static |
176 bool SharedMemory::IsHandleValid(const SharedMemoryHandle& handle) { | 98 bool SharedMemory::IsHandleValid(const SharedMemoryHandle& handle) { |
177 return handle.IsValid(); | 99 return handle.IsValid(); |
178 } | 100 } |
179 | 101 |
180 // static | 102 // static |
181 SharedMemoryHandle SharedMemory::NULLHandle() { | 103 SharedMemoryHandle SharedMemory::NULLHandle() { |
182 return SharedMemoryHandle(); | 104 return SharedMemoryHandle(); |
183 } | 105 } |
184 | 106 |
185 // static | 107 // static |
186 void SharedMemory::CloseHandle(const SharedMemoryHandle& handle) { | 108 void SharedMemory::CloseHandle(const SharedMemoryHandle& handle) { |
187 handle.Close(); | 109 handle.Close(); |
188 } | 110 } |
189 | 111 |
190 // static | 112 // static |
191 size_t SharedMemory::GetHandleLimit() { | 113 size_t SharedMemory::GetHandleLimit() { |
192 return GetMaxFds(); | 114 // This should be effectively unlimited on OS X. |
| 115 return 10000; |
193 } | 116 } |
194 | 117 |
195 // static | 118 // static |
196 SharedMemoryHandle SharedMemory::DuplicateHandle( | 119 SharedMemoryHandle SharedMemory::DuplicateHandle( |
197 const SharedMemoryHandle& handle) { | 120 const SharedMemoryHandle& handle) { |
198 return handle.Duplicate(); | 121 return handle.Duplicate(); |
199 } | 122 } |
200 | 123 |
201 // static | |
202 int SharedMemory::GetFdFromSharedMemoryHandle( | |
203 const SharedMemoryHandle& handle) { | |
204 return handle.GetFileDescriptor().fd; | |
205 } | |
206 | |
207 bool SharedMemory::CreateAndMapAnonymous(size_t size) { | 124 bool SharedMemory::CreateAndMapAnonymous(size_t size) { |
208 return CreateAnonymous(size) && Map(size); | 125 return CreateAnonymous(size) && Map(size); |
209 } | 126 } |
210 | 127 |
211 bool SharedMemory::CreateAndMapAnonymousPosix(size_t size) { | |
212 return CreateAnonymousPosix(size) && Map(size); | |
213 } | |
214 | |
215 bool SharedMemory::CreateAnonymousPosix(size_t size) { | |
216 SharedMemoryCreateOptions options; | |
217 options.type = SharedMemoryHandle::POSIX; | |
218 options.size = size; | |
219 return Create(options); | |
220 } | |
221 | |
222 // static | 128 // static |
223 bool SharedMemory::GetSizeFromSharedMemoryHandle( | 129 bool SharedMemory::GetSizeFromSharedMemoryHandle( |
224 const SharedMemoryHandle& handle, | 130 const SharedMemoryHandle& handle, |
225 size_t* size) { | 131 size_t* size) { |
226 return handle.GetSize(size); | 132 return handle.GetSize(size); |
227 } | 133 } |
228 | 134 |
229 // Chromium mostly only uses the unique/private shmem as specified by | 135 // Chromium mostly only uses the unique/private shmem as specified by |
230 // "name == L"". The exception is in the StatsTable. | 136 // "name == L"". The exception is in the StatsTable. |
231 bool SharedMemory::Create(const SharedMemoryCreateOptions& options) { | 137 bool SharedMemory::Create(const SharedMemoryCreateOptions& options) { |
232 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466437 | 138 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466437 |
233 // is fixed. | 139 // is fixed. |
234 tracked_objects::ScopedTracker tracking_profile1( | 140 tracked_objects::ScopedTracker tracking_profile1( |
235 FROM_HERE_WITH_EXPLICIT_FUNCTION( | 141 FROM_HERE_WITH_EXPLICIT_FUNCTION( |
236 "466437 SharedMemory::Create::Start")); | 142 "466437 SharedMemory::Create::Start")); |
237 DCHECK(!shm_.IsValid()); | 143 DCHECK(!shm_.IsValid()); |
238 if (options.size == 0) return false; | 144 if (options.size == 0) return false; |
239 | 145 |
240 if (options.size > static_cast<size_t>(std::numeric_limits<int>::max())) | 146 if (options.size > static_cast<size_t>(std::numeric_limits<int>::max())) |
241 return false; | 147 return false; |
242 | 148 |
243 if (options.type == SharedMemoryHandle::MACH) { | 149 shm_ = SharedMemoryHandle(options.size); |
244 shm_ = SharedMemoryHandle(options.size); | |
245 requested_size_ = options.size; | |
246 return shm_.IsValid(); | |
247 } | |
248 | |
249 // This function theoretically can block on the disk. Both profiling of real | |
250 // users and local instrumentation shows that this is a real problem. | |
251 // https://code.google.com/p/chromium/issues/detail?id=466437 | |
252 base::ThreadRestrictions::ScopedAllowIO allow_io; | |
253 | |
254 ScopedFILE fp; | |
255 ScopedFD readonly_fd; | |
256 | |
257 FilePath path; | |
258 bool result = CreateAnonymousSharedMemory(options, &fp, &readonly_fd, &path); | |
259 if (!result) | |
260 return false; | |
261 | |
262 if (!fp) { | |
263 PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed"; | |
264 return false; | |
265 } | |
266 | |
267 // Get current size. | |
268 struct stat stat; | |
269 if (fstat(fileno(fp.get()), &stat) != 0) | |
270 return false; | |
271 const size_t current_size = stat.st_size; | |
272 if (current_size != options.size) { | |
273 if (HANDLE_EINTR(ftruncate(fileno(fp.get()), options.size)) != 0) | |
274 return false; | |
275 } | |
276 requested_size_ = options.size; | 150 requested_size_ = options.size; |
277 | 151 return shm_.IsValid(); |
278 return PrepareMapFile(std::move(fp), std::move(readonly_fd)); | |
279 } | 152 } |
280 | 153 |
281 bool SharedMemory::MapAt(off_t offset, size_t bytes) { | 154 bool SharedMemory::MapAt(off_t offset, size_t bytes) { |
282 if (!shm_.IsValid()) | 155 if (!shm_.IsValid()) |
283 return false; | 156 return false; |
284 if (bytes > static_cast<size_t>(std::numeric_limits<int>::max())) | 157 if (bytes > static_cast<size_t>(std::numeric_limits<int>::max())) |
285 return false; | 158 return false; |
286 if (memory_) | 159 if (memory_) |
287 return false; | 160 return false; |
288 | 161 |
289 bool success = shm_.MapAt(offset, bytes, &memory_, read_only_); | 162 bool success = shm_.MapAt(offset, bytes, &memory_, read_only_); |
290 if (success) { | 163 if (success) { |
291 mapped_size_ = bytes; | 164 mapped_size_ = bytes; |
292 DCHECK_EQ(0U, reinterpret_cast<uintptr_t>(memory_) & | 165 DCHECK_EQ(0U, reinterpret_cast<uintptr_t>(memory_) & |
293 (SharedMemory::MAP_MINIMUM_ALIGNMENT - 1)); | 166 (SharedMemory::MAP_MINIMUM_ALIGNMENT - 1)); |
294 mapped_memory_mechanism_ = shm_.GetType(); | |
295 } else { | 167 } else { |
296 memory_ = NULL; | 168 memory_ = NULL; |
297 } | 169 } |
298 | 170 |
299 return success; | 171 return success; |
300 } | 172 } |
301 | 173 |
302 bool SharedMemory::Unmap() { | 174 bool SharedMemory::Unmap() { |
303 if (memory_ == NULL) | 175 if (memory_ == NULL) |
304 return false; | 176 return false; |
305 | 177 |
306 switch (mapped_memory_mechanism_) { | 178 mach_vm_deallocate(mach_task_self(), |
307 case SharedMemoryHandle::POSIX: | 179 reinterpret_cast<mach_vm_address_t>(memory_), |
308 munmap(memory_, mapped_size_); | 180 mapped_size_); |
309 break; | |
310 case SharedMemoryHandle::MACH: | |
311 mach_vm_deallocate(mach_task_self(), | |
312 reinterpret_cast<mach_vm_address_t>(memory_), | |
313 mapped_size_); | |
314 break; | |
315 } | |
316 | |
317 memory_ = NULL; | 181 memory_ = NULL; |
318 mapped_size_ = 0; | 182 mapped_size_ = 0; |
319 return true; | 183 return true; |
320 } | 184 } |
321 | 185 |
322 SharedMemoryHandle SharedMemory::handle() const { | 186 SharedMemoryHandle SharedMemory::handle() const { |
323 switch (shm_.GetType()) { | 187 return shm_; |
324 case SharedMemoryHandle::POSIX: | |
325 return SharedMemoryHandle(shm_.GetFileDescriptor().fd, false); | |
326 case SharedMemoryHandle::MACH: | |
327 return shm_; | |
328 } | |
329 } | 188 } |
330 | 189 |
331 void SharedMemory::Close() { | 190 void SharedMemory::Close() { |
332 shm_.Close(); | 191 shm_.Close(); |
333 shm_ = SharedMemoryHandle(); | 192 shm_ = SharedMemoryHandle(); |
334 if (shm_.GetType() == SharedMemoryHandle::POSIX) { | |
335 if (readonly_mapped_file_ > 0) { | |
336 if (IGNORE_EINTR(close(readonly_mapped_file_)) < 0) | |
337 PLOG(ERROR) << "close"; | |
338 readonly_mapped_file_ = -1; | |
339 } | |
340 } | |
341 } | |
342 | |
343 bool SharedMemory::PrepareMapFile(ScopedFILE fp, ScopedFD readonly_fd) { | |
344 DCHECK(!shm_.IsValid()); | |
345 DCHECK_EQ(-1, readonly_mapped_file_); | |
346 if (fp == NULL) | |
347 return false; | |
348 | |
349 // This function theoretically can block on the disk, but realistically | |
350 // the temporary files we create will just go into the buffer cache | |
351 // and be deleted before they ever make it out to disk. | |
352 base::ThreadRestrictions::ScopedAllowIO allow_io; | |
353 | |
354 struct stat st = {}; | |
355 if (fstat(fileno(fp.get()), &st)) | |
356 NOTREACHED(); | |
357 if (readonly_fd.is_valid()) { | |
358 struct stat readonly_st = {}; | |
359 if (fstat(readonly_fd.get(), &readonly_st)) | |
360 NOTREACHED(); | |
361 if (st.st_dev != readonly_st.st_dev || st.st_ino != readonly_st.st_ino) { | |
362 LOG(ERROR) << "writable and read-only inodes don't match; bailing"; | |
363 return false; | |
364 } | |
365 } | |
366 | |
367 int mapped_file = HANDLE_EINTR(dup(fileno(fp.get()))); | |
368 if (mapped_file == -1) { | |
369 if (errno == EMFILE) { | |
370 LOG(WARNING) << "Shared memory creation failed; out of file descriptors"; | |
371 return false; | |
372 } else { | |
373 NOTREACHED() << "Call to dup failed, errno=" << errno; | |
374 } | |
375 } | |
376 shm_ = SharedMemoryHandle(mapped_file, false); | |
377 readonly_mapped_file_ = readonly_fd.release(); | |
378 | |
379 return true; | |
380 } | 193 } |
381 | 194 |
382 bool SharedMemory::ShareToProcessCommon(ProcessHandle process, | 195 bool SharedMemory::ShareToProcessCommon(ProcessHandle process, |
383 SharedMemoryHandle* new_handle, | 196 SharedMemoryHandle* new_handle, |
384 bool close_self, | 197 bool close_self, |
385 ShareMode share_mode) { | 198 ShareMode share_mode) { |
386 if (shm_.GetType() == SharedMemoryHandle::MACH) { | 199 DCHECK(shm_.IsValid()); |
387 DCHECK(shm_.IsValid()); | |
388 | 200 |
389 bool success = false; | 201 bool success = false; |
390 switch (share_mode) { | |
391 case SHARE_CURRENT_MODE: | |
392 *new_handle = shm_.Duplicate(); | |
393 success = true; | |
394 break; | |
395 case SHARE_READONLY: | |
396 success = MakeMachSharedMemoryHandleReadOnly(new_handle, shm_, memory_); | |
397 break; | |
398 } | |
399 | |
400 if (success) | |
401 new_handle->SetOwnershipPassesToIPC(true); | |
402 | |
403 if (close_self) { | |
404 Unmap(); | |
405 Close(); | |
406 } | |
407 | |
408 return success; | |
409 } | |
410 | |
411 int handle_to_dup = -1; | |
412 switch (share_mode) { | 202 switch (share_mode) { |
413 case SHARE_CURRENT_MODE: | 203 case SHARE_CURRENT_MODE: |
414 handle_to_dup = shm_.GetFileDescriptor().fd; | 204 *new_handle = shm_.Duplicate(); |
| 205 success = true; |
415 break; | 206 break; |
416 case SHARE_READONLY: | 207 case SHARE_READONLY: |
417 // We could imagine re-opening the file from /dev/fd, but that can't make | 208 success = MakeMachSharedMemoryHandleReadOnly(new_handle, shm_, memory_); |
418 // it readonly on Mac: https://codereview.chromium.org/27265002/#msg10 | |
419 CHECK_GE(readonly_mapped_file_, 0); | |
420 handle_to_dup = readonly_mapped_file_; | |
421 break; | 209 break; |
422 } | 210 } |
423 | 211 |
424 const int new_fd = HANDLE_EINTR(dup(handle_to_dup)); | 212 if (success) |
425 if (new_fd < 0) { | 213 new_handle->SetOwnershipPassesToIPC(true); |
426 if (close_self) { | |
427 Unmap(); | |
428 Close(); | |
429 } | |
430 DPLOG(ERROR) << "dup() failed."; | |
431 return false; | |
432 } | |
433 | |
434 new_handle->SetFileHandle(new_fd, true); | |
435 | 214 |
436 if (close_self) { | 215 if (close_self) { |
437 Unmap(); | 216 Unmap(); |
438 Close(); | 217 Close(); |
439 } | 218 } |
440 | 219 |
441 return true; | 220 return success; |
442 } | 221 } |
443 | 222 |
444 } // namespace base | 223 } // namespace base |
OLD | NEW |