1 /* 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 #include "linker_utils.h" 20 21 #include <inttypes.h> 22 #include <stdlib.h> 23 #include <sys/mman.h> 24 #include <unistd.h> 25 26 MappedFileFragment::MappedFileFragment() : map_start_(nullptr), map_size_(0), 27 data_(nullptr), size_ (0) 28 { } 29 30 MappedFileFragment::~MappedFileFragment() { 31 if (map_start_ != nullptr) { 32 munmap(map_start_, map_size_); 33 } 34 } 35 36 bool MappedFileFragment::Map(int fd, off64_t base_offset, size_t elf_offset, size_t size) { 37 off64_t offset; 38 CHECK(safe_add(&offset, base_offset, elf_offset)); 39 40 off64_t page_min = page_start(offset); 41 off64_t end_offset; 42 43 CHECK(safe_add(&end_offset, offset, size)); 44 CHECK(safe_add(&end_offset, end_offset, page_offset(offset))); 45 46 size_t map_size = static_cast<size_t>(end_offset - page_min); 47 CHECK(map_size >= size); 48 49 uint8_t* map_start = static_cast<uint8_t*>( 50 mmap64(nullptr, map_size, PROT_READ, MAP_PRIVATE, fd, page_min)); 51 52 if (map_start == MAP_FAILED) { 53 return false; 54 } 55 56 map_start_ = map_start; 57 map_size_ = map_size; 58 59 data_ = map_start + page_offset(offset); 60 size_ = size; 61 62 return true; 63 } 64