mem/virtual: specify max protection on mmap call in NetBSD and FreeBSD

This commit is contained in:
Laytan Laats
2025-02-18 18:33:19 +01:00
parent ae0f69fbe2
commit cae3f13d9f
6 changed files with 99 additions and 24 deletions
+5 -23
View File
@@ -4,36 +4,18 @@ package mem_virtual
import "core:sys/posix"
// Define non-posix needed flags:
when ODIN_OS == .Darwin || ODIN_OS == .FreeBSD {
MADV_FREE :: 5 /* pages unneeded, discard contents */
} else when ODIN_OS == .OpenBSD || ODIN_OS == .NetBSD {
MADV_FREE :: 6
}
_reserve :: proc "contextless" (size: uint) -> (data: []byte, err: Allocator_Error) {
flags := posix.Map_Flags{ .ANONYMOUS, .PRIVATE }
result := posix.mmap(nil, size, {}, flags)
if result == posix.MAP_FAILED {
return nil, .Out_Of_Memory
}
return ([^]byte)(uintptr(result))[:size], nil
}
_commit :: proc "contextless" (data: rawptr, size: uint) -> Allocator_Error {
if posix.mprotect(data, size, { .READ, .WRITE }) != .OK {
return .Out_Of_Memory
#partial switch posix.errno() {
case .EACCES, .EPERM: return .Invalid_Pointer
case .ENOTSUP, .EINVAL: return .Invalid_Argument
case: return .Out_Of_Memory
}
}
return nil
}
_decommit :: proc "contextless" (data: rawptr, size: uint) {
posix.mprotect(data, size, {})
posix.posix_madvise(data, size, transmute(posix.MAdvice)i32(MADV_FREE))
}
_release :: proc "contextless" (data: rawptr, size: uint) {
posix.munmap(data, size)
}