From 633a00b9b8d23a716401ac076b40901386348566 Mon Sep 17 00:00:00 2001 From: e2dk4r <43293320+e2dk4r@users.noreply.github.com> Date: Mon, 28 Oct 2024 17:32:06 +0300 Subject: [PATCH] include: memory: fix segfault We were calculating memory_chunk's block passed its memory limit. This was causing unexpected memory overwrites. - Re-enable allocation from stack --- include/memory.h | 2 +- src/main.c | 11 ++--------- 2 files changed, 3 insertions(+), 10 deletions(-) diff --git a/include/memory.h b/include/memory.h index e0d3d9b..3432f7b 100644 --- a/include/memory.h +++ b/include/memory.h @@ -74,7 +74,7 @@ static struct memory_chunk * MemPushChunk(struct memory_block *mem, u64 size, u64 max) { struct memory_chunk *chunk = MemPush(mem, sizeof(*chunk) + max * sizeof(u8) + max * size); - chunk->block = chunk + sizeof(*chunk); + chunk->block = (u8*)chunk + sizeof(*chunk); chunk->size = size; chunk->max = max; for (u64 index = 0; index < chunk->max; index++) { diff --git a/src/main.c b/src/main.c index ca07d4b..7aabe19 100644 --- a/src/main.c +++ b/src/main.c @@ -337,14 +337,7 @@ main(int argc, char *argv[]) memory.total = 1 * KILOBYTES; // OPTION A - allocate from stack - // BUG: allocate from stack - // moving ls,rs on gamepad changes gamepad to invalid address SIGSEGV - // problem fixed when using allocation from RAM (option B) instead of stack allocation. - // reproduce steps: - // 1 - stop at memory allocation - // 2 - step through to first memcpy stdoutBuffer usage. - // MemoryForDeviceOpenEvents->block will be overwritten. - if (0) { + if (1) { // - check limit struct rlimit rlim; if (getrlimit(RLIMIT_STACK, &rlim)) { @@ -369,7 +362,7 @@ main(int argc, char *argv[]) } // OPTION B - Allocate from RAM - if (1) { + else { memory.block = mmap(0, (size_t)memory.total, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (!memory.block) { fatal("you do not have 1k memory available.\n");