aboutsummaryrefslogtreecommitdiff
path: root/src/init/alloc.cc
blob: d18917bce44e887873ace786435cb7456088f87c (plain)
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
#include "alloc.h"

#include <cstdio>
#include <cstdint>

namespace init {

std::uint8_t dlsym_level   = 0;
size_t       buffer_offset = 0;
char         buffer[4096];

void* static_malloc(size_t size) {
	if ( buffer_offset + size >= sizeof(buffer) ) {
		std::fprintf(stderr, "static allocator out of memory: %lu\n", buffer_offset);
		exit(1);
	}

	buffer_offset += size;

	return buffer + buffer_offset;
}

void* static_calloc(size_t block, size_t size) {
	void* const mem = static_malloc(block * size);

	for ( size_t i = 0; i < (block * size); ++i ) {
		*(static_cast<char* const>(mem) + i) = '\0';
	}

	return mem;
}

bool from_static_buffer(void* ptr) {
	return static_cast<char*>(ptr) >= buffer
	    && static_cast<char*>(ptr) <= buffer + sizeof(buffer);
}

dlsymContext::dlsymContext() {
	++dlsym_level;
}

dlsymContext::~dlsymContext() {
	--dlsym_level;
}

bool dlsymContext::is_active() {
	return dlsym_level > 0;
}

}