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 <stddef.h>
8 #include <stdint.h>
9 #include <sys/mman.h>
10 #include <sys/stat.h>
11 #include <unistd.h>
12
13 #include "base/logging.h"
14 #include "base/threading/thread_restrictions.h"
15 #include "build/build_config.h"
16
17 namespace base {
18
MemoryMappedFile()19 MemoryMappedFile::MemoryMappedFile() : data_(NULL), length_(0) {
20 }
21
22 #if !defined(OS_NACL)
MapFileRegionToMemory(const MemoryMappedFile::Region & region)23 bool MemoryMappedFile::MapFileRegionToMemory(
24 const MemoryMappedFile::Region& region) {
25 ThreadRestrictions::AssertIOAllowed();
26
27 off_t map_start = 0;
28 size_t map_size = 0;
29 int32_t data_offset = 0;
30
31 if (region == MemoryMappedFile::Region::kWholeFile) {
32 int64_t file_len = file_.GetLength();
33 if (file_len == -1) {
34 DPLOG(ERROR) << "fstat " << file_.GetPlatformFile();
35 return false;
36 }
37 map_size = static_cast<size_t>(file_len);
38 length_ = map_size;
39 } else {
40 // The region can be arbitrarily aligned. mmap, instead, requires both the
41 // start and size to be page-aligned. Hence, we map here the page-aligned
42 // outer region [|aligned_start|, |aligned_start| + |size|] which contains
43 // |region| and then add up the |data_offset| displacement.
44 int64_t aligned_start = 0;
45 int64_t aligned_size = 0;
46 CalculateVMAlignedBoundaries(region.offset,
47 region.size,
48 &aligned_start,
49 &aligned_size,
50 &data_offset);
51
52 // Ensure that the casts in the mmap call below are sane.
53 if (aligned_start < 0 || aligned_size < 0 ||
54 aligned_start > std::numeric_limits<off_t>::max() ||
55 static_cast<uint64_t>(aligned_size) >
56 std::numeric_limits<size_t>::max() ||
57 static_cast<uint64_t>(region.size) >
58 std::numeric_limits<size_t>::max()) {
59 DLOG(ERROR) << "Region bounds are not valid for mmap";
60 return false;
61 }
62
63 map_start = static_cast<off_t>(aligned_start);
64 map_size = static_cast<size_t>(aligned_size);
65 length_ = static_cast<size_t>(region.size);
66 }
67
68 data_ = static_cast<uint8_t*>(mmap(NULL, map_size, PROT_READ, MAP_SHARED,
69 file_.GetPlatformFile(), map_start));
70 if (data_ == MAP_FAILED) {
71 DPLOG(ERROR) << "mmap " << file_.GetPlatformFile();
72 return false;
73 }
74
75 data_ += data_offset;
76 return true;
77 }
78 #endif
79
CloseHandles()80 void MemoryMappedFile::CloseHandles() {
81 ThreadRestrictions::AssertIOAllowed();
82
83 if (data_ != NULL)
84 munmap(data_, length_);
85 file_.Close();
86
87 data_ = NULL;
88 length_ = 0;
89 }
90
91 } // namespace base
92