blob: 86aec382e68883115736c54b77535d38baf2358e [file] [log] [blame]
Primiano Tuccibbaa58c2017-12-20 13:48:20 +01001/*
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"
Anna Zapponebba19412018-01-24 16:38:18 +000022#include "perfetto/base/utils.h"
Primiano Tuccibbaa58c2017-12-20 13:48:20 +010023
24namespace perfetto {
25namespace base {
26
27namespace {
28
Florian Mayer22e4b392018-03-08 10:20:11 +000029constexpr size_t kGuardSize = kPageSize;
Primiano Tuccibbaa58c2017-12-20 13:48:20 +010030
31// static
32PageAllocator::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
49PageAllocator::Deleter::Deleter() : Deleter(0) {}
50PageAllocator::Deleter::Deleter(size_t size) : size_(size) {}
51
52void 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
63PageAllocator::UniquePtr PageAllocator::Allocate(size_t size) {
64 return AllocateInternal(size, false /*unchecked*/);
65}
66
67// static
68PageAllocator::UniquePtr PageAllocator::AllocateMayFail(size_t size) {
69 return AllocateInternal(size, true /*unchecked*/);
70}
71
72} // namespace base
73} // namespace perfetto