1 /*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "berberis/base/mapped_file_fragment.h"
18
19 #include <inttypes.h>
20 #include <stdlib.h>
21 #include <sys/mman.h>
22 #include <sys/user.h>
23 #include <unistd.h>
24
25 #include "berberis/base/checks.h"
26
27 namespace {
28
29 const off64_t kPageMask = ~static_cast<off64_t>(PAGE_SIZE - 1);
30
page_start(off64_t offset)31 off64_t page_start(off64_t offset) {
32 return offset & kPageMask;
33 }
34
page_offset(off64_t offset)35 size_t page_offset(off64_t offset) {
36 return static_cast<size_t>(offset & (PAGE_SIZE - 1));
37 }
38
39 } // namespace
40
MappedFileFragment()41 MappedFileFragment::MappedFileFragment()
42 : map_start_(nullptr), map_size_(0), data_(nullptr), size_(0) {}
43
~MappedFileFragment()44 MappedFileFragment::~MappedFileFragment() {
45 if (map_start_ != nullptr) {
46 munmap(map_start_, map_size_);
47 }
48 }
49
Map(int fd,off64_t base_offset,size_t elf_offset,size_t size)50 bool MappedFileFragment::Map(int fd, off64_t base_offset, size_t elf_offset, size_t size) {
51 off64_t offset;
52 CHECK(!__builtin_add_overflow(base_offset, elf_offset, &offset));
53
54 off64_t page_min = page_start(offset);
55 off64_t end_offset;
56
57 CHECK(!__builtin_add_overflow(offset, size, &end_offset));
58 CHECK(!__builtin_add_overflow(end_offset, page_offset(offset), &end_offset));
59
60 size_t map_size = static_cast<size_t>(end_offset - page_min);
61 CHECK(map_size >= size);
62
63 uint8_t* map_start =
64 static_cast<uint8_t*>(mmap64(nullptr, map_size, PROT_READ, MAP_PRIVATE, fd, page_min));
65
66 if (map_start == MAP_FAILED) {
67 return false;
68 }
69
70 map_start_ = map_start;
71 map_size_ = map_size;
72
73 data_ = map_start + page_offset(offset);
74 size_ = size;
75
76 return true;
77 }
78