xref: /aosp_15_r20/external/cronet/base/memory/platform_shared_memory_mapper_posix.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   void* address =
20       mmap(nullptr, size, PROT_READ | (write_allowed ? PROT_WRITE : 0),
21            MAP_SHARED, handle.fd, checked_cast<off_t>(offset));
22 
23   if (address == MAP_FAILED) {
24     DPLOG(ERROR) << "mmap " << handle.fd << " failed";
25     return std::nullopt;
26   }
27 
28   return make_span(static_cast<uint8_t*>(address), size);
29 }
30 
Unmap(span<uint8_t> mapping)31 void PlatformSharedMemoryMapper::Unmap(span<uint8_t> mapping) {
32   if (munmap(mapping.data(), mapping.size()) < 0)
33     DPLOG(ERROR) << "munmap";
34 }
35 
36 }  // namespace base
37