Skip to content

Atomic memory allocator #521

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions std/assembly/allocator/atomic.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { AL_MASK, MAX_SIZE_32 } from "../internal/allocator";

var SATRT_OFFSET: usize = (HEAP_BASE + AL_MASK) & ~AL_MASK;
var OFFSET_PTR: usize = SATRT_OFFSET;
var TOP = (HEAP_BASE + 8 + AL_MASK) & ~AL_MASK;
store<usize>(OFFSET_PTR, TOP);

@global export function __allocator_get_offset(): usize {
return atomic.load<usize>(OFFSET_PTR);
}

@global export function __allocator_set_offset(oldOffset: usize, newOffset: usize): usize {
return atomic.cmpxchg<usize>(OFFSET_PTR, oldOffset, newOffset);
}

@global export function __memory_allocate(size: usize): usize {
if (size) {
if (size > MAX_SIZE_32) unreachable();
let currentOffset: usize;
let top: usize;
do {
currentOffset = __allocator_get_offset();
top = (currentOffset + size + AL_MASK) & ~AL_MASK;
let pagesBefore = memory.size();
if (top > (<usize>pagesBefore) << 16) {
let pagesNeeded = ((top - currentOffset + 0xffff) & ~0xffff) >>> 16;
let pagesWanted = max(pagesBefore, pagesNeeded); // double memory
if (memory.grow(pagesWanted) < 0) {
if (memory.grow(pagesNeeded) < 0) {
unreachable(); // out of memory
}
}
}
} while (
atomic.cmpxchg<usize>(OFFSET_PTR, currentOffset, top) != currentOffset
);

return currentOffset;
}
return 0;
}

@global export function __memory_free(ptr: usize): void {
//TODO: Not implemented
}

@global export function __memory_reset(): void {
atomic.store<usize>(OFFSET_PTR, SATRT_OFFSET);
}