• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #ifndef MEM_CHUNK_H
18 #define MEM_CHUNK_H
19 
20 #include <stddef.h>
21 #include <stdint.h>
22 #include <stdlib.h>
23 
24 typedef void *(*AllocFunc) (size_t, uint32_t);
25 typedef void (*FreeFunc) (void *);
26 
27 class MemChunk {
28 private:
29   unsigned char *buf;
30   size_t buf_size;
31   bool bVendorBuf;
32 
33   static AllocFunc VendorAlloc;
34   static FreeFunc VendorFree;
35 
36   bool invalidBuf() const;
37 
38 public:
39   MemChunk();
40 
41   ~MemChunk();
42 
43   bool allocate(size_t size);
44 
45   void print() const;
46 
47   bool protect(int prot);
48 
getBuffer()49   unsigned char const *getBuffer() const {
50     return buf;
51   }
52 
getBuffer()53   unsigned char *getBuffer() {
54     return buf;
55   }
56 
57   unsigned char &operator[](size_t index) {
58     return buf[index];
59   }
60 
61   unsigned char const &operator[](size_t index) const {
62     return buf[index];
63   }
64 
size()65   size_t size() const {
66     return buf_size;
67   }
68 
69   // The allocation function must return page-aligned memory or we will be
70   // unable to mprotect the region appropriately.
registerAllocFreeCallbacks(AllocFunc a,FreeFunc f)71   static void registerAllocFreeCallbacks(AllocFunc a, FreeFunc f) {
72     VendorAlloc = a;
73     VendorFree = f;
74   }
75 };
76 
77 #endif // MEM_CHUNK_H
78