xref: /aosp_15_r20/external/cronet/base/memory/platform_shared_memory_mapper_android.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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 #include "base/numerics/safe_conversions.h"
9 
10 #include <sys/mman.h>
11 
12 namespace base {
13 
Map(subtle::PlatformSharedMemoryHandle handle,bool write_allowed,uint64_t offset,size_t size)14 std::optional<span<uint8_t>> PlatformSharedMemoryMapper::Map(
15     subtle::PlatformSharedMemoryHandle handle,
16     bool write_allowed,
17     uint64_t offset,
18     size_t size) {
19   // IMPORTANT: Even if the mapping is readonly and the mapped data is not
20   // changing, the region must ALWAYS be mapped with MAP_SHARED, otherwise with
21   // ashmem the mapping is equivalent to a private anonymous mapping.
22   void* address =
23       mmap(nullptr, size, PROT_READ | (write_allowed ? PROT_WRITE : 0),
24            MAP_SHARED, handle, checked_cast<off_t>(offset));
25 
26   if (address == MAP_FAILED) {
27     DPLOG(ERROR) << "mmap " << handle << " failed";
28     return std::nullopt;
29   }
30 
31   return make_span(static_cast<uint8_t*>(address), size);
32 }
33 
Unmap(span<uint8_t> mapping)34 void PlatformSharedMemoryMapper::Unmap(span<uint8_t> mapping) {
35   if (munmap(mapping.data(), mapping.size()) < 0)
36     DPLOG(ERROR) << "munmap";
37 }
38 
39 }  // namespace base
40