blob: 6a500ef1ed67523190576dbbc8d4277e4d891614 [file] [log] [blame]
Dmitriy Ivanovcf1cbbe2015-10-19 16:57:46 -07001/*
2 * Copyright (C) 2015 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 "linker_mapped_file_fragment.h"
18#include "linker_debug.h"
19
20#include <inttypes.h>
21#include <stdlib.h>
22#include <sys/mman.h>
23#include <unistd.h>
24
25constexpr off64_t kPageMask = ~static_cast<off64_t>(PAGE_SIZE-1);
26
27static off64_t page_start(off64_t offset) {
28 return offset & kPageMask;
29}
30
31static bool safe_add(off64_t* out, off64_t a, size_t b) {
32 CHECK(a >= 0);
33 if (static_cast<uint64_t>(INT64_MAX - a) < b) {
34 return false;
35 }
36
37 *out = a + b;
38 return true;
39}
40
41static size_t page_offset(off64_t offset) {
42 return static_cast<size_t>(offset & (PAGE_SIZE-1));
43}
44
45MappedFileFragment::MappedFileFragment() : map_start_(nullptr), map_size_(0),
46 data_(nullptr), size_ (0)
47{ }
48
49MappedFileFragment::~MappedFileFragment() {
50 if (map_start_ != nullptr) {
51 munmap(map_start_, map_size_);
52 }
53}
54
55bool MappedFileFragment::Map(int fd, off64_t base_offset, size_t elf_offset, size_t size) {
56 off64_t offset;
57 CHECK(safe_add(&offset, base_offset, elf_offset));
58
59 off64_t page_min = page_start(offset);
60 off64_t end_offset;
61
62 CHECK(safe_add(&end_offset, offset, size));
63 CHECK(safe_add(&end_offset, end_offset, page_offset(offset)));
64
65 size_t map_size = static_cast<size_t>(end_offset - page_min);
66 CHECK(map_size >= size);
67
68 uint8_t* map_start = static_cast<uint8_t*>(
69 mmap64(nullptr, map_size, PROT_READ, MAP_PRIVATE, fd, page_min));
70
71 if (map_start == MAP_FAILED) {
72 return false;
73 }
74
75 map_start_ = map_start;
76 map_size_ = map_size;
77
78 data_ = map_start + page_offset(offset);
79 size_ = size;
80
81 return true;
82}