motiejus/zig

fork of https://codeberg.org/ziglang/zig
git clone https://git.jakstys.lt/motiejus/zig.git
Log | Tree | Refs | README | LICENSE

commit fd43baa9ad37217a5715c1e3cfad2d2d78558d1f (tree)
parent a338c279f82bfeb68e37b40cd4fc59557336b6ce
Author: Jay Petacat <jay@jayschwa.net>
Date:   Mon,  9 Oct 2023 22:24:14 -0600

byos: Ease `GeneralPurposeAllocator` integration

These changes enable me to use `GeneralPurposeAllocator` with my "Bring
Your Own OS" package. The previous checks for a freestanding target have
been expanded to `@hasDecl` checks.

- `root.os.heap.page_allocator` is used if it exists.
- `debug.isValidMemory` only calls `os.msync` if it's supported.

Diffstat:
Mlib/std/debug.zig | 29+++++++++++++++--------------
Mlib/std/heap.zig | 8+++++---
2 files changed, 20 insertions(+), 17 deletions(-)

diff --git a/lib/std/debug.zig b/lib/std/debug.zig @@ -667,20 +667,7 @@ pub const StackIterator = struct { if (aligned_address == 0) return false; const aligned_memory = @as([*]align(mem.page_size) u8, @ptrFromInt(aligned_address))[0..mem.page_size]; - if (native_os != .windows) { - if (native_os != .wasi) { - os.msync(aligned_memory, os.MSF.ASYNC) catch |err| { - switch (err) { - os.MSyncError.UnmappedMemory => { - return false; - }, - else => unreachable, - } - }; - } - - return true; - } else { + if (native_os == .windows) { const w = os.windows; var memory_info: w.MEMORY_BASIC_INFORMATION = undefined; @@ -701,6 +688,20 @@ pub const StackIterator = struct { } return true; + } else if (@hasDecl(os.system, "msync") and native_os != .wasi) { + os.msync(aligned_memory, os.MSF.ASYNC) catch |err| { + switch (err) { + os.MSyncError.UnmappedMemory => { + return false; + }, + else => unreachable, + } + }; + + return true; + } else { + // We are unable to determine validity of memory on this target. + return true; } } diff --git a/lib/std/heap.zig b/lib/std/heap.zig @@ -223,7 +223,11 @@ fn rawCFree( /// This allocator makes a syscall directly for every allocation and free. /// Thread-safe and lock-free. -pub const page_allocator = if (builtin.target.isWasm()) +pub const page_allocator = if (@hasDecl(root, "os") and + @hasDecl(root.os, "heap") and + @hasDecl(root.os.heap, "page_allocator")) + root.os.heap.page_allocator +else if (builtin.target.isWasm()) Allocator{ .ptr = undefined, .vtable = &WasmPageAllocator.vtable, @@ -233,8 +237,6 @@ else if (builtin.target.os.tag == .plan9) .ptr = undefined, .vtable = &SbrkAllocator(std.os.plan9.sbrk).vtable, } -else if (builtin.target.os.tag == .freestanding) - root.os.heap.page_allocator else Allocator{ .ptr = undefined,