• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2013 The Chromium Authors. All rights reserved.
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/logging.h"
15 #include "base/numerics/safe_conversions.h"
16 #include "base/threading/thread_restrictions.h"
17 #include "build/build_config.h"
18 
19 #if defined(OS_ANDROID)
20 #include <android/api-level.h>
21 #endif
22 
23 namespace base {
24 
MemoryMappedFile()25 MemoryMappedFile::MemoryMappedFile() : data_(nullptr), length_(0) {}
26 
27 #if !defined(OS_NACL)
MapFileRegionToMemory(const MemoryMappedFile::Region & region,Access access)28 bool MemoryMappedFile::MapFileRegionToMemory(
29     const MemoryMappedFile::Region& region,
30     Access access) {
31   AssertBlockingAllowed();
32 
33   off_t map_start = 0;
34   size_t map_size = 0;
35   int32_t data_offset = 0;
36 
37   if (region == MemoryMappedFile::Region::kWholeFile) {
38     int64_t file_len = file_.GetLength();
39     if (file_len < 0) {
40       DPLOG(ERROR) << "fstat " << file_.GetPlatformFile();
41       return false;
42     }
43     if (!IsValueInRangeForNumericType<size_t>(file_len))
44       return false;
45     map_size = static_cast<size_t>(file_len);
46     length_ = map_size;
47   } else {
48     // The region can be arbitrarily aligned. mmap, instead, requires both the
49     // start and size to be page-aligned. Hence, we map here the page-aligned
50     // outer region [|aligned_start|, |aligned_start| + |size|] which contains
51     // |region| and then add up the |data_offset| displacement.
52     int64_t aligned_start = 0;
53     size_t aligned_size = 0;
54     CalculateVMAlignedBoundaries(region.offset,
55                                  region.size,
56                                  &aligned_start,
57                                  &aligned_size,
58                                  &data_offset);
59 
60     // Ensure that the casts in the mmap call below are sane.
61     if (aligned_start < 0 ||
62         !IsValueInRangeForNumericType<off_t>(aligned_start)) {
63       DLOG(ERROR) << "Region bounds are not valid for mmap";
64       return false;
65     }
66 
67     map_start = static_cast<off_t>(aligned_start);
68     map_size = aligned_size;
69     length_ = region.size;
70   }
71 
72   int flags = 0;
73   switch (access) {
74     case READ_ONLY:
75       flags |= PROT_READ;
76       break;
77 
78     case READ_WRITE:
79       flags |= PROT_READ | PROT_WRITE;
80       break;
81 
82     case READ_WRITE_EXTEND:
83       flags |= PROT_READ | PROT_WRITE;
84 
85       const int64_t new_file_len = region.offset + region.size;
86 
87       // POSIX won't auto-extend the file when it is written so it must first
88       // be explicitly extended to the maximum size. Zeros will fill the new
89       // space. It is assumed that the existing file is fully realized as
90       // otherwise the entire file would have to be read and possibly written.
91       const int64_t original_file_len = file_.GetLength();
92       if (original_file_len < 0) {
93         DPLOG(ERROR) << "fstat " << file_.GetPlatformFile();
94         return false;
95       }
96 
97       // Increase the actual length of the file, if necessary. This can fail if
98       // the disk is full and the OS doesn't support sparse files.
99       if (!file_.SetLength(std::max(original_file_len, new_file_len))) {
100         DPLOG(ERROR) << "ftruncate " << file_.GetPlatformFile();
101         return false;
102       }
103 
104       // Realize the extent of the file so that it can't fail (and crash) later
105       // when trying to write to a memory page that can't be created. This can
106       // fail if the disk is full and the file is sparse.
107       bool do_manual_extension = false;
108 
109 #if defined(OS_ANDROID) && __ANDROID_API__ < 21
110       // Only Android API>=21 supports the fallocate call. Older versions need
111       // to manually extend the file by writing zeros at block intervals.
112       do_manual_extension = true;
113 #elif defined(OS_MACOSX)
114       // MacOS doesn't support fallocate even though their new APFS filesystem
115       // does support sparse files. It does, however, have the functionality
116       // available via fcntl.
117       // See also: https://openradar.appspot.com/32720223
118       fstore_t params = {F_ALLOCATEALL, F_PEOFPOSMODE, region.offset,
119                          region.size, 0};
120       if (fcntl(file_.GetPlatformFile(), F_PREALLOCATE, &params) != 0) {
121         DPLOG(ERROR) << "F_PREALLOCATE";
122         // This can fail because the filesystem doesn't support it so don't
123         // give up just yet. Try the manual method below.
124         do_manual_extension = true;
125       }
126 #else
127       if (posix_fallocate(file_.GetPlatformFile(), region.offset,
128                           region.size) != 0) {
129         DPLOG(ERROR) << "posix_fallocate";
130         // This can fail because the filesystem doesn't support it so don't
131         // give up just yet. Try the manual method below.
132         do_manual_extension = true;
133       }
134 #endif
135 
136       // Manually realize the extended file by writing bytes to it at intervals.
137       if (do_manual_extension) {
138         int64_t block_size = 512;  // Start with something safe.
139         struct stat statbuf;
140         if (fstat(file_.GetPlatformFile(), &statbuf) == 0 &&
141             statbuf.st_blksize > 0) {
142           block_size = statbuf.st_blksize;
143         }
144 
145         // Write starting at the next block boundary after the old file length.
146         const int64_t extension_start =
147             (original_file_len + block_size - 1) & ~(block_size - 1);
148         for (int64_t i = extension_start; i < new_file_len; i += block_size) {
149           char existing_byte;
150           if (pread(file_.GetPlatformFile(), &existing_byte, 1, i) != 1)
151             return false;  // Can't read? Not viable.
152           if (existing_byte != 0)
153             continue;  // Block has data so must already exist.
154           if (pwrite(file_.GetPlatformFile(), &existing_byte, 1, i) != 1)
155             return false;  // Can't write? Not viable.
156         }
157       }
158 
159       break;
160   }
161 
162   data_ = static_cast<uint8_t*>(mmap(nullptr, map_size, flags, MAP_SHARED,
163                                      file_.GetPlatformFile(), map_start));
164   if (data_ == MAP_FAILED) {
165     DPLOG(ERROR) << "mmap " << file_.GetPlatformFile();
166     return false;
167   }
168 
169   data_ += data_offset;
170   return true;
171 }
172 #endif
173 
CloseHandles()174 void MemoryMappedFile::CloseHandles() {
175   AssertBlockingAllowed();
176 
177   if (data_ != nullptr)
178     munmap(data_, length_);
179   file_.Close();
180 
181   data_ = nullptr;
182   length_ = 0;
183 }
184 
185 }  // namespace base
186