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 "base/logging.h"
8
9 #include <mach/vm_map.h>
10 #include "base/apple/mach_logging.h"
11
12 namespace base {
13
Map(subtle::PlatformSharedMemoryHandle handle,bool write_allowed,uint64_t offset,size_t size)14 absl::optional<span<uint8_t>> PlatformSharedMemoryMapper::Map(
15 subtle::PlatformSharedMemoryHandle handle,
16 bool write_allowed,
17 uint64_t offset,
18 size_t size) {
19 vm_prot_t vm_prot_write = write_allowed ? VM_PROT_WRITE : 0;
20 vm_address_t address = 0;
21 kern_return_t kr = vm_map(mach_task_self(),
22 &address, // Output parameter
23 size,
24 0, // Alignment mask
25 VM_FLAGS_ANYWHERE, handle, offset,
26 FALSE, // Copy
27 VM_PROT_READ | vm_prot_write, // Current protection
28 VM_PROT_READ | vm_prot_write, // Maximum protection
29 VM_INHERIT_NONE);
30 if (kr != KERN_SUCCESS) {
31 MACH_DLOG(ERROR, kr) << "vm_map";
32 return absl::nullopt;
33 }
34
35 return make_span(reinterpret_cast<uint8_t*>(address), size);
36 }
37
Unmap(span<uint8_t> mapping)38 void PlatformSharedMemoryMapper::Unmap(span<uint8_t> mapping) {
39 kern_return_t kr = vm_deallocate(
40 mach_task_self(), reinterpret_cast<vm_address_t>(mapping.data()),
41 mapping.size());
42 MACH_DLOG_IF(ERROR, kr != KERN_SUCCESS, kr) << "vm_deallocate";
43 }
44
45 } // namespace base
46