1/* 2 * Copyright 2011, 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 "MemChunk.h" 18 19#include "utils/flush_cpu_cache.h" 20#include "utils/helper.h" 21 22#include <llvm/Support/raw_ostream.h> 23 24#include <sys/mman.h> 25 26#include <stdlib.h> 27 28#ifndef MAP_32BIT 29#define MAP_32BIT 0 30// Note: If the <sys/mman.h> does not come with MAP_32BIT, then we 31// define it as zero, so that it won't manipulate the flags. 32#endif 33 34#if USE_FIXED_ADDR_MEM_CHUNK 35static uintptr_t StartAddr = 0x7e000000UL; 36#endif 37 38MemChunk::MemChunk() : buf((unsigned char *)MAP_FAILED), buf_size(0) { 39} 40 41MemChunk::~MemChunk() { 42 if (buf != MAP_FAILED) { 43 munmap(buf, buf_size); 44 } 45} 46 47bool MemChunk::allocate(size_t size) { 48#if USE_FIXED_ADDR_MEM_CHUNK 49 buf = (unsigned char *)mmap((void *)StartAddr, size, 50 PROT_READ | PROT_WRITE, 51 MAP_PRIVATE | MAP_ANON | MAP_32BIT, 52 -1, 0); 53#else 54 buf = (unsigned char *)mmap(0, size, 55 PROT_READ | PROT_WRITE, 56 MAP_PRIVATE | MAP_ANON | MAP_32BIT, 57 -1, 0); 58#endif 59 60 if (buf == MAP_FAILED) { 61 return false; 62 } 63 64#if USE_FIXED_ADDR_MEM_CHUNK 65 StartAddr += (size + 4095) / 4096 * 4096; 66#endif 67 68 buf_size = size; 69 return true; 70} 71 72void MemChunk::print() const { 73 if (buf != MAP_FAILED) { 74 dump_hex(buf, buf_size, 0, buf_size); 75 } 76} 77 78bool MemChunk::protect(int prot) { 79 if (buf_size > 0) { 80 int ret = mprotect((void *)buf, buf_size, prot); 81 if (ret == -1) { 82 llvm::errs() << "Error: Can't mprotect.\n"; 83 return false; 84 } 85 86 if (prot & PROT_EXEC) { 87 FLUSH_CPU_CACHE(buf, buf + buf_size); 88 } 89 } 90 91 return true; 92} 93