authorgravatar for jay@jayschwa.netJay Petacat <jay@jayschwa.net> 2023-10-09 22:24:14-06:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2024-01-16 15:05:38-08:00
logfd43baa9ad37217a5715c1e3cfad2d2d78558d1f
treec0d75d8a8c92038f05ea78f961b5dd7b23e0efbc
parenta338c279f82bfeb68e37b40cd4fc59557336b6ce

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.

2 files changed, 20 insertions(+), 17 deletions(-)

lib/std/debug.zig+15-14
......@@ -667,20 +667,7 @@ pub const StackIterator = struct {
667667 if (aligned_address == 0) return false;
668668 const aligned_memory = @as([*]align(mem.page_size) u8, @ptrFromInt(aligned_address))[0..mem.page_size];
669669
670 if (native_os != .windows) {
671 if (native_os != .wasi) {
672 os.msync(aligned_memory, os.MSF.ASYNC) catch |err| {
673 switch (err) {
674 os.MSyncError.UnmappedMemory => {
675 return false;
676 },
677 else => unreachable,
678 }
679 };
680 }
681
682 return true;
683 } else {
670 if (native_os == .windows) {
684671 const w = os.windows;
685672 var memory_info: w.MEMORY_BASIC_INFORMATION = undefined;
686673
......@@ -700,6 +687,20 @@ pub const StackIterator = struct {
700687 return false;
701688 }
702689
690 return true;
691 } else if (@hasDecl(os.system, "msync") and native_os != .wasi) {
692 os.msync(aligned_memory, os.MSF.ASYNC) catch |err| {
693 switch (err) {
694 os.MSyncError.UnmappedMemory => {
695 return false;
696 },
697 else => unreachable,
698 }
699 };
700
701 return true;
702 } else {
703 // We are unable to determine validity of memory on this target.
703704 return true;
704705 }
705706 }
lib/std/heap.zig+5-3
......@@ -223,7 +223,11 @@ fn rawCFree(
223223
224224/// This allocator makes a syscall directly for every allocation and free.
225225/// Thread-safe and lock-free.
226pub const page_allocator = if (builtin.target.isWasm())
226pub const page_allocator = if (@hasDecl(root, "os") and
227 @hasDecl(root.os, "heap") and
228 @hasDecl(root.os.heap, "page_allocator"))
229 root.os.heap.page_allocator
230else if (builtin.target.isWasm())
227231 Allocator{
228232 .ptr = undefined,
229233 .vtable = &WasmPageAllocator.vtable,
......@@ -233,8 +237,6 @@ else if (builtin.target.os.tag == .plan9)
233237 .ptr = undefined,
234238 .vtable = &SbrkAllocator(std.os.plan9.sbrk).vtable,
235239 }
236else if (builtin.target.os.tag == .freestanding)
237 root.os.heap.page_allocator
238240else
239241 Allocator{
240242 .ptr = undefined,