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 <stddef.h> 8 #include <sys/mman.h> 9 10 #include "base/logging.h" 11 #include "third_party/ashmem/ashmem.h" 12 13 namespace base { 14 15 // For Android, we use ashmem to implement SharedMemory. ashmem_create_region 16 // will automatically pin the region. We never explicitly call pin/unpin. When 17 // all the file descriptors from different processes associated with the region 18 // are closed, the memory buffer will go away. 19 Create(const SharedMemoryCreateOptions & options)20bool SharedMemory::Create(const SharedMemoryCreateOptions& options) { 21 DCHECK(!shm_.IsValid()); 22 23 if (options.size > static_cast<size_t>(std::numeric_limits<int>::max())) 24 return false; 25 26 // "name" is just a label in ashmem. It is visible in /proc/pid/maps. 27 int fd = ashmem_create_region( 28 options.name_deprecated ? options.name_deprecated->c_str() : "", 29 options.size); 30 shm_ = SharedMemoryHandle::ImportHandle(fd, options.size); 31 if (!shm_.IsValid()) { 32 DLOG(ERROR) << "Shared memory creation failed"; 33 return false; 34 } 35 36 int flags = PROT_READ | PROT_WRITE | (options.executable ? PROT_EXEC : 0); 37 int err = ashmem_set_prot_region(shm_.GetHandle(), flags); 38 if (err < 0) { 39 DLOG(ERROR) << "Error " << err << " when setting protection of ashmem"; 40 return false; 41 } 42 43 requested_size_ = options.size; 44 45 return true; 46 } 47 Delete(const std::string & name)48bool SharedMemory::Delete(const std::string& name) { 49 // Like on Windows, this is intentionally returning true as ashmem will 50 // automatically releases the resource when all FDs on it are closed. 51 return true; 52 } 53 Open(const std::string & name,bool read_only)54bool SharedMemory::Open(const std::string& name, bool read_only) { 55 // ashmem doesn't support name mapping 56 NOTIMPLEMENTED(); 57 return false; 58 } 59 Close()60void SharedMemory::Close() { 61 if (shm_.IsValid()) { 62 shm_.Close(); 63 shm_ = SharedMemoryHandle(); 64 } 65 } 66 GetReadOnlyHandle() const67SharedMemoryHandle SharedMemory::GetReadOnlyHandle() const { 68 // There are no read-only Ashmem descriptors on Android. 69 // Instead, the protection mask is a property of the region itself. 70 SharedMemoryHandle handle = shm_.Duplicate(); 71 handle.SetReadOnly(); 72 return handle; 73 } 74 75 } // namespace base 76