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 #include "berberis/base/page_size.h"
27
28 namespace {
29
30 const off64_t kPageMask = ~static_cast<off64_t>(berberis::kPageSize - 1);
31
page_start(off64_t offset)32 off64_t page_start(off64_t offset) {
33 return offset & kPageMask;
34 }
35
page_offset(off64_t offset)36 size_t page_offset(off64_t offset) {
37 return static_cast<size_t>(offset & (berberis::kPageSize - 1));
38 }
39
40 } // namespace
41
MappedFileFragment()42 MappedFileFragment::MappedFileFragment()
43 : map_start_(nullptr), map_size_(0), data_(nullptr), size_(0) {}
44
~MappedFileFragment()45 MappedFileFragment::~MappedFileFragment() {
46 if (map_start_ != nullptr) {
47 munmap(map_start_, map_size_);
48 }
49 }
50
Map(int fd,off64_t base_offset,size_t elf_offset,size_t size)51 bool MappedFileFragment::Map(int fd, off64_t base_offset, size_t elf_offset, size_t size) {
52 off64_t offset;
53 CHECK(!__builtin_add_overflow(base_offset, elf_offset, &offset));
54
55 off64_t page_min = page_start(offset);
56 off64_t end_offset;
57
58 CHECK(!__builtin_add_overflow(offset, size, &end_offset));
59 CHECK(!__builtin_add_overflow(end_offset, page_offset(offset), &end_offset));
60
61 size_t map_size = static_cast<size_t>(end_offset - page_min);
62 CHECK(map_size >= size);
63
64 uint8_t* map_start =
65 static_cast<uint8_t*>(mmap64(nullptr, map_size, PROT_READ, MAP_PRIVATE, fd, page_min));
66
67 if (map_start == MAP_FAILED) {
68 return false;
69 }
70
71 map_start_ = map_start;
72 map_size_ = map_size;
73
74 data_ = map_start + page_offset(offset);
75 size_ = size;
76
77 return true;
78 }
79