Skip to content

Commit 3375a97

Browse files
committed
darwin: fix madvise
1 parent 259ff4f commit 3375a97

File tree

1 file changed

+11
-22
lines changed

1 file changed

+11
-22
lines changed

stable_array.zig

Lines changed: 11 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@ const os = std.os;
44
const mem = std.mem;
55
const assert = std.debug.assert;
66

7+
const darwin = struct {
8+
extern "c" fn madvise(ptr: [*]align(mem.page_size) u8, length: usize, advice: c_int) c_int;
9+
};
10+
711
pub fn StableArray(comptime T: type) type {
812
return StableArrayAligned(T, @alignOf(T));
913
}
@@ -204,7 +208,12 @@ pub fn StableArrayAligned(comptime T: type, comptime alignment: u29) type {
204208
var addr: [*]align(mem.page_size) u8 = @alignCast(mem.page_size, @intToPtr([*]u8, offset_addr));
205209
if (comptime builtin.target.isDarwin()) {
206210
const MADV_DONTNEED = 4;
207-
darwin_madvise(addr, bytes_to_free, MADV_DONTNEED) catch unreachable;
211+
const err: c_int = darwin.madvise(addr, bytes_to_free, MADV_DONTNEED);
212+
switch (@intToEnum(os.darwin.E, err)) {
213+
os.E.INVAL => unreachable,
214+
os.E.NOMEM => unreachable,
215+
else => {},
216+
}
208217
} else {
209218
os.madvise(addr, bytes_to_free, std.c.MADV.DONTNEED) catch unreachable;
210219
}
@@ -315,27 +324,6 @@ pub fn StableArrayAligned(comptime T: type, comptime alignment: u29) type {
315324
};
316325
}
317326

318-
fn darwin_syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize {
319-
return asm volatile ("syscall"
320-
: [ret] "={rax}" (-> usize),
321-
: [number] "{rax}" (number),
322-
[arg1] "{rdi}" (arg1),
323-
[arg2] "{rsi}" (arg2),
324-
[arg3] "{rdx}" (arg3),
325-
: "rcx", "r11", "memory"
326-
);
327-
}
328-
329-
fn darwin_madvise(ptr: [*]align(mem.page_size) u8, length: usize, advice: u32) os.MadviseError!void {
330-
if (darwin_syscall3(75, @ptrToInt(ptr), length, advice) == -1) {
331-
return switch (os.errno()) {
332-
os.c.INVAL => os.MadviseError.InvalidSyscall,
333-
os.c.ENOMEM => os.MadviseError.OutOfMemory,
334-
else => os.MadviseError.Unexpected,
335-
};
336-
}
337-
}
338-
339327
const TEST_VIRTUAL_ALLOC_SIZE = 1024 * 1024 * 2; // 2 MB
340328

341329
test "init" {
@@ -374,6 +362,7 @@ test "shrinkAndFree" {
374362
var a = StableArray(u8).init(TEST_VIRTUAL_ALLOC_SIZE);
375363
try a.appendSlice(&[_]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
376364
a.shrinkAndFree(5);
365+
377366
assert(a.calcTotalUsedBytes() == mem.page_size);
378367
assert(a.items.len == 5);
379368
for (a.items) |v, i| {

0 commit comments

Comments
 (0)