xref: /aosp_15_r20/external/cronet/base/files/memory_mapped_file_win.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 <windows.h>
8 
9 #include <stddef.h>
10 #include <stdint.h>
11 #include <winnt.h>
12 
13 #include <limits>
14 #include <string>
15 
16 #include "base/files/file_path.h"
17 #include "base/logging.h"
18 #include "base/numerics/checked_math.h"
19 #include "base/numerics/safe_conversions.h"
20 #include "base/threading/scoped_blocking_call.h"
21 #include "base/win/pe_image.h"
22 
23 namespace base {
24 
25 MemoryMappedFile::MemoryMappedFile() = default;
26 
MapImageToMemory(Access access)27 bool MemoryMappedFile::MapImageToMemory(Access access) {
28   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
29 
30   // The arguments to the calls of ::CreateFile(), ::CreateFileMapping(), and
31   // ::MapViewOfFile() need to be self consistent as far as access rights and
32   // type of mapping or one or more of them will fail in non-obvious ways.
33 
34   if (!file_.IsValid())
35     return false;
36 
37   file_mapping_.Set(::CreateFileMapping(file_.GetPlatformFile(), nullptr,
38                                         PAGE_READONLY | SEC_IMAGE_NO_EXECUTE, 0,
39                                         0, NULL));
40   if (!file_mapping_.is_valid())
41     return false;
42 
43   auto* ptr = static_cast<uint8_t*>(
44       ::MapViewOfFile(file_mapping_.get(), FILE_MAP_READ, 0, 0, 0));
45   if (!ptr) {
46     return false;
47   }
48 
49   // We need to know how large the mapped file is.
50   base::win::PEImage pe_image(ptr);
51   size_t len = pe_image.GetNTHeaders()->OptionalHeader.SizeOfImage;
52   if (len == 0u) {
53     // Consistent cross-platform behaviour, an empty `bytes_` indicates nothing
54     // is mapped.
55     return false;
56   }
57 
58   // SAFETY: The `len` is the size of the image at `ptr`.
59   bytes_ = UNSAFE_BUFFERS(base::span(ptr, len));
60   return true;
61 }
62 
MapFileRegionToMemory(const MemoryMappedFile::Region & region,Access access)63 bool MemoryMappedFile::MapFileRegionToMemory(
64     const MemoryMappedFile::Region& region,
65     Access access) {
66   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
67 
68   DCHECK(access != READ_CODE_IMAGE || region == Region::kWholeFile);
69 
70   if (!file_.IsValid())
71     return false;
72 
73   DWORD view_access;
74   DWORD flags = 0;
75   ULARGE_INTEGER size = {};
76   switch (access) {
77     case READ_ONLY:
78       flags |= PAGE_READONLY;
79       view_access = FILE_MAP_READ;
80       break;
81     case READ_WRITE:
82       flags |= PAGE_READWRITE;
83       view_access = FILE_MAP_WRITE;
84       break;
85     case READ_WRITE_COPY:
86       flags |= PAGE_WRITECOPY;
87       view_access = FILE_MAP_COPY;
88       break;
89     case READ_WRITE_EXTEND:
90       flags |= PAGE_READWRITE;
91       view_access = FILE_MAP_WRITE;
92       size.QuadPart = region.size;
93       break;
94     case READ_CODE_IMAGE:
95       return MapImageToMemory(access);
96   }
97 
98   file_mapping_.Set(::CreateFileMapping(file_.GetPlatformFile(), NULL, flags,
99                                         size.HighPart, size.LowPart, NULL));
100   if (!file_mapping_.is_valid())
101     return false;
102 
103   ULARGE_INTEGER map_start = {};
104   SIZE_T map_size = 0u;
105   int32_t data_offset = 0;
106   size_t byte_size = 0u;
107 
108   if (region == MemoryMappedFile::Region::kWholeFile) {
109     DCHECK_NE(READ_WRITE_EXTEND, access);
110     int64_t file_len = file_.GetLength();
111     if (file_len <= 0 || !IsValueInRangeForNumericType<size_t>(file_len)) {
112       return false;
113     }
114     byte_size = base::checked_cast<size_t>(file_len);
115   } else {
116     // The region can be arbitrarily aligned. MapViewOfFile, instead, requires
117     // that the start address is aligned to the VM granularity (which is
118     // typically larger than a page size, for instance 32k).
119     // Also, conversely to POSIX's mmap, the |map_size| doesn't have to be
120     // aligned and must be less than or equal the mapped file size.
121     // We map here the outer region [|aligned_start|, |aligned_start+size|]
122     // which contains |region| and then add up the |data_offset| displacement.
123     int64_t aligned_start = 0;
124     size_t ignored = 0u;
125     CalculateVMAlignedBoundaries(region.offset, region.size, &aligned_start,
126                                  &ignored, &data_offset);
127     base::CheckedNumeric<SIZE_T> full_map_size = region.size;
128     full_map_size += data_offset;
129 
130     // Ensure that the casts below in the MapViewOfFile call are sane.
131     if (aligned_start < 0 || !full_map_size.IsValid()) {
132       DLOG(ERROR) << "Region bounds are not valid for MapViewOfFile";
133       return false;
134     }
135     map_start.QuadPart = static_cast<uint64_t>(aligned_start);
136     map_size = full_map_size.ValueOrDie();
137     byte_size = region.size;
138 
139     if (map_size == 0u) {
140       // Consistent cross-platform behaviour, an empty `bytes_` indicates
141       // nothing is mapped.
142       return false;
143     }
144   }
145 
146   auto* ptr = static_cast<uint8_t*>(
147       ::MapViewOfFile(file_mapping_.get(), view_access, map_start.HighPart,
148                       map_start.LowPart, map_size));
149   if (ptr == nullptr) {
150     return false;
151   }
152 
153   // SAFETY: For the span construction to be valid, `ptr` needs to point to at
154   // least `data_size + byte_size` many bytes. The MapViewOfFile() will return a
155   // pointer of `map_size` bytes, unless it's 0 in which case it returns a
156   // pointer to all bytes in the file after the offset.
157   //
158   // If the mapping is of the whole file, `map_size == 0`, so `file_len` bytes
159   // are mapped. `byte_size == file_len` and `data_offset == 0`, so
160   // `data_offset + byte_size <= file_len` is trivially satisfied.
161   //
162   // If the mapping is a sub-range of the file, `map_size > 0` and `map_size`
163   // many bytes are mapped:
164   // - `aligned_start` is page aligned and <= `start`.
165   // - `map_size` is a multiple of the VM granularity and >=
166   //   `byte_size`.
167   // - `data_offset` is the displacement of `start` w.r.t `aligned_start`.
168   // |..................|xxxxxxxxxxxxxxxxxx|.................|
169   // ^ aligned start    ^ start            |                 |
170   // ^------------------^ data_offset      |                 |
171   //                    ^------------------^ byte_size       |
172   // ^-------------------------------------------------------^ map_size
173   //
174   // The `data_offset` undoes the alignment of start. The `map_size` contains
175   // the padding before and after the mapped region to satisfy alignment. So
176   // the `data_offset + byte_size <= map_size`.
177   bytes_ = UNSAFE_BUFFERS(base::span(ptr + data_offset, byte_size));
178   return true;
179 }
180 
CloseHandles()181 void MemoryMappedFile::CloseHandles() {
182   if (!bytes_.empty()) {
183     ::UnmapViewOfFile(bytes_.data());
184   }
185   if (file_mapping_.is_valid())
186     file_mapping_.Close();
187   if (file_.IsValid())
188     file_.Close();
189 
190   bytes_ = base::span<uint8_t>();
191 }
192 
193 }  // namespace base
194