xref: /aosp_15_r20/external/cronet/base/files/memory_mapped_file.h (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 #ifndef BASE_FILES_MEMORY_MAPPED_FILE_H_
6 #define BASE_FILES_MEMORY_MAPPED_FILE_H_
7 
8 #include <stddef.h>
9 #include <stdint.h>
10 
11 #include <utility>
12 
13 #include "base/base_export.h"
14 #include "base/containers/span.h"
15 #include "base/files/file.h"
16 #include "base/memory/raw_ptr_exclusion.h"
17 #include "build/build_config.h"
18 
19 #if BUILDFLAG(IS_WIN)
20 #include "base/win/scoped_handle.h"
21 #endif
22 
23 namespace base {
24 
25 class FilePath;
26 
27 class BASE_EXPORT MemoryMappedFile {
28  public:
29   enum Access {
30     // Mapping a file into memory effectively allows for file I/O on any thread.
31     // The accessing thread could be paused while data from the file is paged
32     // into memory. Worse, a corrupted filesystem could cause a SEGV within the
33     // program instead of just an I/O error.
34     READ_ONLY,
35 
36     // This provides read/write access to a file and must be used with care of
37     // the additional subtleties involved in doing so. Though the OS will do
38     // the writing of data on its own time, too many dirty pages can cause
39     // the OS to pause the thread while it writes them out. The pause can
40     // be as much as 1s on some systems.
41     READ_WRITE,
42 
43     // This provides read/write access to the mapped file contents as above, but
44     // applies a copy-on-write policy such that no writes are carried through to
45     // the underlying file.
46     READ_WRITE_COPY,
47 
48     // This provides read/write access but with the ability to write beyond
49     // the end of the existing file up to a maximum size specified as the
50     // "region". Depending on the OS, the file may or may not be immediately
51     // extended to the maximum size though it won't be loaded in RAM until
52     // needed. Note, however, that the maximum size will still be reserved
53     // in the process address space.
54     READ_WRITE_EXTEND,
55 
56 #if BUILDFLAG(IS_WIN)
57     // This provides read access, but as executable code used for prefetching
58     // DLLs into RAM to avoid inefficient hard fault patterns such as during
59     // process startup. The accessing thread could be paused while data from
60     // the file is read into memory (if needed).
61     READ_CODE_IMAGE,
62 #endif
63   };
64 
65   // The default constructor sets all members to invalid/null values.
66   MemoryMappedFile();
67   MemoryMappedFile(const MemoryMappedFile&) = delete;
68   MemoryMappedFile& operator=(const MemoryMappedFile&) = delete;
69   ~MemoryMappedFile();
70 
71   // Used to hold information about a region [offset + size] of a file.
72   struct BASE_EXPORT Region {
73     static const Region kWholeFile;
74 
75     friend bool operator==(const Region&, const Region&) = default;
76 
77     // Start of the region (measured in bytes from the beginning of the file).
78     int64_t offset;
79 
80     // Length of the region in bytes.
81     size_t size;
82   };
83 
84   // Opens an existing file and maps it into memory. |access| can be read-only
85   // or read/write but not read/write+extend. If this object already points
86   // to a valid memory mapped file then this method will fail and return
87   // false. If it cannot open the file, the file does not exist, or the
88   // memory mapping fails, it will return false.
89   [[nodiscard]] bool Initialize(const FilePath& file_name, Access access);
Initialize(const FilePath & file_name)90   [[nodiscard]] bool Initialize(const FilePath& file_name) {
91     return Initialize(file_name, READ_ONLY);
92   }
93 
94   // As above, but works with an already-opened file. |access| can be read-only
95   // or read/write but not read/write+extend. MemoryMappedFile takes ownership
96   // of |file| and closes it when done. |file| must have been opened with
97   // permissions suitable for |access|. If the memory mapping fails, it will
98   // return false.
99   [[nodiscard]] bool Initialize(File file, Access access);
Initialize(File file)100   [[nodiscard]] bool Initialize(File file) {
101     return Initialize(std::move(file), READ_ONLY);
102   }
103 
104   // As above, but works with a region of an already-opened file. |access|
105   // must not be READ_CODE_IMAGE. If READ_WRITE_EXTEND is specified then
106   // |region| provides the maximum size of the file. If the memory mapping
107   // fails, it return false.
108   [[nodiscard]] bool Initialize(File file, const Region& region, Access access);
Initialize(File file,const Region & region)109   [[nodiscard]] bool Initialize(File file, const Region& region) {
110     return Initialize(std::move(file), region, READ_ONLY);
111   }
112 
data()113   const uint8_t* data() const { return bytes_.data(); }
data()114   uint8_t* data() { return bytes_.data(); }
length()115   size_t length() const { return bytes_.size(); }
116 
bytes()117   span<const uint8_t> bytes() const { return bytes_; }
mutable_bytes()118   span<uint8_t> mutable_bytes() { return bytes_; }
119 
120   // Is file_ a valid file handle that points to an open, memory mapped file?
121   bool IsValid() const;
122 
123  private:
124   // Given the arbitrarily aligned memory region [start, size], returns the
125   // boundaries of the region aligned to the granularity specified by the OS,
126   // (a page on Linux, ~32k on Windows) as follows:
127   // - |aligned_start| is page aligned and <= |start|.
128   // - |aligned_size| is a multiple of the VM granularity and >= |size|.
129   // - |offset| is the displacement of |start| w.r.t |aligned_start|.
130   static void CalculateVMAlignedBoundaries(int64_t start,
131                                            size_t size,
132                                            int64_t* aligned_start,
133                                            size_t* aligned_size,
134                                            int32_t* offset);
135 
136 #if BUILDFLAG(IS_WIN)
137   // Maps the executable file to memory, point `bytes_` to the memory range.
138   // Return true on success.
139   bool MapImageToMemory(Access access);
140 #endif
141 
142   // Map the file to memory, point `bytes_` to that memory address. Return true
143   // on success, false on any kind of failure. This is a helper for
144   // Initialize().
145   bool MapFileRegionToMemory(const Region& region, Access access);
146 
147   // Closes all open handles.
148   void CloseHandles();
149 
150   File file_;
151 
152   // RAW_PTR_EXCLUSION: Never allocated by PartitionAlloc (always mmap'ed), so
153   // there is no benefit to using a raw_span, only cost.
154   RAW_PTR_EXCLUSION span<uint8_t> bytes_;
155 
156 #if BUILDFLAG(IS_WIN)
157   win::ScopedHandle file_mapping_;
158 #endif
159 };
160 
161 }  // namespace base
162 
163 #endif  // BASE_FILES_MEMORY_MAPPED_FILE_H_
164