platform_shared_memory_mapper_android.cc 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  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 "base/numerics/safe_conversions.h"
  7. #include <sys/mman.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. // IMPORTANT: Even if the mapping is readonly and the mapped data is not
  15. // changing, the region must ALWAYS be mapped with MAP_SHARED, otherwise with
  16. // ashmem the mapping is equivalent to a private anonymous mapping.
  17. void* address =
  18. mmap(nullptr, size, PROT_READ | (write_allowed ? PROT_WRITE : 0),
  19. MAP_SHARED, handle, checked_cast<off_t>(offset));
  20. if (address == MAP_FAILED) {
  21. DPLOG(ERROR) << "mmap " << handle << " failed";
  22. return absl::nullopt;
  23. }
  24. return make_span(reinterpret_cast<uint8_t*>(address), size);
  25. }
  26. void PlatformSharedMemoryMapper::Unmap(span<uint8_t> mapping) {
  27. if (munmap(mapping.data(), mapping.size()) < 0)
  28. DPLOG(ERROR) << "munmap";
  29. }
  30. } // namespace base