| OLD | NEW |
| (Empty) |
| 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. | |
| 4 | |
| 5 #include "base/memory/shared_memory.h" | |
| 6 | |
| 7 #include <fcntl.h> | |
| 8 #include <sys/mman.h> | |
| 9 #include <sys/stat.h> | |
| 10 #include <unistd.h> | |
| 11 | |
| 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" | |
| 21 | |
| 22 #if defined(OS_MACOSX) | |
| 23 #include "base/mac/foundation_util.h" | |
| 24 #endif // OS_MACOSX | |
| 25 | |
| 26 namespace base { | |
| 27 | |
| 28 namespace { | |
| 29 | |
| 30 struct ScopedPathUnlinkerTraits { | |
| 31 static FilePath* InvalidValue() { return nullptr; } | |
| 32 | |
| 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"; | |
| 41 } | |
| 42 }; | |
| 43 | |
| 44 // Unlinks the FilePath when the object is destroyed. | |
| 45 typedef ScopedGeneric<FilePath*, ScopedPathUnlinkerTraits> ScopedPathUnlinker; | |
| 46 | |
| 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 // It doesn't make sense to have a open-existing private piece of shmem | |
| 57 DCHECK(!options.open_existing_deprecated); | |
| 58 // Q: Why not use the shm_open() etc. APIs? | |
| 59 // A: Because they're limited to 4mb on OS X. FFFFFFFUUUUUUUUUUU | |
| 60 FilePath directory; | |
| 61 ScopedPathUnlinker path_unlinker; | |
| 62 if (GetShmemTempDir(options.executable, &directory)) { | |
| 63 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466437 | |
| 64 // is fixed. | |
| 65 tracked_objects::ScopedTracker tracking_profile( | |
| 66 FROM_HERE_WITH_EXPLICIT_FUNCTION( | |
| 67 "466437 SharedMemory::Create::OpenTemporaryFile")); | |
| 68 fp->reset(base::CreateAndOpenTemporaryFileInDir(directory, path)); | |
| 69 | |
| 70 // Deleting the file prevents anyone else from mapping it in (making it | |
| 71 // private), and prevents the need for cleanup (once the last fd is | |
| 72 // closed, it is truly freed). | |
| 73 if (*fp) | |
| 74 path_unlinker.reset(path); | |
| 75 } | |
| 76 | |
| 77 if (*fp) { | |
| 78 if (options.share_read_only) { | |
| 79 // TODO(erikchen): Remove ScopedTracker below once | |
| 80 // http://crbug.com/466437 is fixed. | |
| 81 tracked_objects::ScopedTracker tracking_profile( | |
| 82 FROM_HERE_WITH_EXPLICIT_FUNCTION( | |
| 83 "466437 SharedMemory::Create::OpenReadonly")); | |
| 84 // Also open as readonly so that we can ShareReadOnlyToProcess. | |
| 85 readonly_fd->reset(HANDLE_EINTR(open(path->value().c_str(), O_RDONLY))); | |
| 86 if (!readonly_fd->is_valid()) { | |
| 87 DPLOG(ERROR) << "open(\"" << path->value() << "\", O_RDONLY) failed"; | |
| 88 fp->reset(); | |
| 89 return false; | |
| 90 } | |
| 91 } | |
| 92 } | |
| 93 return true; | |
| 94 } | |
| 95 } | |
| 96 | |
| 97 SharedMemory::SharedMemory() | |
| 98 : mapped_file_(-1), | |
| 99 readonly_mapped_file_(-1), | |
| 100 mapped_size_(0), | |
| 101 memory_(NULL), | |
| 102 read_only_(false), | |
| 103 requested_size_(0) { | |
| 104 } | |
| 105 | |
| 106 SharedMemory::SharedMemory(const SharedMemoryHandle& handle, bool read_only) | |
| 107 : mapped_file_(GetFdFromSharedMemoryHandle(handle)), | |
| 108 readonly_mapped_file_(-1), | |
| 109 mapped_size_(0), | |
| 110 memory_(NULL), | |
| 111 read_only_(read_only), | |
| 112 requested_size_(0) { | |
| 113 } | |
| 114 | |
| 115 SharedMemory::SharedMemory(const SharedMemoryHandle& handle, | |
| 116 bool read_only, | |
| 117 ProcessHandle process) | |
| 118 : mapped_file_(GetFdFromSharedMemoryHandle(handle)), | |
| 119 readonly_mapped_file_(-1), | |
| 120 mapped_size_(0), | |
| 121 memory_(NULL), | |
| 122 read_only_(read_only), | |
| 123 requested_size_(0) { | |
| 124 // We don't handle this case yet (note the ignored parameter); let's die if | |
| 125 // someone comes calling. | |
| 126 NOTREACHED(); | |
| 127 } | |
| 128 | |
| 129 SharedMemory::~SharedMemory() { | |
| 130 Unmap(); | |
| 131 Close(); | |
| 132 } | |
| 133 | |
| 134 // static | |
| 135 bool SharedMemory::IsHandleValid(const SharedMemoryHandle& handle) { | |
| 136 return handle.IsValid(); | |
| 137 } | |
| 138 | |
| 139 // static | |
| 140 SharedMemoryHandle SharedMemory::NULLHandle() { | |
| 141 return SharedMemoryHandle(); | |
| 142 } | |
| 143 | |
| 144 // static | |
| 145 void SharedMemory::CloseHandle(const SharedMemoryHandle& handle) { | |
| 146 DCHECK_GE(GetFdFromSharedMemoryHandle(handle), 0); | |
| 147 if (close(GetFdFromSharedMemoryHandle(handle)) < 0) | |
| 148 DPLOG(ERROR) << "close"; | |
| 149 } | |
| 150 | |
| 151 // static | |
| 152 size_t SharedMemory::GetHandleLimit() { | |
| 153 return base::GetMaxFds(); | |
| 154 } | |
| 155 | |
| 156 // static | |
| 157 SharedMemoryHandle SharedMemory::DuplicateHandle( | |
| 158 const SharedMemoryHandle& handle) { | |
| 159 return handle.Duplicate(); | |
| 160 } | |
| 161 | |
| 162 // static | |
| 163 int SharedMemory::GetFdFromSharedMemoryHandle( | |
| 164 const SharedMemoryHandle& handle) { | |
| 165 return handle.GetFileDescriptor().fd; | |
| 166 } | |
| 167 | |
| 168 bool SharedMemory::CreateAndMapAnonymous(size_t size) { | |
| 169 return CreateAnonymous(size) && Map(size); | |
| 170 } | |
| 171 | |
| 172 // static | |
| 173 int SharedMemory::GetSizeFromSharedMemoryHandle( | |
| 174 const SharedMemoryHandle& handle) { | |
| 175 struct stat st; | |
| 176 if (fstat(GetFdFromSharedMemoryHandle(handle), &st) != 0) | |
| 177 return -1; | |
| 178 return st.st_size; | |
| 179 } | |
| 180 | |
| 181 // Chromium mostly only uses the unique/private shmem as specified by | |
| 182 // "name == L"". The exception is in the StatsTable. | |
| 183 // TODO(jrg): there is no way to "clean up" all unused named shmem if | |
| 184 // we restart from a crash. (That isn't a new problem, but it is a problem.) | |
| 185 // In case we want to delete it later, it may be useful to save the value | |
| 186 // of mem_filename after FilePathForMemoryName(). | |
| 187 bool SharedMemory::Create(const SharedMemoryCreateOptions& options) { | |
| 188 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466437 | |
| 189 // is fixed. | |
| 190 tracked_objects::ScopedTracker tracking_profile1( | |
| 191 FROM_HERE_WITH_EXPLICIT_FUNCTION( | |
| 192 "466437 SharedMemory::Create::Start")); | |
| 193 DCHECK_EQ(-1, mapped_file_); | |
| 194 if (options.size == 0) return false; | |
| 195 | |
| 196 if (options.size > static_cast<size_t>(std::numeric_limits<int>::max())) | |
| 197 return false; | |
| 198 | |
| 199 // This function theoretically can block on the disk, but realistically | |
| 200 // the temporary files we create will just go into the buffer cache | |
| 201 // and be deleted before they ever make it out to disk. | |
| 202 base::ThreadRestrictions::ScopedAllowIO allow_io; | |
| 203 | |
| 204 ScopedFILE fp; | |
| 205 bool fix_size = true; | |
| 206 ScopedFD readonly_fd; | |
| 207 | |
| 208 FilePath path; | |
| 209 if (options.name_deprecated == NULL || options.name_deprecated->empty()) { | |
| 210 bool result = | |
| 211 CreateAnonymousSharedMemory(options, &fp, &readonly_fd, &path); | |
| 212 if (!result) | |
| 213 return false; | |
| 214 } else { | |
| 215 if (!FilePathForMemoryName(*options.name_deprecated, &path)) | |
| 216 return false; | |
| 217 | |
| 218 // Make sure that the file is opened without any permission | |
| 219 // to other users on the system. | |
| 220 const mode_t kOwnerOnly = S_IRUSR | S_IWUSR; | |
| 221 | |
| 222 // First, try to create the file. | |
| 223 int fd = HANDLE_EINTR( | |
| 224 open(path.value().c_str(), O_RDWR | O_CREAT | O_EXCL, kOwnerOnly)); | |
| 225 if (fd == -1 && options.open_existing_deprecated) { | |
| 226 // If this doesn't work, try and open an existing file in append mode. | |
| 227 // Opening an existing file in a world writable directory has two main | |
| 228 // security implications: | |
| 229 // - Attackers could plant a file under their control, so ownership of | |
| 230 // the file is checked below. | |
| 231 // - Attackers could plant a symbolic link so that an unexpected file | |
| 232 // is opened, so O_NOFOLLOW is passed to open(). | |
| 233 fd = HANDLE_EINTR( | |
| 234 open(path.value().c_str(), O_RDWR | O_APPEND | O_NOFOLLOW)); | |
| 235 | |
| 236 // Check that the current user owns the file. | |
| 237 // If uid != euid, then a more complex permission model is used and this | |
| 238 // API is not appropriate. | |
| 239 const uid_t real_uid = getuid(); | |
| 240 const uid_t effective_uid = geteuid(); | |
| 241 struct stat sb; | |
| 242 if (fd >= 0 && | |
| 243 (fstat(fd, &sb) != 0 || sb.st_uid != real_uid || | |
| 244 sb.st_uid != effective_uid)) { | |
| 245 LOG(ERROR) << | |
| 246 "Invalid owner when opening existing shared memory file."; | |
| 247 close(fd); | |
| 248 return false; | |
| 249 } | |
| 250 | |
| 251 // An existing file was opened, so its size should not be fixed. | |
| 252 fix_size = false; | |
| 253 } | |
| 254 | |
| 255 if (options.share_read_only) { | |
| 256 // Also open as readonly so that we can ShareReadOnlyToProcess. | |
| 257 readonly_fd.reset(HANDLE_EINTR(open(path.value().c_str(), O_RDONLY))); | |
| 258 if (!readonly_fd.is_valid()) { | |
| 259 DPLOG(ERROR) << "open(\"" << path.value() << "\", O_RDONLY) failed"; | |
| 260 close(fd); | |
| 261 fd = -1; | |
| 262 return false; | |
| 263 } | |
| 264 } | |
| 265 if (fd >= 0) { | |
| 266 // "a+" is always appropriate: if it's a new file, a+ is similar to w+. | |
| 267 fp.reset(fdopen(fd, "a+")); | |
| 268 } | |
| 269 } | |
| 270 if (fp && fix_size) { | |
| 271 // Get current size. | |
| 272 struct stat stat; | |
| 273 if (fstat(fileno(fp.get()), &stat) != 0) | |
| 274 return false; | |
| 275 const size_t current_size = stat.st_size; | |
| 276 if (current_size != options.size) { | |
| 277 if (HANDLE_EINTR(ftruncate(fileno(fp.get()), options.size)) != 0) | |
| 278 return false; | |
| 279 } | |
| 280 requested_size_ = options.size; | |
| 281 } | |
| 282 if (fp == NULL) { | |
| 283 PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed"; | |
| 284 return false; | |
| 285 } | |
| 286 | |
| 287 return PrepareMapFile(fp.Pass(), readonly_fd.Pass()); | |
| 288 } | |
| 289 | |
| 290 // Our current implementation of shmem is with mmap()ing of files. | |
| 291 // These files need to be deleted explicitly. | |
| 292 // In practice this call is only needed for unit tests. | |
| 293 bool SharedMemory::Delete(const std::string& name) { | |
| 294 FilePath path; | |
| 295 if (!FilePathForMemoryName(name, &path)) | |
| 296 return false; | |
| 297 | |
| 298 if (PathExists(path)) | |
| 299 return base::DeleteFile(path, false); | |
| 300 | |
| 301 // Doesn't exist, so success. | |
| 302 return true; | |
| 303 } | |
| 304 | |
| 305 bool SharedMemory::Open(const std::string& name, bool read_only) { | |
| 306 FilePath path; | |
| 307 if (!FilePathForMemoryName(name, &path)) | |
| 308 return false; | |
| 309 | |
| 310 read_only_ = read_only; | |
| 311 | |
| 312 const char *mode = read_only ? "r" : "r+"; | |
| 313 ScopedFILE fp(base::OpenFile(path, mode)); | |
| 314 ScopedFD readonly_fd(HANDLE_EINTR(open(path.value().c_str(), O_RDONLY))); | |
| 315 if (!readonly_fd.is_valid()) { | |
| 316 DPLOG(ERROR) << "open(\"" << path.value() << "\", O_RDONLY) failed"; | |
| 317 return false; | |
| 318 } | |
| 319 return PrepareMapFile(fp.Pass(), readonly_fd.Pass()); | |
| 320 } | |
| 321 | |
| 322 bool SharedMemory::MapAt(off_t offset, size_t bytes) { | |
| 323 if (mapped_file_ == -1) | |
| 324 return false; | |
| 325 | |
| 326 if (bytes > static_cast<size_t>(std::numeric_limits<int>::max())) | |
| 327 return false; | |
| 328 | |
| 329 if (memory_) | |
| 330 return false; | |
| 331 | |
| 332 memory_ = mmap(NULL, bytes, PROT_READ | (read_only_ ? 0 : PROT_WRITE), | |
| 333 MAP_SHARED, mapped_file_, offset); | |
| 334 | |
| 335 bool mmap_succeeded = memory_ != (void*)-1 && memory_ != NULL; | |
| 336 if (mmap_succeeded) { | |
| 337 mapped_size_ = bytes; | |
| 338 DCHECK_EQ(0U, reinterpret_cast<uintptr_t>(memory_) & | |
| 339 (SharedMemory::MAP_MINIMUM_ALIGNMENT - 1)); | |
| 340 } else { | |
| 341 memory_ = NULL; | |
| 342 } | |
| 343 | |
| 344 return mmap_succeeded; | |
| 345 } | |
| 346 | |
| 347 bool SharedMemory::Unmap() { | |
| 348 if (memory_ == NULL) | |
| 349 return false; | |
| 350 | |
| 351 munmap(memory_, mapped_size_); | |
| 352 memory_ = NULL; | |
| 353 mapped_size_ = 0; | |
| 354 return true; | |
| 355 } | |
| 356 | |
| 357 SharedMemoryHandle SharedMemory::handle() const { | |
| 358 return SharedMemoryHandle(mapped_file_, false); | |
| 359 } | |
| 360 | |
| 361 void SharedMemory::Close() { | |
| 362 if (mapped_file_ > 0) { | |
| 363 if (close(mapped_file_) < 0) | |
| 364 PLOG(ERROR) << "close"; | |
| 365 mapped_file_ = -1; | |
| 366 } | |
| 367 if (readonly_mapped_file_ > 0) { | |
| 368 if (close(readonly_mapped_file_) < 0) | |
| 369 PLOG(ERROR) << "close"; | |
| 370 readonly_mapped_file_ = -1; | |
| 371 } | |
| 372 } | |
| 373 | |
| 374 bool SharedMemory::PrepareMapFile(ScopedFILE fp, ScopedFD readonly_fd) { | |
| 375 DCHECK_EQ(-1, mapped_file_); | |
| 376 DCHECK_EQ(-1, readonly_mapped_file_); | |
| 377 if (fp == NULL) | |
| 378 return false; | |
| 379 | |
| 380 // This function theoretically can block on the disk, but realistically | |
| 381 // the temporary files we create will just go into the buffer cache | |
| 382 // and be deleted before they ever make it out to disk. | |
| 383 base::ThreadRestrictions::ScopedAllowIO allow_io; | |
| 384 | |
| 385 struct stat st = {}; | |
| 386 if (fstat(fileno(fp.get()), &st)) | |
| 387 NOTREACHED(); | |
| 388 if (readonly_fd.is_valid()) { | |
| 389 struct stat readonly_st = {}; | |
| 390 if (fstat(readonly_fd.get(), &readonly_st)) | |
| 391 NOTREACHED(); | |
| 392 if (st.st_dev != readonly_st.st_dev || st.st_ino != readonly_st.st_ino) { | |
| 393 LOG(ERROR) << "writable and read-only inodes don't match; bailing"; | |
| 394 return false; | |
| 395 } | |
| 396 } | |
| 397 | |
| 398 mapped_file_ = HANDLE_EINTR(dup(fileno(fp.get()))); | |
| 399 if (mapped_file_ == -1) { | |
| 400 if (errno == EMFILE) { | |
| 401 LOG(WARNING) << "Shared memory creation failed; out of file descriptors"; | |
| 402 return false; | |
| 403 } else { | |
| 404 NOTREACHED() << "Call to dup failed, errno=" << errno; | |
| 405 } | |
| 406 } | |
| 407 readonly_mapped_file_ = readonly_fd.release(); | |
| 408 | |
| 409 return true; | |
| 410 } | |
| 411 | |
| 412 // For the given shmem named |mem_name|, return a filename to mmap() | |
| 413 // (and possibly create). Modifies |filename|. Return false on | |
| 414 // error, or true of we are happy. | |
| 415 bool SharedMemory::FilePathForMemoryName(const std::string& mem_name, | |
| 416 FilePath* path) { | |
| 417 // mem_name will be used for a filename; make sure it doesn't | |
| 418 // contain anything which will confuse us. | |
| 419 DCHECK_EQ(std::string::npos, mem_name.find('/')); | |
| 420 DCHECK_EQ(std::string::npos, mem_name.find('\0')); | |
| 421 | |
| 422 FilePath temp_dir; | |
| 423 if (!GetShmemTempDir(false, &temp_dir)) | |
| 424 return false; | |
| 425 | |
| 426 std::string name_base = std::string(base::mac::BaseBundleID()); | |
| 427 *path = temp_dir.AppendASCII(name_base + ".shmem." + mem_name); | |
| 428 return true; | |
| 429 } | |
| 430 | |
| 431 bool SharedMemory::ShareToProcessCommon(ProcessHandle process, | |
| 432 SharedMemoryHandle* new_handle, | |
| 433 bool close_self, | |
| 434 ShareMode share_mode) { | |
| 435 int handle_to_dup = -1; | |
| 436 switch(share_mode) { | |
| 437 case SHARE_CURRENT_MODE: | |
| 438 handle_to_dup = mapped_file_; | |
| 439 break; | |
| 440 case SHARE_READONLY: | |
| 441 // We could imagine re-opening the file from /dev/fd, but that can't make | |
| 442 // it readonly on Mac: https://codereview.chromium.org/27265002/#msg10 | |
| 443 CHECK_GE(readonly_mapped_file_, 0); | |
| 444 handle_to_dup = readonly_mapped_file_; | |
| 445 break; | |
| 446 } | |
| 447 | |
| 448 const int new_fd = HANDLE_EINTR(dup(handle_to_dup)); | |
| 449 if (new_fd < 0) { | |
| 450 DPLOG(ERROR) << "dup() failed."; | |
| 451 return false; | |
| 452 } | |
| 453 | |
| 454 new_handle->SetFileHandle(new_fd, true); | |
| 455 | |
| 456 if (close_self) { | |
| 457 Unmap(); | |
| 458 Close(); | |
| 459 } | |
| 460 | |
| 461 return true; | |
| 462 } | |
| 463 | |
| 464 } // namespace base | |
| OLD | NEW |