Skip to content

Commit

Permalink
include: memory: fix segfault
Browse files Browse the repository at this point in the history
We were calculating memory_chunk's block passed its memory limit. This
was causing unexpected memory overwrites.

- Re-enable allocation from stack
  • Loading branch information
e2dk4r committed Oct 28, 2024
1 parent eb8f71f commit c55dadb
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 12 deletions.
2 changes: 1 addition & 1 deletion include/memory.h
Original file line number Diff line number Diff line change
Expand Up @@ -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++) {
Expand Down
15 changes: 4 additions & 11 deletions src/main.c
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand All @@ -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");
Expand All @@ -396,13 +389,13 @@ main(int argc, char *argv[])
u64 length = 0;

#define PRINTLN_U64(prefix, number) \
string = STRING_FROM_ZERO_TERMINATED(prefix); \
string = (struct string){.value = (u8 *)prefix, .length = sizeof(prefix) - 1}; \
memcpy(stdoutBuffer.value + length, string.value, string.length); \
length += string.length; \
string = FormatU64(&stringBuffer, number); \
memcpy(stdoutBuffer.value + length, string.value, string.length); \
length += string.length; \
string = STRING_FROM_ZERO_TERMINATED("\n"); \
string = (struct string){.value = (u8 *)"\n", .length = 1}; \
memcpy(stdoutBuffer.value + length, string.value, string.length); \
length += string.length

Expand Down

0 comments on commit c55dadb

Please sign in to comment.