Files
mango/sandbox/base/main.c

83 lines
2.2 KiB
C

#include <stdio.h>
#include <stddef.h>
#include <inttypes.h>
#include <sys/mman.h>
#include <socks/types.h>
#include <socks/memblock.h>
/* we're working with 4MiB of simulated system RAM */
#define MEMORY_SIZE_MB 128
#define ALLOC_START_MB 16
#define ALLOC_END_MB 18
/* virtual address of where system memory is mapped */
static void *system_memory = NULL;
#define MEMPTR(offset) ((uintptr_t)system_memory + (offset))
#define MB_TO_BYTES(v) ((size_t)(v) * 0x100000)
#define PHYS_TO_VIRT(p) ((void *)((uintptr_t)system_memory + (p)))
#define VIRT_TO_PHYS(p) ((void *)((p) - (uintptr_t)system_memory))
int main(int argc, const char **argv)
{
system_memory = mmap(
NULL,
MB_TO_BYTES(MEMORY_SIZE_MB),
PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS,
-1, 0);
if (system_memory == MAP_FAILED) {
perror("mmap");
fprintf(stderr, "cannot allocate simulated system RAM buffer\n");
return -1;
}
printf("allocated %u MiB (0x%zx bytes) of memory to act as system RAM at %p\n", MEMORY_SIZE_MB, MB_TO_BYTES(MEMORY_SIZE_MB), system_memory);
uintptr_t voffset = (uintptr_t)system_memory;
memblock_init(MB_TO_BYTES(ALLOC_START_MB) + voffset, MB_TO_BYTES(ALLOC_END_MB) + voffset, voffset);
printf("memblock heap initialised in 0x%zx-0x%zx\n", MB_TO_BYTES(ALLOC_START_MB), MB_TO_BYTES(ALLOC_END_MB));
memblock_add(0, MB_TO_BYTES(MEMORY_SIZE_MB));
memblock_reserve(0x00000, 0x40000);
memblock_reserve(0x60000, 0x20000);
memblock_reserve(0x30000, 0x40000);
memblock_reserve(0x100000, 0x10000);
phys_addr_t alloc = memblock_alloc_phys(512);
printf("allocated 512 bytes at 0x%" PRIxPTR "\n", alloc);
printf("memory regions:\n");
memblock_iter_t it;
for_each_mem_range(&it, 0, 0x100000) {
printf("\t%08" PRIxPTR "-%08" PRIxPTR "\n",
it.it_base,
it.it_limit);
}
printf("reserved regions:\n");
for_each_reserved_mem_range(&it, 0, 0x100000) {
printf("\t%08" PRIxPTR "-%08" PRIxPTR " (%s)\n",
it.it_base,
it.it_limit,
it.it_status == MEMBLOCK_ALLOC ? "allocated" : "reserved");
}
printf("free regions:\n");
for_each_free_mem_range(&it, 0, ULLONG_MAX) {
printf("\t%08" PRIxPTR "-%08" PRIxPTR "\n",
it.it_base,
it.it_limit);
}
munmap(system_memory, MB_TO_BYTES(MEMORY_SIZE_MB));
return 0;
}