1 /*
2 * Copyright (C) 2017 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 "perfetto/base/page_allocator.h"
18
19 #include <sys/mman.h>
20
21 #include "perfetto/base/logging.h"
22 #include "perfetto/base/utils.h"
23
24 namespace perfetto {
25 namespace base {
26
27 namespace {
28
29 constexpr size_t kGuardSize = kPageSize;
30
31 // static
AllocateInternal(size_t size,bool unchecked)32 PageAllocator::UniquePtr AllocateInternal(size_t size, bool unchecked) {
33 PERFETTO_DCHECK(size % kPageSize == 0);
34 size_t outer_size = size + kGuardSize * 2;
35 void* ptr = mmap(nullptr, outer_size, PROT_READ | PROT_WRITE,
36 MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
37 if (ptr == MAP_FAILED && unchecked)
38 return nullptr;
39 PERFETTO_CHECK(ptr && ptr != MAP_FAILED);
40 char* usable_region = reinterpret_cast<char*>(ptr) + kGuardSize;
41 int res = mprotect(ptr, kGuardSize, PROT_NONE);
42 res |= mprotect(usable_region + size, kGuardSize, PROT_NONE);
43 PERFETTO_CHECK(res == 0);
44 return PageAllocator::UniquePtr(usable_region, PageAllocator::Deleter(size));
45 }
46
47 } // namespace
48
Deleter()49 PageAllocator::Deleter::Deleter() : Deleter(0) {}
Deleter(size_t size)50 PageAllocator::Deleter::Deleter(size_t size) : size_(size) {}
51
operator ()(void * ptr) const52 void PageAllocator::Deleter::operator()(void* ptr) const {
53 if (!ptr)
54 return;
55 PERFETTO_CHECK(size_);
56 char* start = reinterpret_cast<char*>(ptr) - kGuardSize;
57 const size_t outer_size = size_ + kGuardSize * 2;
58 int res = munmap(start, outer_size);
59 PERFETTO_CHECK(res == 0);
60 }
61
62 // static
Allocate(size_t size)63 PageAllocator::UniquePtr PageAllocator::Allocate(size_t size) {
64 return AllocateInternal(size, false /*unchecked*/);
65 }
66
67 // static
AllocateMayFail(size_t size)68 PageAllocator::UniquePtr PageAllocator::AllocateMayFail(size_t size) {
69 return AllocateInternal(size, true /*unchecked*/);
70 }
71
72 } // namespace base
73 } // namespace perfetto
74