From fd43baa9ad37217a5715c1e3cfad2d2d78558d1f Mon Sep 17 00:00:00 2001 From: Jay Petacat Date: Mon, 9 Oct 2023 22:24:14 -0600 Subject: [PATCH] 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. --- lib/std/debug.zig | 29 +++++++++++++++-------------- lib/std/heap.zig | 8 +++++--- 2 files changed, 20 insertions(+), 17 deletions(-) diff --git a/lib/std/debug.zig b/lib/std/debug.zig index 4670c49dfa..5976e52684 100644 --- 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; @@ -700,6 +687,20 @@ pub const StackIterator = struct { return false; } + 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 index 3dc4f83396..f044c13886 100644 --- 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,