Skip to content

Commit

Permalink
darwin: fix madvise
Browse files Browse the repository at this point in the history
  • Loading branch information
rdunnington committed Aug 16, 2023
1 parent 259ff4f commit 3375a97
Showing 1 changed file with 11 additions and 22 deletions.
33 changes: 11 additions & 22 deletions stable_array.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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" {
Expand Down Expand Up @@ -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| {
Expand Down

0 comments on commit 3375a97

Please sign in to comment.