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