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