platform_shared_memory_mapper_mac.cc 1.5 KB

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