1 /*
2 * Copyright (C) 2016 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 BERBERIS_BASE_MMAP_H_
18 #define BERBERIS_BASE_MMAP_H_
19
20 #include <sys/mman.h>
21
22 #include <cstddef>
23
24 #include "berberis/base/bit_util.h"
25 #include "berberis/base/macros.h"
26
27 namespace berberis {
28
29 // TODO(b/232598137): make a runtime CHECK against sysconf(_SC_PAGE_SIZE)!
30 constexpr size_t kPageSizeLog2 = 12; // 4096
31 constexpr size_t kPageSize = 1 << kPageSizeLog2;
32
33 template <typename T>
AlignDownPageSize(T x)34 constexpr T AlignDownPageSize(T x) {
35 return AlignDown(x, kPageSize);
36 }
37
38 template <typename T>
AlignUpPageSize(T x)39 constexpr T AlignUpPageSize(T x) {
40 return AlignUp(x, kPageSize);
41 }
42
43 template <typename T>
IsAlignedPageSize(T x)44 constexpr bool IsAlignedPageSize(T x) {
45 return IsAligned(x, kPageSize);
46 }
47
48 struct MmapImplArgs {
49 void* addr = nullptr;
50 size_t size = 0;
51 int prot = PROT_READ | PROT_WRITE;
52 int flags = MAP_PRIVATE | MAP_ANONYMOUS;
53 int fd = -1;
54 off_t offset = 0;
55 };
56
57 void* MmapImpl(MmapImplArgs args);
58 void* MmapImplOrDie(MmapImplArgs args);
59
Mmap(size_t size)60 inline void* Mmap(size_t size) {
61 return MmapImpl({.size = size});
62 }
63
MmapOrDie(size_t size)64 inline void* MmapOrDie(size_t size) {
65 return MmapImplOrDie({.size = size});
66 }
67
68 void MunmapOrDie(void* ptr, size_t size);
69
70 void MprotectOrDie(void* ptr, size_t size, int prot);
71
72 class ScopedMmap {
73 public:
ScopedMmap()74 ScopedMmap() : data_(nullptr), size_(0) {}
ScopedMmap(size_t size)75 explicit ScopedMmap(size_t size) { Init(size); }
76
~ScopedMmap()77 ~ScopedMmap() {
78 if (size_) {
79 MunmapOrDie(data_, size_);
80 }
81 }
82
Init(size_t size)83 void Init(size_t size) {
84 size_ = AlignUpPageSize(size);
85 data_ = MmapOrDie(size_);
86 }
87
data()88 void* data() const { return data_; }
size()89 size_t size() const { return size_; }
90
91 private:
92 void* data_;
93 size_t size_;
94
95 DISALLOW_COPY_AND_ASSIGN(ScopedMmap);
96 };
97
98 } // namespace berberis
99
100 #endif // BERBERIS_BASE_MMAP_H_
101