MemChunk.cpp revision b9aad104e835c4124d62ca6b31886bfd7a362216
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
34static uintptr_t StartAddr = 0x7e000000UL;
35
36MemChunk::MemChunk() : buf((unsigned char *)MAP_FAILED), buf_size(0) {
37}
38
39MemChunk::~MemChunk() {
40  if (buf != MAP_FAILED) {
41    munmap(buf, buf_size);
42  }
43}
44
45bool MemChunk::allocate(size_t size) {
46  buf = (unsigned char *)mmap((void *)StartAddr, size, PROT_READ | PROT_WRITE,
47                              MAP_PRIVATE | MAP_ANONYMOUS | MAP_32BIT,
48                              -1, 0);
49
50  if (buf == MAP_FAILED) {
51    return false;
52  }
53
54  StartAddr += (size + 4095) / 4096 * 4096;
55
56  buf_size = size;
57  return true;
58}
59
60void MemChunk::print() const {
61  if (buf != MAP_FAILED) {
62    dump_hex(buf, buf_size, 0, buf_size);
63  }
64}
65
66bool MemChunk::protect(int prot) {
67  if (buf_size > 0) {
68    int ret = mprotect((void *)buf, buf_size, prot);
69    if (ret == -1) {
70      llvm::errs() << "Error: Can't mprotect.\n";
71      return false;
72    }
73
74    if (prot & PROT_EXEC) {
75      FLUSH_CPU_CACHE(buf, buf + buf_size);
76    }
77  }
78
79  return true;
80}
81