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" | |
13 #include "base/mac/mac_util.h" | 18 #include "base/mac/mac_util.h" |
14 #include "base/mac/scoped_mach_vm.h" | 19 #include "base/mac/scoped_mach_vm.h" |
15 #include "base/metrics/field_trial.h" | 20 #include "base/metrics/field_trial.h" |
16 #include "base/metrics/histogram_macros.h" | 21 #include "base/metrics/histogram_macros.h" |
| 22 #include "base/posix/eintr_wrapper.h" |
| 23 #include "base/posix/safe_strerror.h" |
17 #include "base/process/process_metrics.h" | 24 #include "base/process/process_metrics.h" |
18 #include "base/profiler/scoped_tracker.h" | 25 #include "base/profiler/scoped_tracker.h" |
19 #include "base/scoped_generic.h" | 26 #include "base/scoped_generic.h" |
20 #include "base/strings/utf_string_conversions.h" | 27 #include "base/strings/utf_string_conversions.h" |
21 #include "build/build_config.h" | 28 #include "build/build_config.h" |
22 | 29 |
| 30 #if defined(OS_MACOSX) |
| 31 #include "base/mac/foundation_util.h" |
| 32 #endif // OS_MACOSX |
| 33 |
23 namespace base { | 34 namespace base { |
24 | 35 |
25 namespace { | 36 namespace { |
26 | 37 |
27 // Returns whether the operation succeeded. | 38 // Returns whether the operation succeeded. |
28 // |new_handle| is an output variable, populated on success. The caller takes | 39 // |new_handle| is an output variable, populated on success. The caller takes |
29 // ownership of the underlying memory object. | 40 // ownership of the underlying memory object. |
30 // |handle| is the handle to copy. | 41 // |handle| is the handle to copy. |
31 // If |handle| is already mapped, |mapped_addr| is its mapped location. | 42 // If |handle| is already mapped, |mapped_addr| is its mapped location. |
32 // Otherwise, |mapped_addr| should be |nullptr|. | 43 // Otherwise, |mapped_addr| should be |nullptr|. |
(...skipping 27 matching lines...) Expand all Loading... |
60 mach_task_self(), reinterpret_cast<memory_object_size_t*>(&size), | 71 mach_task_self(), reinterpret_cast<memory_object_size_t*>(&size), |
61 reinterpret_cast<memory_object_offset_t>(temp_addr), VM_PROT_READ, | 72 reinterpret_cast<memory_object_offset_t>(temp_addr), VM_PROT_READ, |
62 &named_right, MACH_PORT_NULL); | 73 &named_right, MACH_PORT_NULL); |
63 if (kr != KERN_SUCCESS) | 74 if (kr != KERN_SUCCESS) |
64 return false; | 75 return false; |
65 | 76 |
66 *new_handle = SharedMemoryHandle(named_right, size, base::GetCurrentProcId()); | 77 *new_handle = SharedMemoryHandle(named_right, size, base::GetCurrentProcId()); |
67 return true; | 78 return true; |
68 } | 79 } |
69 | 80 |
| 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 |
70 } // namespace | 145 } // namespace |
71 | 146 |
72 SharedMemory::SharedMemory() | 147 SharedMemory::SharedMemory() |
73 : mapped_size_(0), memory_(NULL), read_only_(false), requested_size_(0) {} | 148 : mapped_memory_mechanism_(SharedMemoryHandle::MACH), |
| 149 readonly_mapped_file_(-1), |
| 150 mapped_size_(0), |
| 151 memory_(NULL), |
| 152 read_only_(false), |
| 153 requested_size_(0) {} |
74 | 154 |
75 SharedMemory::SharedMemory(const SharedMemoryHandle& handle, bool read_only) | 155 SharedMemory::SharedMemory(const SharedMemoryHandle& handle, bool read_only) |
76 : shm_(handle), | 156 : shm_(handle), |
| 157 mapped_memory_mechanism_(SharedMemoryHandle::POSIX), |
| 158 readonly_mapped_file_(-1), |
77 mapped_size_(0), | 159 mapped_size_(0), |
78 memory_(NULL), | 160 memory_(NULL), |
79 read_only_(read_only), | 161 read_only_(read_only), |
80 requested_size_(0) {} | 162 requested_size_(0) {} |
81 | 163 |
82 SharedMemory::~SharedMemory() { | 164 SharedMemory::~SharedMemory() { |
83 Unmap(); | 165 Unmap(); |
84 Close(); | 166 Close(); |
85 } | 167 } |
86 | 168 |
87 // static | 169 // static |
88 bool SharedMemory::IsHandleValid(const SharedMemoryHandle& handle) { | 170 bool SharedMemory::IsHandleValid(const SharedMemoryHandle& handle) { |
89 return handle.IsValid(); | 171 return handle.IsValid(); |
90 } | 172 } |
91 | 173 |
92 // static | 174 // static |
93 SharedMemoryHandle SharedMemory::NULLHandle() { | 175 SharedMemoryHandle SharedMemory::NULLHandle() { |
94 return SharedMemoryHandle(); | 176 return SharedMemoryHandle(); |
95 } | 177 } |
96 | 178 |
97 // static | 179 // static |
98 void SharedMemory::CloseHandle(const SharedMemoryHandle& handle) { | 180 void SharedMemory::CloseHandle(const SharedMemoryHandle& handle) { |
99 handle.Close(); | 181 handle.Close(); |
100 } | 182 } |
101 | 183 |
102 // static | 184 // static |
103 size_t SharedMemory::GetHandleLimit() { | 185 size_t SharedMemory::GetHandleLimit() { |
104 // This should be effectively unlimited on OS X. | 186 return GetMaxFds(); |
105 return 10000; | |
106 } | 187 } |
107 | 188 |
108 // static | 189 // static |
109 SharedMemoryHandle SharedMemory::DuplicateHandle( | 190 SharedMemoryHandle SharedMemory::DuplicateHandle( |
110 const SharedMemoryHandle& handle) { | 191 const SharedMemoryHandle& handle) { |
111 return handle.Duplicate(); | 192 return handle.Duplicate(); |
112 } | 193 } |
113 | 194 |
| 195 // static |
| 196 int SharedMemory::GetFdFromSharedMemoryHandle( |
| 197 const SharedMemoryHandle& handle) { |
| 198 return handle.GetFileDescriptor().fd; |
| 199 } |
| 200 |
114 bool SharedMemory::CreateAndMapAnonymous(size_t size) { | 201 bool SharedMemory::CreateAndMapAnonymous(size_t size) { |
115 return CreateAnonymous(size) && Map(size); | 202 return CreateAnonymous(size) && Map(size); |
116 } | 203 } |
117 | 204 |
| 205 bool SharedMemory::CreateAndMapAnonymousPosix(size_t size) { |
| 206 return CreateAnonymousPosix(size) && Map(size); |
| 207 } |
| 208 |
| 209 bool SharedMemory::CreateAnonymousPosix(size_t size) { |
| 210 SharedMemoryCreateOptions options; |
| 211 options.type = SharedMemoryHandle::POSIX; |
| 212 options.size = size; |
| 213 return Create(options); |
| 214 } |
| 215 |
118 // static | 216 // static |
119 bool SharedMemory::GetSizeFromSharedMemoryHandle( | 217 bool SharedMemory::GetSizeFromSharedMemoryHandle( |
120 const SharedMemoryHandle& handle, | 218 const SharedMemoryHandle& handle, |
121 size_t* size) { | 219 size_t* size) { |
122 return handle.GetSize(size); | 220 return handle.GetSize(size); |
123 } | 221 } |
124 | 222 |
125 // Chromium mostly only uses the unique/private shmem as specified by | 223 // Chromium mostly only uses the unique/private shmem as specified by |
126 // "name == L"". The exception is in the StatsTable. | 224 // "name == L"". The exception is in the StatsTable. |
127 bool SharedMemory::Create(const SharedMemoryCreateOptions& options) { | 225 bool SharedMemory::Create(const SharedMemoryCreateOptions& options) { |
128 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466437 | 226 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466437 |
129 // is fixed. | 227 // is fixed. |
130 tracked_objects::ScopedTracker tracking_profile1( | 228 tracked_objects::ScopedTracker tracking_profile1( |
131 FROM_HERE_WITH_EXPLICIT_FUNCTION( | 229 FROM_HERE_WITH_EXPLICIT_FUNCTION( |
132 "466437 SharedMemory::Create::Start")); | 230 "466437 SharedMemory::Create::Start")); |
133 DCHECK(!shm_.IsValid()); | 231 DCHECK(!shm_.IsValid()); |
134 if (options.size == 0) return false; | 232 if (options.size == 0) return false; |
135 | 233 |
136 if (options.size > static_cast<size_t>(std::numeric_limits<int>::max())) | 234 if (options.size > static_cast<size_t>(std::numeric_limits<int>::max())) |
137 return false; | 235 return false; |
138 | 236 |
139 shm_ = SharedMemoryHandle(options.size); | 237 if (options.type == SharedMemoryHandle::MACH) { |
| 238 shm_ = SharedMemoryHandle(options.size); |
| 239 requested_size_ = options.size; |
| 240 return shm_.IsValid(); |
| 241 } |
| 242 |
| 243 // This function theoretically can block on the disk. Both profiling of real |
| 244 // users and local instrumentation shows that this is a real problem. |
| 245 // https://code.google.com/p/chromium/issues/detail?id=466437 |
| 246 base::ThreadRestrictions::ScopedAllowIO allow_io; |
| 247 |
| 248 ScopedFILE fp; |
| 249 ScopedFD readonly_fd; |
| 250 |
| 251 FilePath path; |
| 252 bool result = CreateAnonymousSharedMemory(options, &fp, &readonly_fd, &path); |
| 253 if (!result) |
| 254 return false; |
| 255 |
| 256 if (!fp) { |
| 257 PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed"; |
| 258 return false; |
| 259 } |
| 260 |
| 261 // Get current size. |
| 262 struct stat stat; |
| 263 if (fstat(fileno(fp.get()), &stat) != 0) |
| 264 return false; |
| 265 const size_t current_size = stat.st_size; |
| 266 if (current_size != options.size) { |
| 267 if (HANDLE_EINTR(ftruncate(fileno(fp.get()), options.size)) != 0) |
| 268 return false; |
| 269 } |
140 requested_size_ = options.size; | 270 requested_size_ = options.size; |
141 return shm_.IsValid(); | 271 |
| 272 return PrepareMapFile(std::move(fp), std::move(readonly_fd)); |
142 } | 273 } |
143 | 274 |
144 bool SharedMemory::MapAt(off_t offset, size_t bytes) { | 275 bool SharedMemory::MapAt(off_t offset, size_t bytes) { |
145 if (!shm_.IsValid()) | 276 if (!shm_.IsValid()) |
146 return false; | 277 return false; |
147 if (bytes > static_cast<size_t>(std::numeric_limits<int>::max())) | 278 if (bytes > static_cast<size_t>(std::numeric_limits<int>::max())) |
148 return false; | 279 return false; |
149 if (memory_) | 280 if (memory_) |
150 return false; | 281 return false; |
151 | 282 |
152 bool success = shm_.MapAt(offset, bytes, &memory_, read_only_); | 283 bool success = shm_.MapAt(offset, bytes, &memory_, read_only_); |
153 if (success) { | 284 if (success) { |
154 mapped_size_ = bytes; | 285 mapped_size_ = bytes; |
155 DCHECK_EQ(0U, reinterpret_cast<uintptr_t>(memory_) & | 286 DCHECK_EQ(0U, reinterpret_cast<uintptr_t>(memory_) & |
156 (SharedMemory::MAP_MINIMUM_ALIGNMENT - 1)); | 287 (SharedMemory::MAP_MINIMUM_ALIGNMENT - 1)); |
| 288 mapped_memory_mechanism_ = shm_.GetType(); |
157 } else { | 289 } else { |
158 memory_ = NULL; | 290 memory_ = NULL; |
159 } | 291 } |
160 | 292 |
161 return success; | 293 return success; |
162 } | 294 } |
163 | 295 |
164 bool SharedMemory::Unmap() { | 296 bool SharedMemory::Unmap() { |
165 if (memory_ == NULL) | 297 if (memory_ == NULL) |
166 return false; | 298 return false; |
167 | 299 |
168 mach_vm_deallocate(mach_task_self(), | 300 switch (mapped_memory_mechanism_) { |
169 reinterpret_cast<mach_vm_address_t>(memory_), | 301 case SharedMemoryHandle::POSIX: |
170 mapped_size_); | 302 munmap(memory_, mapped_size_); |
| 303 break; |
| 304 case SharedMemoryHandle::MACH: |
| 305 mach_vm_deallocate(mach_task_self(), |
| 306 reinterpret_cast<mach_vm_address_t>(memory_), |
| 307 mapped_size_); |
| 308 break; |
| 309 } |
| 310 |
171 memory_ = NULL; | 311 memory_ = NULL; |
172 mapped_size_ = 0; | 312 mapped_size_ = 0; |
173 return true; | 313 return true; |
174 } | 314 } |
175 | 315 |
176 SharedMemoryHandle SharedMemory::handle() const { | 316 SharedMemoryHandle SharedMemory::handle() const { |
177 return shm_; | 317 switch (shm_.GetType()) { |
| 318 case SharedMemoryHandle::POSIX: |
| 319 return SharedMemoryHandle(shm_.GetFileDescriptor().fd, false); |
| 320 case SharedMemoryHandle::MACH: |
| 321 return shm_; |
| 322 } |
178 } | 323 } |
179 | 324 |
180 SharedMemoryHandle SharedMemory::TakeHandle() { | 325 SharedMemoryHandle SharedMemory::TakeHandle() { |
181 SharedMemoryHandle dup = DuplicateHandle(handle()); | 326 SharedMemoryHandle dup = DuplicateHandle(handle()); |
182 Close(); | 327 Close(); |
183 return dup; | 328 return dup; |
184 } | 329 } |
185 | 330 |
186 void SharedMemory::Close() { | 331 void SharedMemory::Close() { |
187 shm_.Close(); | 332 shm_.Close(); |
188 shm_ = SharedMemoryHandle(); | 333 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; |
189 } | 380 } |
190 | 381 |
191 bool SharedMemory::ShareToProcessCommon(ProcessHandle process, | 382 bool SharedMemory::ShareToProcessCommon(ProcessHandle process, |
192 SharedMemoryHandle* new_handle, | 383 SharedMemoryHandle* new_handle, |
193 bool close_self, | 384 bool close_self, |
194 ShareMode share_mode) { | 385 ShareMode share_mode) { |
195 DCHECK(shm_.IsValid()); | 386 if (shm_.GetType() == SharedMemoryHandle::MACH) { |
| 387 DCHECK(shm_.IsValid()); |
196 | 388 |
197 bool success = false; | 389 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; |
198 switch (share_mode) { | 412 switch (share_mode) { |
199 case SHARE_CURRENT_MODE: | 413 case SHARE_CURRENT_MODE: |
200 *new_handle = shm_.Duplicate(); | 414 handle_to_dup = shm_.GetFileDescriptor().fd; |
201 success = true; | |
202 break; | 415 break; |
203 case SHARE_READONLY: | 416 case SHARE_READONLY: |
204 success = MakeMachSharedMemoryHandleReadOnly(new_handle, shm_, memory_); | 417 // We could imagine re-opening the file from /dev/fd, but that can't make |
| 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_; |
205 break; | 421 break; |
206 } | 422 } |
207 | 423 |
208 if (success) | 424 const int new_fd = HANDLE_EINTR(dup(handle_to_dup)); |
209 new_handle->SetOwnershipPassesToIPC(true); | 425 if (new_fd < 0) { |
| 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); |
210 | 435 |
211 if (close_self) { | 436 if (close_self) { |
212 Unmap(); | 437 Unmap(); |
213 Close(); | 438 Close(); |
214 } | 439 } |
215 | 440 |
216 return success; | 441 return true; |
217 } | 442 } |
218 | 443 |
219 } // namespace base | 444 } // namespace base |
OLD | NEW |