Skip to content

Commit

Permalink
fix memory corruption when using standalone heap (#1478)
Browse files Browse the repository at this point in the history
## Summary

Fix using the standalone heap (enabled with `--os:standalone` or
`-d:StandaloneHeapSize`) resulting in memory corruption due to
incorrect page alignment.

## Details

The initial pointer for the array-based page allocator is now aligned
to the size of a page, which ensures that `osAllocPages` always returns
a page-aligned pointer (the default allocator relies on this to be the
case).

A test is added to ensure that simple allocation/deallocation works
when using the array-based page allocator.
  • Loading branch information
zerbina authored Dec 20, 2024
1 parent d217009 commit 2780633
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/system/osalloc.nim
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,9 @@ elif hostOS == "standalone" or defined(StandaloneHeapSize):
const StandaloneHeapSize {.intdefine.}: int = 1024 * PageSize
var
theHeap: array[StandaloneHeapSize div sizeof(float64), float64] # 'float64' for alignment
bumpPointer = cast[int](addr theHeap)
# pages must always be aligned to the page size, which the heap array is
# not guaranteed to be, hence the roundup
bumpPointer = roundup(cast[int](addr theHeap), PageSize)

proc osAllocPages(size: int): pointer {.inline.} =
if size+bumpPointer < cast[int](addr theHeap) + sizeof(theHeap):
Expand Down
14 changes: 14 additions & 0 deletions tests/system/tosalloc_standalone_heap.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
discard """
description: "Ensure that the standalone heap option works"
matrix: "-d:StandaloneHeapSize:4166656 -d:useSysAssert"
targets: "c"
"""

# test with ``-d:useSysAssert`` so that violated allocator invariants are
# caught

# allocate, write, read back, and deallocate again
let p = create(int)
p[] = 100
doAssert p[] == 100
dealloc(p)

0 comments on commit 2780633

Please sign in to comment.