From 3375a97c399cd9263281a27e895ec6ba984a1a53 Mon Sep 17 00:00:00 2001 From: Reuben Dunnington Date: Wed, 16 Aug 2023 10:57:27 -0700 Subject: [PATCH] darwin: fix madvise --- stable_array.zig | 33 +++++++++++---------------------- 1 file changed, 11 insertions(+), 22 deletions(-) diff --git a/stable_array.zig b/stable_array.zig index ac64e0e..acf8e95 100644 --- a/stable_array.zig +++ b/stable_array.zig @@ -4,6 +4,10 @@ const os = std.os; const mem = std.mem; const assert = std.debug.assert; +const darwin = struct { + extern "c" fn madvise(ptr: [*]align(mem.page_size) u8, length: usize, advice: c_int) c_int; +}; + pub fn StableArray(comptime T: type) type { return StableArrayAligned(T, @alignOf(T)); } @@ -204,7 +208,12 @@ pub fn StableArrayAligned(comptime T: type, comptime alignment: u29) type { var addr: [*]align(mem.page_size) u8 = @alignCast(mem.page_size, @intToPtr([*]u8, offset_addr)); if (comptime builtin.target.isDarwin()) { const MADV_DONTNEED = 4; - darwin_madvise(addr, bytes_to_free, MADV_DONTNEED) catch unreachable; + const err: c_int = darwin.madvise(addr, bytes_to_free, MADV_DONTNEED); + switch (@intToEnum(os.darwin.E, err)) { + os.E.INVAL => unreachable, + os.E.NOMEM => unreachable, + else => {}, + } } else { os.madvise(addr, bytes_to_free, std.c.MADV.DONTNEED) catch unreachable; } @@ -315,27 +324,6 @@ pub fn StableArrayAligned(comptime T: type, comptime alignment: u29) type { }; } -fn darwin_syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize { - return asm volatile ("syscall" - : [ret] "={rax}" (-> usize), - : [number] "{rax}" (number), - [arg1] "{rdi}" (arg1), - [arg2] "{rsi}" (arg2), - [arg3] "{rdx}" (arg3), - : "rcx", "r11", "memory" - ); -} - -fn darwin_madvise(ptr: [*]align(mem.page_size) u8, length: usize, advice: u32) os.MadviseError!void { - if (darwin_syscall3(75, @ptrToInt(ptr), length, advice) == -1) { - return switch (os.errno()) { - os.c.INVAL => os.MadviseError.InvalidSyscall, - os.c.ENOMEM => os.MadviseError.OutOfMemory, - else => os.MadviseError.Unexpected, - }; - } -} - const TEST_VIRTUAL_ALLOC_SIZE = 1024 * 1024 * 2; // 2 MB test "init" { @@ -374,6 +362,7 @@ test "shrinkAndFree" { var a = StableArray(u8).init(TEST_VIRTUAL_ALLOC_SIZE); try a.appendSlice(&[_]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }); a.shrinkAndFree(5); + assert(a.calcTotalUsedBytes() == mem.page_size); assert(a.items.len == 5); for (a.items) |v, i| {