Home | History | Annotate | Download | only in memory
      1 // Copyright (c) 2011 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 "base/logging.h"
      8 #include "base/strings/utf_string_conversions.h"
      9 
     10 namespace {
     11 
     12 // Returns the length of the memory section starting at the supplied address.
     13 size_t GetMemorySectionSize(void* address) {
     14   MEMORY_BASIC_INFORMATION memory_info;
     15   if (!::VirtualQuery(address, &memory_info, sizeof(memory_info)))
     16     return 0;
     17   return memory_info.RegionSize - (static_cast<char*>(address) -
     18          static_cast<char*>(memory_info.AllocationBase));
     19 }
     20 
     21 }  // namespace.
     22 
     23 namespace base {
     24 
     25 SharedMemory::SharedMemory()
     26     : mapped_file_(NULL),
     27       memory_(NULL),
     28       read_only_(false),
     29       mapped_size_(0),
     30       requested_size_(0),
     31       lock_(NULL) {
     32 }
     33 
     34 SharedMemory::SharedMemory(const std::wstring& name)
     35     : mapped_file_(NULL),
     36       memory_(NULL),
     37       read_only_(false),
     38       requested_size_(0),
     39       mapped_size_(0),
     40       lock_(NULL),
     41       name_(name) {
     42 }
     43 
     44 SharedMemory::SharedMemory(SharedMemoryHandle handle, bool read_only)
     45     : mapped_file_(handle),
     46       memory_(NULL),
     47       read_only_(read_only),
     48       requested_size_(0),
     49       mapped_size_(0),
     50       lock_(NULL) {
     51 }
     52 
     53 SharedMemory::SharedMemory(SharedMemoryHandle handle, bool read_only,
     54                            ProcessHandle process)
     55     : mapped_file_(NULL),
     56       memory_(NULL),
     57       read_only_(read_only),
     58       requested_size_(0),
     59       mapped_size_(0),
     60       lock_(NULL) {
     61   ::DuplicateHandle(process, handle,
     62                     GetCurrentProcess(), &mapped_file_,
     63                     STANDARD_RIGHTS_REQUIRED |
     64                     (read_only_ ? FILE_MAP_READ : FILE_MAP_ALL_ACCESS),
     65                     FALSE, 0);
     66 }
     67 
     68 SharedMemory::~SharedMemory() {
     69   Close();
     70   if (lock_ != NULL)
     71     CloseHandle(lock_);
     72 }
     73 
     74 // static
     75 bool SharedMemory::IsHandleValid(const SharedMemoryHandle& handle) {
     76   return handle != NULL;
     77 }
     78 
     79 // static
     80 SharedMemoryHandle SharedMemory::NULLHandle() {
     81   return NULL;
     82 }
     83 
     84 // static
     85 void SharedMemory::CloseHandle(const SharedMemoryHandle& handle) {
     86   DCHECK(handle != NULL);
     87   ::CloseHandle(handle);
     88 }
     89 
     90 // static
     91 size_t SharedMemory::GetHandleLimit() {
     92   // Rounded down from value reported here:
     93   // http://blogs.technet.com/b/markrussinovich/archive/2009/09/29/3283844.aspx
     94   return static_cast<size_t>(1 << 23);
     95 }
     96 
     97 bool SharedMemory::CreateAndMapAnonymous(size_t size) {
     98   return CreateAnonymous(size) && Map(size);
     99 }
    100 
    101 bool SharedMemory::Create(const SharedMemoryCreateOptions& options) {
    102   // TODO(bsy,sehr): crbug.com/210609 NaCl forces us to round up 64k here,
    103   // wasting 32k per mapping on average.
    104   static const size_t kSectionMask = 65536 - 1;
    105   DCHECK(!options.executable);
    106   DCHECK(!mapped_file_);
    107   if (options.size == 0)
    108     return false;
    109 
    110   // Check maximum accounting for overflow.
    111   if (options.size >
    112       static_cast<size_t>(std::numeric_limits<int>::max()) - kSectionMask)
    113     return false;
    114 
    115   size_t rounded_size = (options.size + kSectionMask) & ~kSectionMask;
    116   name_ = ASCIIToWide(options.name == NULL ? "" : *options.name);
    117   mapped_file_ = CreateFileMapping(INVALID_HANDLE_VALUE, NULL,
    118       PAGE_READWRITE, 0, static_cast<DWORD>(rounded_size),
    119       name_.empty() ? NULL : name_.c_str());
    120   if (!mapped_file_)
    121     return false;
    122 
    123   requested_size_ = options.size;
    124 
    125   // Check if the shared memory pre-exists.
    126   if (GetLastError() == ERROR_ALREADY_EXISTS) {
    127     // If the file already existed, set requested_size_ to 0 to show that
    128     // we don't know the size.
    129     requested_size_ = 0;
    130     if (!options.open_existing) {
    131       Close();
    132       return false;
    133     }
    134   }
    135 
    136   return true;
    137 }
    138 
    139 bool SharedMemory::Delete(const std::string& name) {
    140   // intentionally empty -- there is nothing for us to do on Windows.
    141   return true;
    142 }
    143 
    144 bool SharedMemory::Open(const std::string& name, bool read_only) {
    145   DCHECK(!mapped_file_);
    146 
    147   name_ = ASCIIToWide(name);
    148   read_only_ = read_only;
    149   mapped_file_ = OpenFileMapping(
    150       read_only_ ? FILE_MAP_READ : FILE_MAP_ALL_ACCESS, false,
    151       name_.empty() ? NULL : name_.c_str());
    152   if (mapped_file_ != NULL) {
    153     // Note: size_ is not set in this case.
    154     return true;
    155   }
    156   return false;
    157 }
    158 
    159 bool SharedMemory::MapAt(off_t offset, size_t bytes) {
    160   if (mapped_file_ == NULL)
    161     return false;
    162 
    163   if (bytes > static_cast<size_t>(std::numeric_limits<int>::max()))
    164     return false;
    165 
    166   memory_ = MapViewOfFile(mapped_file_,
    167                           read_only_ ? FILE_MAP_READ : FILE_MAP_ALL_ACCESS,
    168                           static_cast<uint64>(offset) >> 32,
    169                           static_cast<DWORD>(offset),
    170                           bytes);
    171   if (memory_ != NULL) {
    172     DCHECK_EQ(0U, reinterpret_cast<uintptr_t>(memory_) &
    173         (SharedMemory::MAP_MINIMUM_ALIGNMENT - 1));
    174     mapped_size_ = GetMemorySectionSize(memory_);
    175     return true;
    176   }
    177   return false;
    178 }
    179 
    180 bool SharedMemory::Unmap() {
    181   if (memory_ == NULL)
    182     return false;
    183 
    184   UnmapViewOfFile(memory_);
    185   memory_ = NULL;
    186   return true;
    187 }
    188 
    189 bool SharedMemory::ShareToProcessCommon(ProcessHandle process,
    190                                         SharedMemoryHandle *new_handle,
    191                                         bool close_self) {
    192   *new_handle = 0;
    193   DWORD access = STANDARD_RIGHTS_REQUIRED | FILE_MAP_READ;
    194   DWORD options = 0;
    195   HANDLE mapped_file = mapped_file_;
    196   HANDLE result;
    197   if (!read_only_)
    198     access |= FILE_MAP_WRITE;
    199   if (close_self) {
    200     // DUPLICATE_CLOSE_SOURCE causes DuplicateHandle to close mapped_file.
    201     options = DUPLICATE_CLOSE_SOURCE;
    202     mapped_file_ = NULL;
    203     Unmap();
    204   }
    205 
    206   if (process == GetCurrentProcess() && close_self) {
    207     *new_handle = mapped_file;
    208     return true;
    209   }
    210 
    211   if (!DuplicateHandle(GetCurrentProcess(), mapped_file, process,
    212       &result, access, FALSE, options))
    213     return false;
    214   *new_handle = result;
    215   return true;
    216 }
    217 
    218 
    219 void SharedMemory::Close() {
    220   if (memory_ != NULL) {
    221     UnmapViewOfFile(memory_);
    222     memory_ = NULL;
    223   }
    224 
    225   if (mapped_file_ != NULL) {
    226     CloseHandle(mapped_file_);
    227     mapped_file_ = NULL;
    228   }
    229 }
    230 
    231 void SharedMemory::Lock() {
    232   Lock(INFINITE, NULL);
    233 }
    234 
    235 bool SharedMemory::Lock(uint32 timeout_ms, SECURITY_ATTRIBUTES* sec_attr) {
    236   if (lock_ == NULL) {
    237     std::wstring name = name_;
    238     name.append(L"lock");
    239     lock_ = CreateMutex(sec_attr, FALSE, name.c_str());
    240     if (lock_ == NULL) {
    241       DPLOG(ERROR) << "Could not create mutex.";
    242       return false;  // there is nothing good we can do here.
    243     }
    244   }
    245   DWORD result = WaitForSingleObject(lock_, timeout_ms);
    246 
    247   // Return false for WAIT_ABANDONED, WAIT_TIMEOUT or WAIT_FAILED.
    248   return (result == WAIT_OBJECT_0);
    249 }
    250 
    251 void SharedMemory::Unlock() {
    252   DCHECK(lock_ != NULL);
    253   ReleaseMutex(lock_);
    254 }
    255 
    256 SharedMemoryHandle SharedMemory::handle() const {
    257   return mapped_file_;
    258 }
    259 
    260 }  // namespace base
    261