xref: /aosp_15_r20/external/cronet/base/files/memory_mapped_file_posix.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2013 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/files/memory_mapped_file.h"
6 
7 #include <fcntl.h>
8 #include <stddef.h>
9 #include <stdint.h>
10 #include <sys/mman.h>
11 #include <sys/stat.h>
12 #include <unistd.h>
13 
14 #include "base/files/file_util.h"
15 #include "base/logging.h"
16 #include "base/numerics/safe_conversions.h"
17 #include "base/threading/scoped_blocking_call.h"
18 #include "build/build_config.h"
19 
20 namespace base {
21 
22 MemoryMappedFile::MemoryMappedFile() = default;
23 
24 #if !BUILDFLAG(IS_NACL)
MapFileRegionToMemory(const MemoryMappedFile::Region & region,Access access)25 bool MemoryMappedFile::MapFileRegionToMemory(
26     const MemoryMappedFile::Region& region,
27     Access access) {
28   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
29 
30   off_t map_start = 0;
31   size_t map_size = 0u;
32   int32_t data_offset = 0;
33   size_t byte_size = 0u;
34 
35   if (region == MemoryMappedFile::Region::kWholeFile) {
36     int64_t file_len = file_.GetLength();
37     if (file_len < 0) {
38       DPLOG(ERROR) << "fstat " << file_.GetPlatformFile();
39       return false;
40     }
41     if (!IsValueInRangeForNumericType<size_t>(file_len))
42       return false;
43     map_size = base::checked_cast<size_t>(file_len);
44     byte_size = map_size;
45   } else {
46     // The region can be arbitrarily aligned. mmap, instead, requires both the
47     // start and size to be page-aligned. Hence, we map here the page-aligned
48     // outer region [|aligned_start|, |aligned_start| + |size|] which contains
49     // |region| and then add up the |data_offset| displacement.
50     int64_t aligned_start = 0;
51     size_t aligned_size = 0u;
52     CalculateVMAlignedBoundaries(region.offset,
53                                  region.size,
54                                  &aligned_start,
55                                  &aligned_size,
56                                  &data_offset);
57 
58     // Ensure that the casts in the mmap call below are sane.
59     if (aligned_start < 0 ||
60         !IsValueInRangeForNumericType<off_t>(aligned_start)) {
61       DLOG(ERROR) << "Region bounds are not valid for mmap";
62       return false;
63     }
64 
65     map_start = base::checked_cast<off_t>(aligned_start);
66     map_size = aligned_size;
67     byte_size = region.size;
68   }
69 
70   if (map_size == 0u) {
71     // mmap() requires `map_size > 0`, and this ensures an empty span indicates
72     // invalid.
73     return false;
74   }
75 
76   int prot = 0;
77   int flags = MAP_SHARED;
78   switch (access) {
79     case READ_ONLY:
80       prot |= PROT_READ;
81       break;
82 
83     case READ_WRITE:
84       prot |= PROT_READ | PROT_WRITE;
85       break;
86 
87     case READ_WRITE_COPY:
88       prot |= PROT_READ | PROT_WRITE;
89       flags = MAP_PRIVATE;
90       break;
91 
92     case READ_WRITE_EXTEND:
93       prot |= PROT_READ | PROT_WRITE;
94 
95       if (!AllocateFileRegion(&file_, region.offset, region.size))
96         return false;
97 
98       break;
99   }
100 
101   auto* ptr = static_cast<uint8_t*>(
102       mmap(nullptr, map_size, prot, flags, file_.GetPlatformFile(), map_start));
103   if (ptr == MAP_FAILED) {
104     DPLOG(ERROR) << "mmap " << file_.GetPlatformFile();
105     return false;
106   }
107 
108   // SAFETY: For the span construction to be valid, `ptr` needs to point to at
109   // least `map_size` many bytes, which is the guarantee of mmap() when it
110   // returns a valid pointer, and that `data_offset + byte_size <= map_size`.
111   //
112   // If the mapping is of the whole file, `map_size == byte_size`
113   // and `data_offset == 0`, so `data_offset + byte_size <= map_size` is
114   // trivially satisfied.
115   //
116   // If the mapping is a sub-range of the file:
117   // - `aligned_start` is page aligned and <= `start`.
118   // - `map_size` is a multiple of the VM granularity and >=
119   //   `byte_size`.
120   // - `data_offset` is the displacement of `start` w.r.t `aligned_start`.
121   // |..................|xxxxxxxxxxxxxxxxxx|.................|
122   // ^ aligned start    ^ start            |                 |
123   // ^------------------^ data_offset      |                 |
124   //                    ^------------------^ byte_size       |
125   // ^-------------------------------------------------------^ map_size
126   //
127   // The `data_offset` undoes the alignment of start. The `map_size` contains
128   // the padding before and after the mapped region to satisfy alignment. So
129   // the `data_offset + byte_size <= map_size`.
130   bytes_ = UNSAFE_BUFFERS(base::span(ptr + data_offset, byte_size));
131   return true;
132 }
133 #endif
134 
CloseHandles()135 void MemoryMappedFile::CloseHandles() {
136   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
137 
138   if (!bytes_.empty()) {
139     munmap(bytes_.data(), bytes_.size());
140   }
141   file_.Close();
142   bytes_ = base::span<uint8_t>();
143 }
144 
145 }  // namespace base
146