1 // Copyright 2022 The Chromium Authors
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/platform_shared_memory_mapper.h"
6
7 #include <mach/vm_map.h>
8
9 #include "base/apple/mach_logging.h"
10 #include "base/containers/span.h"
11 #include "base/logging.h"
12
13 namespace base {
14
Map(subtle::PlatformSharedMemoryHandle handle,bool write_allowed,uint64_t offset,size_t size)15 std::optional<span<uint8_t>> PlatformSharedMemoryMapper::Map(
16 subtle::PlatformSharedMemoryHandle handle,
17 bool write_allowed,
18 uint64_t offset,
19 size_t size) {
20 vm_prot_t vm_prot_write = write_allowed ? VM_PROT_WRITE : 0;
21 vm_address_t address = 0;
22 kern_return_t kr = vm_map(mach_task_self(),
23 &address, // Output parameter
24 size,
25 0, // Alignment mask
26 VM_FLAGS_ANYWHERE, handle, offset,
27 FALSE, // Copy
28 VM_PROT_READ | vm_prot_write, // Current protection
29 VM_PROT_READ | vm_prot_write, // Maximum protection
30 VM_INHERIT_NONE);
31 if (kr != KERN_SUCCESS) {
32 MACH_DLOG(ERROR, kr) << "vm_map";
33 return std::nullopt;
34 }
35
36 // SAFETY: vm_map() maps a memory segment of `size` bytes. Since
37 // `VM_FLAGS_ANYWHERE` is used, the address will be chosen by vm_map() and
38 // returned in `address`.
39 return UNSAFE_BUFFERS(base::span(reinterpret_cast<uint8_t*>(address), size));
40 }
41
Unmap(span<uint8_t> mapping)42 void PlatformSharedMemoryMapper::Unmap(span<uint8_t> mapping) {
43 kern_return_t kr = vm_deallocate(
44 mach_task_self(), reinterpret_cast<vm_address_t>(mapping.data()),
45 mapping.size());
46 MACH_DLOG_IF(ERROR, kr != KERN_SUCCESS, kr) << "vm_deallocate";
47 }
48
49 } // namespace base
50