Home | History | Annotate | Download | only in memory
      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 <errno.h>
      8 #include <fcntl.h>
      9 #include <stddef.h>
     10 #include <sys/mman.h>
     11 #include <sys/stat.h>
     12 #include <unistd.h>
     13 
     14 #include "base/files/file_util.h"
     15 #include "base/files/scoped_file.h"
     16 #include "base/logging.h"
     17 #include "base/memory/shared_memory_helper.h"
     18 #include "base/memory/shared_memory_tracker.h"
     19 #include "base/posix/eintr_wrapper.h"
     20 #include "base/posix/safe_strerror.h"
     21 #include "base/process/process_metrics.h"
     22 #include "base/scoped_generic.h"
     23 #include "base/strings/utf_string_conversions.h"
     24 #include "base/threading/thread_restrictions.h"
     25 #include "base/trace_event/trace_event.h"
     26 #include "build/build_config.h"
     27 
     28 #if defined(OS_ANDROID)
     29 #include "base/os_compat_android.h"
     30 #endif
     31 #if defined(OS_ANDROID) || defined(__ANDROID__)
     32 #include "third_party/ashmem/ashmem.h"
     33 #endif
     34 
     35 namespace base {
     36 
     37 SharedMemory::SharedMemory()
     38     : mapped_file_(-1),
     39       readonly_mapped_file_(-1),
     40       mapped_size_(0),
     41       memory_(NULL),
     42       read_only_(false),
     43       requested_size_(0) {
     44 }
     45 
     46 SharedMemory::SharedMemory(const SharedMemoryHandle& handle, bool read_only)
     47     : mapped_file_(handle.fd),
     48       readonly_mapped_file_(-1),
     49       mapped_size_(0),
     50       memory_(NULL),
     51       read_only_(read_only),
     52       requested_size_(0) {
     53 }
     54 
     55 SharedMemory::~SharedMemory() {
     56   Unmap();
     57   Close();
     58 }
     59 
     60 // static
     61 bool SharedMemory::IsHandleValid(const SharedMemoryHandle& handle) {
     62   return handle.fd >= 0;
     63 }
     64 
     65 // static
     66 SharedMemoryHandle SharedMemory::NULLHandle() {
     67   return SharedMemoryHandle();
     68 }
     69 
     70 // static
     71 void SharedMemory::CloseHandle(const SharedMemoryHandle& handle) {
     72   DCHECK_GE(handle.fd, 0);
     73   if (IGNORE_EINTR(close(handle.fd)) < 0)
     74     DPLOG(ERROR) << "close";
     75 }
     76 
     77 // static
     78 size_t SharedMemory::GetHandleLimit() {
     79   return base::GetMaxFds();
     80 }
     81 
     82 // static
     83 SharedMemoryHandle SharedMemory::DuplicateHandle(
     84     const SharedMemoryHandle& handle) {
     85   int duped_handle = HANDLE_EINTR(dup(handle.fd));
     86   if (duped_handle < 0)
     87     return base::SharedMemory::NULLHandle();
     88   return base::FileDescriptor(duped_handle, true);
     89 }
     90 
     91 // static
     92 int SharedMemory::GetFdFromSharedMemoryHandle(
     93     const SharedMemoryHandle& handle) {
     94   return handle.fd;
     95 }
     96 
     97 bool SharedMemory::CreateAndMapAnonymous(size_t size) {
     98   return CreateAnonymous(size) && Map(size);
     99 }
    100 
    101 #if !defined(OS_ANDROID) && !defined(__ANDROID__)
    102 // static
    103 bool SharedMemory::GetSizeFromSharedMemoryHandle(
    104     const SharedMemoryHandle& handle,
    105     size_t* size) {
    106   struct stat st;
    107   if (fstat(handle.fd, &st) != 0)
    108     return false;
    109   if (st.st_size < 0)
    110     return false;
    111   *size = st.st_size;
    112   return true;
    113 }
    114 
    115 // Chromium mostly only uses the unique/private shmem as specified by
    116 // "name == L"". The exception is in the StatsTable.
    117 // TODO(jrg): there is no way to "clean up" all unused named shmem if
    118 // we restart from a crash.  (That isn't a new problem, but it is a problem.)
    119 // In case we want to delete it later, it may be useful to save the value
    120 // of mem_filename after FilePathForMemoryName().
    121 bool SharedMemory::Create(const SharedMemoryCreateOptions& options) {
    122   DCHECK_EQ(-1, mapped_file_);
    123   if (options.size == 0) return false;
    124 
    125   if (options.size > static_cast<size_t>(std::numeric_limits<int>::max()))
    126     return false;
    127 
    128   // This function theoretically can block on the disk, but realistically
    129   // the temporary files we create will just go into the buffer cache
    130   // and be deleted before they ever make it out to disk.
    131   base::ThreadRestrictions::ScopedAllowIO allow_io;
    132 
    133   ScopedFILE fp;
    134   bool fix_size = true;
    135   ScopedFD readonly_fd;
    136 
    137   FilePath path;
    138   if (options.name_deprecated == NULL || options.name_deprecated->empty()) {
    139     bool result =
    140         CreateAnonymousSharedMemory(options, &fp, &readonly_fd, &path);
    141     if (!result)
    142       return false;
    143   } else {
    144     if (!FilePathForMemoryName(*options.name_deprecated, &path))
    145       return false;
    146 
    147     // Make sure that the file is opened without any permission
    148     // to other users on the system.
    149     const mode_t kOwnerOnly = S_IRUSR | S_IWUSR;
    150 
    151     // First, try to create the file.
    152     int fd = HANDLE_EINTR(
    153         open(path.value().c_str(), O_RDWR | O_CREAT | O_EXCL, kOwnerOnly));
    154     if (fd == -1 && options.open_existing_deprecated) {
    155       // If this doesn't work, try and open an existing file in append mode.
    156       // Opening an existing file in a world writable directory has two main
    157       // security implications:
    158       // - Attackers could plant a file under their control, so ownership of
    159       //   the file is checked below.
    160       // - Attackers could plant a symbolic link so that an unexpected file
    161       //   is opened, so O_NOFOLLOW is passed to open().
    162       fd = HANDLE_EINTR(
    163           open(path.value().c_str(), O_RDWR | O_APPEND | O_NOFOLLOW));
    164 
    165       // Check that the current user owns the file.
    166       // If uid != euid, then a more complex permission model is used and this
    167       // API is not appropriate.
    168       const uid_t real_uid = getuid();
    169       const uid_t effective_uid = geteuid();
    170       struct stat sb;
    171       if (fd >= 0 &&
    172           (fstat(fd, &sb) != 0 || sb.st_uid != real_uid ||
    173            sb.st_uid != effective_uid)) {
    174         LOG(ERROR) <<
    175             "Invalid owner when opening existing shared memory file.";
    176         close(fd);
    177         return false;
    178       }
    179 
    180       // An existing file was opened, so its size should not be fixed.
    181       fix_size = false;
    182     }
    183 
    184     if (options.share_read_only) {
    185       // Also open as readonly so that we can ShareReadOnlyToProcess.
    186       readonly_fd.reset(HANDLE_EINTR(open(path.value().c_str(), O_RDONLY)));
    187       if (!readonly_fd.is_valid()) {
    188         DPLOG(ERROR) << "open(\"" << path.value() << "\", O_RDONLY) failed";
    189         close(fd);
    190         fd = -1;
    191         return false;
    192       }
    193     }
    194     if (fd >= 0) {
    195       // "a+" is always appropriate: if it's a new file, a+ is similar to w+.
    196       fp.reset(fdopen(fd, "a+"));
    197     }
    198   }
    199   if (fp && fix_size) {
    200     // Get current size.
    201     struct stat stat;
    202     if (fstat(fileno(fp.get()), &stat) != 0)
    203       return false;
    204     const size_t current_size = stat.st_size;
    205     if (current_size != options.size) {
    206       if (HANDLE_EINTR(ftruncate(fileno(fp.get()), options.size)) != 0)
    207         return false;
    208     }
    209     requested_size_ = options.size;
    210   }
    211   if (fp == NULL) {
    212     PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed";
    213     FilePath dir = path.DirName();
    214     if (access(dir.value().c_str(), W_OK | X_OK) < 0) {
    215       PLOG(ERROR) << "Unable to access(W_OK|X_OK) " << dir.value();
    216       if (dir.value() == "/dev/shm") {
    217         LOG(FATAL) << "This is frequently caused by incorrect permissions on "
    218                    << "/dev/shm.  Try 'sudo chmod 1777 /dev/shm' to fix.";
    219       }
    220     }
    221     return false;
    222   }
    223 
    224   return PrepareMapFile(std::move(fp), std::move(readonly_fd), &mapped_file_,
    225                         &readonly_mapped_file_);
    226 }
    227 
    228 // Our current implementation of shmem is with mmap()ing of files.
    229 // These files need to be deleted explicitly.
    230 // In practice this call is only needed for unit tests.
    231 bool SharedMemory::Delete(const std::string& name) {
    232   FilePath path;
    233   if (!FilePathForMemoryName(name, &path))
    234     return false;
    235 
    236   if (PathExists(path))
    237     return base::DeleteFile(path, false);
    238 
    239   // Doesn't exist, so success.
    240   return true;
    241 }
    242 
    243 bool SharedMemory::Open(const std::string& name, bool read_only) {
    244   FilePath path;
    245   if (!FilePathForMemoryName(name, &path))
    246     return false;
    247 
    248   read_only_ = read_only;
    249 
    250   const char *mode = read_only ? "r" : "r+";
    251   ScopedFILE fp(base::OpenFile(path, mode));
    252   ScopedFD readonly_fd(HANDLE_EINTR(open(path.value().c_str(), O_RDONLY)));
    253   if (!readonly_fd.is_valid()) {
    254     DPLOG(ERROR) << "open(\"" << path.value() << "\", O_RDONLY) failed";
    255     return false;
    256   }
    257   return PrepareMapFile(std::move(fp), std::move(readonly_fd), &mapped_file_,
    258                         &readonly_mapped_file_);
    259 }
    260 #endif  // !defined(OS_ANDROID) && !defined(__ANDROID__)
    261 
    262 bool SharedMemory::MapAt(off_t offset, size_t bytes) {
    263   if (mapped_file_ == -1)
    264     return false;
    265 
    266   if (bytes > static_cast<size_t>(std::numeric_limits<int>::max()))
    267     return false;
    268 
    269   if (memory_)
    270     return false;
    271 
    272 #if defined(OS_ANDROID) || defined(__ANDROID__)
    273   // On Android, Map can be called with a size and offset of zero to use the
    274   // ashmem-determined size.
    275   if (bytes == 0) {
    276     DCHECK_EQ(0, offset);
    277     int ashmem_bytes = ashmem_get_size_region(mapped_file_);
    278     if (ashmem_bytes < 0)
    279       return false;
    280     bytes = ashmem_bytes;
    281   }
    282 #endif
    283 
    284   memory_ = mmap(NULL, bytes, PROT_READ | (read_only_ ? 0 : PROT_WRITE),
    285                  MAP_SHARED, mapped_file_, offset);
    286 
    287   bool mmap_succeeded = memory_ != (void*)-1 && memory_ != NULL;
    288   if (mmap_succeeded) {
    289     mapped_size_ = bytes;
    290     DCHECK_EQ(0U,
    291               reinterpret_cast<uintptr_t>(memory_) &
    292                   (SharedMemory::MAP_MINIMUM_ALIGNMENT - 1));
    293     SharedMemoryTracker::GetInstance()->IncrementMemoryUsage(*this);
    294   } else {
    295     memory_ = NULL;
    296   }
    297 
    298   return mmap_succeeded;
    299 }
    300 
    301 bool SharedMemory::Unmap() {
    302   if (memory_ == NULL)
    303     return false;
    304 
    305   munmap(memory_, mapped_size_);
    306   SharedMemoryTracker::GetInstance()->DecrementMemoryUsage(*this);
    307   memory_ = NULL;
    308   mapped_size_ = 0;
    309   return true;
    310 }
    311 
    312 SharedMemoryHandle SharedMemory::handle() const {
    313   return FileDescriptor(mapped_file_, false);
    314 }
    315 
    316 SharedMemoryHandle SharedMemory::TakeHandle() {
    317   FileDescriptor handle(mapped_file_, true);
    318   mapped_file_ = -1;
    319   memory_ = nullptr;
    320   mapped_size_ = 0;
    321   return handle;
    322 }
    323 
    324 void SharedMemory::Close() {
    325   if (mapped_file_ > 0) {
    326     if (IGNORE_EINTR(close(mapped_file_)) < 0)
    327       PLOG(ERROR) << "close";
    328     mapped_file_ = -1;
    329   }
    330   if (readonly_mapped_file_ > 0) {
    331     if (IGNORE_EINTR(close(readonly_mapped_file_)) < 0)
    332       PLOG(ERROR) << "close";
    333     readonly_mapped_file_ = -1;
    334   }
    335 }
    336 
    337 #if !defined(OS_ANDROID) && !defined(__ANDROID__)
    338 // For the given shmem named |mem_name|, return a filename to mmap()
    339 // (and possibly create).  Modifies |filename|.  Return false on
    340 // error, or true of we are happy.
    341 bool SharedMemory::FilePathForMemoryName(const std::string& mem_name,
    342                                          FilePath* path) {
    343   // mem_name will be used for a filename; make sure it doesn't
    344   // contain anything which will confuse us.
    345   DCHECK_EQ(std::string::npos, mem_name.find('/'));
    346   DCHECK_EQ(std::string::npos, mem_name.find('\0'));
    347 
    348   FilePath temp_dir;
    349   if (!GetShmemTempDir(false, &temp_dir))
    350     return false;
    351 
    352 #if defined(GOOGLE_CHROME_BUILD)
    353   std::string name_base = std::string("com.google.Chrome");
    354 #else
    355   std::string name_base = std::string("org.chromium.Chromium");
    356 #endif
    357   *path = temp_dir.AppendASCII(name_base + ".shmem." + mem_name);
    358   return true;
    359 }
    360 #endif  // !defined(OS_ANDROID) && !defined(__ANDROID__)
    361 
    362 bool SharedMemory::ShareToProcessCommon(ProcessHandle process,
    363                                         SharedMemoryHandle* new_handle,
    364                                         bool close_self,
    365                                         ShareMode share_mode) {
    366   int handle_to_dup = -1;
    367   switch(share_mode) {
    368     case SHARE_CURRENT_MODE:
    369       handle_to_dup = mapped_file_;
    370       break;
    371     case SHARE_READONLY:
    372       // We could imagine re-opening the file from /dev/fd, but that can't make
    373       // it readonly on Mac: https://codereview.chromium.org/27265002/#msg10
    374       CHECK_GE(readonly_mapped_file_, 0);
    375       handle_to_dup = readonly_mapped_file_;
    376       break;
    377   }
    378 
    379   const int new_fd = HANDLE_EINTR(dup(handle_to_dup));
    380   if (new_fd < 0) {
    381     if (close_self) {
    382       Unmap();
    383       Close();
    384     }
    385     DPLOG(ERROR) << "dup() failed.";
    386     return false;
    387   }
    388 
    389   new_handle->fd = new_fd;
    390   new_handle->auto_close = true;
    391 
    392   if (close_self) {
    393     Unmap();
    394     Close();
    395   }
    396 
    397   return true;
    398 }
    399 
    400 bool SharedMemory::GetUniqueId(SharedMemory::UniqueId* id) const {
    401   // This function is called just after mmap. fstat is a system call that might
    402   // cause I/O. It's safe to call fstat here because mmap for shared memory is
    403   // called in two cases:
    404   // 1) To handle file-mapped memory
    405   // 2) To handle annonymous shared memory
    406   // In 1), I/O is already permitted. In 2), the backend is on page cache and
    407   // fstat doesn't cause I/O access to the disk. See the discussion at
    408   // crbug.com/604726#c41.
    409   base::ThreadRestrictions::ScopedAllowIO allow_io;
    410   struct stat file_stat;
    411   if (HANDLE_EINTR(::fstat(static_cast<int>(handle().fd), &file_stat)) != 0)
    412     return false;
    413   id->first = file_stat.st_dev;
    414   id->second = file_stat.st_ino;
    415   return true;
    416 }
    417 
    418 }  // namespace base
    419