Zig 0.17.0-dev (Split by item)

This is an example of documentation generated by ZigDoc, an alternative to Zig's built-in Auto Doc feature. See also examples in other modes/formats. The project being documented here (as the example) is the Zig library itself.

protectMemory

process.protectMemory
pub fn protectMemory(memory: []align(std.heap.page_size_min) u8, protection: MemoryProtection) ProtectMemoryError!void

File

lib/std/process.zig:1078

Code

pub fn protectMemory(memory: []align(std.heap.page_size_min) u8, protection: MemoryProtection) ProtectMemoryError!void {
    if (native_os == .windows) {
        var addr = memory.ptr; // ntdll takes an extra level of indirection here
        var size = memory.len; // ntdll takes an extra level of indirection here
        var old: windows.PAGE = undefined;
        const current_process: windows.HANDLE = @ptrFromInt(@as(usize, @bitCast(@as(isize, -1))));
        const new = windows.PAGE.fromProtection(protection) orelse return error.AccessDenied;
        switch (windows.ntdll.NtProtectVirtualMemory(current_process, @ptrCast(&addr), &size, new, &old)) {
            .SUCCESS => return,
            .INVALID_ADDRESS => return error.AccessDenied,
            else => |st| return windows.unexpectedStatus(st),
        }
    } else if (posix.PROT != void) {
        const flags: posix.PROT = .{
            .READ = protection.read,
            .WRITE = protection.write,
            .EXEC = protection.execute,
        };
        switch (posix.errno(posix.system.mprotect(memory.ptr, memory.len, flags))) {
            .SUCCESS => return,
            .PERM => return error.PermissionDenied,
            .INVAL => |err| return std.Io.Threaded.errnoBug(err),
            .ACCES => return error.AccessDenied,
            .NOMEM => return error.OutOfMemory,
            else => |err| return posix.unexpectedErrno(err),
        }
    }
    return error.UnsupportedOperation;
}