print errors on mem alloc failure

This commit is contained in:
silverweed 2024-07-17 13:20:46 +02:00
parent 3d7f61362b
commit d177ea66a8
3 changed files with 21 additions and 3 deletions

View file

@ -61,7 +61,7 @@ Arena *arena_alloc_sized(u64 init_res, u64 init_cmt)
{
assert(ARENA_HEADER_SIZE < init_cmt && init_cmt <= init_res);
u64 page_size = getpagesize();
u64 page_size = os_page_size();
u64 res = align_pow2(init_res, page_size);
u64 cmt = align_pow2(init_cmt, page_size);
@ -199,6 +199,7 @@ u8 *arena_push_contiguous(Arena *arena, u64 size)
arena->grow = 0;
void *mem = arena_push_impl(arena, size);
arena->grow = restore;
if (!mem) fprintf(stderr, "Failed to allocate %lu bytes of contiguous memory\n", size);
return (u8 *)mem;
}

View file

@ -4,6 +4,12 @@
#include <unistd.h>
#include <limits.h> // for NAME_MAX
internal
i32 os_page_size()
{
return getpagesize();
}
internal
bool os_open_and_map_file(const char *fname, App_State &app)
{
@ -56,7 +62,11 @@ void os_stop_file_watch(App_State &app)
internal
void *os_reserve(u64 size)
{
return mmap(0, size, PROT_NONE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
void *mem = mmap(0, size, PROT_NONE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
if (UNLIKELY(mem == MAP_FAILED)) {
fprintf(stderr, "Error reserving memory: %s (%d)\n", strerror(errno), errno);
}
return mem;
}
internal
@ -68,6 +78,10 @@ void os_release(void *mem, u64 size)
internal
b32x os_commit(void *addr, u64 size)
{
return mprotect(addr, size, PROT_READ|PROT_WRITE) == 0;
b32x err = mprotect(addr, size, PROT_READ|PROT_WRITE);
if (UNLIKELY(err)) {
fprintf(stderr, "Error committing memory: %s (%d)\n", strerror(errno), errno);
}
return err == 0;
}

View file

@ -22,3 +22,6 @@ using i64 = int64_t;
#define KiB(b) (b * 1024)
#define MiB(b) (KiB(b) * 1024)
#define GiB(b) (MiB(b) * 1024)
#define LIKELY(x) __builtin_expect(!!(x), 1)
#define UNLIKELY(x) __builtin_expect(!!(x), 0)