-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathallocate.h
More file actions
51 lines (40 loc) · 1.19 KB
/
allocate.h
File metadata and controls
51 lines (40 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// SPDX-FileCopyrightText: Steven Ward
// SPDX-License-Identifier: MPL-2.0
/// Allocate private, anonymous memory using \c mmap
/**
* \file
* \author Steven Ward
* \sa https://man7.org/linux/man-pages/man2/mmap.2.html
* \sa https://man7.org/linux/man-pages/man2/madvise.2.html
* \sa https://github.com/google/boringssl/blob/master/SANDBOXING.md
* \sa https://github.com/aws/s2n-tls/blob/main/utils/s2n_fork_detection.c
*/
#pragma once
#include <err.h>
#include <stdlib.h>
#include <sys/mman.h>
#if defined(__cplusplus)
extern "C" {
#endif
/**
* \param len the number of bytes to allocate
* \return a pointer to the allocated memory
* \note This function terminates the calling process upon catastrophic error.
*/
static void*
allocate(const size_t len)
{
constexpr int prot = PROT_READ | PROT_WRITE;
constexpr int flags = MAP_PRIVATE | MAP_ANONYMOUS;
void* addr = mmap(nullptr, len, prot, flags, -1, 0);
if (addr == MAP_FAILED)
err(EXIT_FAILURE, "mmap");
if (madvise(addr, len, MADV_DONTDUMP) < 0)
err(EXIT_FAILURE, "madvise");
if (madvise(addr, len, MADV_WIPEONFORK) < 0)
err(EXIT_FAILURE, "madvise");
return addr;
}
#if defined(__cplusplus)
}
#endif