• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "berberis/base/page_size.h"
27 
28 namespace berberis {
29 
30 template <typename T>
AlignDownPageSize(T x)31 constexpr T AlignDownPageSize(T x) {
32   return AlignDown(x, kPageSize);
33 }
34 
35 template <typename T>
AlignUpPageSize(T x)36 constexpr T AlignUpPageSize(T x) {
37   return AlignUp(x, kPageSize);
38 }
39 
40 template <typename T>
IsAlignedPageSize(T x)41 constexpr bool IsAlignedPageSize(T x) {
42   return IsAligned(x, kPageSize);
43 }
44 
45 struct MmapImplArgs {
46   void* addr = nullptr;
47   size_t size = 0;
48   int prot = PROT_READ | PROT_WRITE;
49   int flags = MAP_PRIVATE | MAP_ANONYMOUS;
50   int fd = -1;
51   off_t offset = 0;
52 };
53 
54 void* MmapImpl(MmapImplArgs args);
55 void* MmapImplOrDie(MmapImplArgs args);
56 
Mmap(size_t size)57 inline void* Mmap(size_t size) {
58   return MmapImpl({.size = size});
59 }
60 
MmapOrDie(size_t size)61 inline void* MmapOrDie(size_t size) {
62   return MmapImplOrDie({.size = size});
63 }
64 
65 void MunmapOrDie(void* ptr, size_t size);
66 
67 void MprotectOrDie(void* ptr, size_t size, int prot);
68 
69 class ScopedMmap {
70  public:
ScopedMmap()71   ScopedMmap() : data_(nullptr), size_(0) {}
ScopedMmap(size_t size)72   explicit ScopedMmap(size_t size) { Init(size); }
73 
~ScopedMmap()74   ~ScopedMmap() {
75     if (size_) {
76       MunmapOrDie(data_, size_);
77     }
78   }
79 
Init(size_t size)80   void Init(size_t size) {
81     size_ = AlignUpPageSize(size);
82     data_ = MmapOrDie(size_);
83   }
84 
data()85   void* data() const { return data_; }
size()86   size_t size() const { return size_; }
87 
88  private:
89   void* data_;
90   size_t size_;
91 
92   DISALLOW_COPY_AND_ASSIGN(ScopedMmap);
93 };
94 
95 }  // namespace berberis
96 
97 #endif  // BERBERIS_BASE_MMAP_H_
98