const root = @import("root");
const std = @import("std.zig");
const builtin = @import("builtin");
const assert = std.debug.assert;
const math = std.math;
const mem = std.mem;
const elf = std.elf;
const fs = std.fs;
const dl = @import("dynamic_library.zig");
const MAX_PATH_BYTES = std.fs.MAX_PATH_BYTES;
const is_windows = builtin.os.tag == .windows;
const Allocator = std.mem.Allocator;
const Preopen = std.fs.wasi.Preopen;
const PreopenList = std.fs.wasi.PreopenList;
pub const darwin = std.c;
pub const dragonfly = std.c;
pub const freebsd = std.c;
pub const haiku = std.c;
pub const netbsd = std.c;
pub const openbsd = std.c;
pub const solaris = std.c;
pub const linux = @import("os/linux.zig");
pub const plan9 = @import("os/plan9.zig");
pub const uefi = @import("os/uefi.zig");
pub const wasi = @import("os/wasi.zig");
pub const windows = @import("os/windows.zig");
comptime {
assert(@import("std") == std);
}
test {
_ = darwin;
_ = linux;
if (builtin.os.tag == .uefi) {
_ = uefi;
}
_ = wasi;
_ = windows;
_ = @import("os/test.zig");
}
pub const system = if (@hasDecl(root, "os") and root.os != @This())
root.os.system
else if (builtin.link_libc or is_windows)
std.c
else switch (builtin.os.tag) {
.linux => linux,
.wasi => wasi,
.uefi => uefi,
else => struct {},
};
pub const AF = system.AF;
pub const AF_SUN = system.AF_SUN;
pub const ARCH = system.ARCH;
pub const AT = system.AT;
pub const AT_SUN = system.AT_SUN;
pub const CLOCK = system.CLOCK;
pub const CPU_COUNT = system.CPU_COUNT;
pub const CTL = system.CTL;
pub const DT = system.DT;
pub const E = system.E;
pub const Elf_Symndx = system.Elf_Symndx;
pub const F = system.F;
pub const FD_CLOEXEC = system.FD_CLOEXEC;
pub const Flock = system.Flock;
pub const HOST_NAME_MAX = system.HOST_NAME_MAX;
pub const IFNAMESIZE = system.IFNAMESIZE;
pub const IOV_MAX = system.IOV_MAX;
pub const IPPROTO = system.IPPROTO;
pub const KERN = system.KERN;
pub const Kevent = system.Kevent;
pub const LOCK = system.LOCK;
pub const MADV = system.MADV;
pub const MAP = system.MAP;
pub const MSF = system.MSF;
pub const MAX_ADDR_LEN = system.MAX_ADDR_LEN;
pub const MFD = system.MFD;
pub const MMAP2_UNIT = system.MMAP2_UNIT;
pub const MSG = system.MSG;
pub const NAME_MAX = system.NAME_MAX;
pub const O = switch (builtin.os.tag) {
.wasi => std.c.O,
else => system.O,
};
pub const PATH_MAX = system.PATH_MAX;
pub const POLL = system.POLL;
pub const POSIX_FADV = system.POSIX_FADV;
pub const PR = system.PR;
pub const PROT = system.PROT;
pub const REG = system.REG;
pub const RIGHT = system.RIGHT;
pub const RLIM = system.RLIM;
pub const RR = system.RR;
pub const S = system.S;
pub const SA = system.SA;
pub const SC = system.SC;
pub const _SC = system._SC;
pub const SEEK = system.SEEK;
pub const SHUT = system.SHUT;
pub const SIG = system.SIG;
pub const SIOCGIFINDEX = system.SIOCGIFINDEX;
pub const SO = system.SO;
pub const SOCK = system.SOCK;
pub const SOL = system.SOL;
pub const STDERR_FILENO = system.STDERR_FILENO;
pub const STDIN_FILENO = system.STDIN_FILENO;
pub const STDOUT_FILENO = system.STDOUT_FILENO;
pub const SYS = system.SYS;
pub const Sigaction = system.Sigaction;
pub const Stat = system.Stat;
pub const TCSA = system.TCSA;
pub const TCP = system.TCP;
pub const VDSO = system.VDSO;
pub const W = system.W;
pub const addrinfo = system.addrinfo;
pub const blkcnt_t = system.blkcnt_t;
pub const blksize_t = system.blksize_t;
pub const clock_t = system.clock_t;
pub const cpu_set_t = if (builtin.os.tag == .linux)
system.cpu_set_t
else if (builtin.os.tag == .freebsd)
freebsd.cpuset_t
else
u32;
pub const dev_t = system.dev_t;
pub const dl_phdr_info = system.dl_phdr_info;
pub const empty_sigset = system.empty_sigset;
pub const fd_t = system.fd_t;
pub const fdflags_t = system.fdflags_t;
pub const fdstat_t = system.fdstat_t;
pub const gid_t = system.gid_t;
pub const ifreq = system.ifreq;
pub const ino_t = system.ino_t;
pub const lookupflags_t = system.lookupflags_t;
pub const mcontext_t = system.mcontext_t;
pub const mode_t = system.mode_t;
pub const msghdr = system.msghdr;
pub const msghdr_const = system.msghdr_const;
pub const nfds_t = system.nfds_t;
pub const nlink_t = system.nlink_t;
pub const off_t = system.off_t;
pub const oflags_t = system.oflags_t;
pub const pid_t = system.pid_t;
pub const pollfd = system.pollfd;
pub const port_t = system.port_t;
pub const port_event = system.port_event;
pub const port_notify = system.port_notify;
pub const file_obj = system.file_obj;
pub const rights_t = system.rights_t;
pub const rlim_t = system.rlim_t;
pub const rlimit = system.rlimit;
pub const rlimit_resource = system.rlimit_resource;
pub const rusage = system.rusage;
pub const sa_family_t = system.sa_family_t;
pub const siginfo_t = system.siginfo_t;
pub const sigset_t = system.sigset_t;
pub const sockaddr = system.sockaddr;
pub const socklen_t = system.socklen_t;
pub const stack_t = system.stack_t;
pub const tcflag_t = system.tcflag_t;
pub const termios = system.termios;
pub const time_t = system.time_t;
pub const timespec = system.timespec;
pub const timestamp_t = system.timestamp_t;
pub const timeval = system.timeval;
pub const timezone = system.timezone;
pub const ucontext_t = system.ucontext_t;
pub const uid_t = system.uid_t;
pub const user_desc = system.user_desc;
pub const utsname = system.utsname;
pub const F_OK = system.F_OK;
pub const R_OK = system.R_OK;
pub const W_OK = system.W_OK;
pub const X_OK = system.X_OK;
pub const iovec = extern struct {
iov_base: [*]u8,
iov_len: usize,
};
pub const iovec_const = extern struct {
iov_base: [*]const u8,
iov_len: usize,
};
pub const LOG = struct {
pub const EMERG = 0;
pub const ALERT = 1;
pub const CRIT = 2;
pub const ERR = 3;
pub const WARNING = 4;
pub const NOTICE = 5;
pub const INFO = 6;
pub const DEBUG = 7;
};
pub const RelativePathWasi = struct {
dir_fd: fd_t,
relative_path: []const u8,
};
pub const socket_t = if (builtin.os.tag == .windows) windows.ws2_32.SOCKET else fd_t;
pub var environ: [][*:0]u8 = undefined;
pub var argv: [][*:0]u8 = if (builtin.link_libc) undefined else switch (builtin.os.tag) {
.windows => @compileError("argv isn't supported on Windows: use std.process.argsAlloc instead"),
.wasi => @compileError("argv isn't supported on WASI: use std.process.argsAlloc instead"),
else => undefined,
};
pub const have_sigpipe_support = @hasDecl(@This(), "SIG") and @hasDecl(SIG, "PIPE");
fn noopSigHandler(_: c_int) callconv(.C) void {}
pub fn maybeIgnoreSigpipe() void {
if (have_sigpipe_support and !std.options.keep_sigpipe) {
const act = Sigaction{
.handler = .{ .handler = noopSigHandler },
.mask = empty_sigset,
.flags = 0,
};
sigaction(SIG.PIPE, &act, null) catch |err|
std.debug.panic("failed to install noop SIGPIPE handler with '{s}'", .{@errorName(err)});
}
}
pub const errno = system.getErrno;
pub fn close(fd: fd_t) void {
if (builtin.os.tag == .windows) {
return windows.CloseHandle(fd);
}
if (builtin.os.tag == .wasi and !builtin.link_libc) {
_ = wasi.fd_close(fd);
return;
}
if (comptime builtin.target.isDarwin()) {
switch (darwin.getErrno(darwin.@"close$NOCANCEL"(fd))) {
.BADF => unreachable,
else => return,
}
}
switch (errno(system.close(fd))) {
.BADF => unreachable,
.INTR => return,
else => return,
}
}
pub const FChmodError = error{
AccessDenied,
InputOutput,
SymLinkLoop,
FileNotFound,
SystemResources,
ReadOnlyFileSystem,
} || UnexpectedError;
pub fn fchmod(fd: fd_t, mode: mode_t) FChmodError!void {
if (!std.fs.has_executable_bit) @compileError("fchmod unsupported by target OS");
while (true) {
const res = system.fchmod(fd, mode);
switch (system.getErrno(res)) {
.SUCCESS => return,
.INTR => continue,
.BADF => unreachable,
.FAULT => unreachable,
.INVAL => unreachable,
.ACCES => return error.AccessDenied,
.IO => return error.InputOutput,
.LOOP => return error.SymLinkLoop,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOTDIR => return error.FileNotFound,
.PERM => return error.AccessDenied,
.ROFS => return error.ReadOnlyFileSystem,
else => |err| return unexpectedErrno(err),
}
}
}
const FChmodAtError = FChmodError || error{
NameTooLong,
};
pub fn fchmodat(dirfd: fd_t, path: []const u8, mode: mode_t, flags: u32) FChmodAtError!void {
if (!std.fs.has_executable_bit) @compileError("fchmodat unsupported by target OS");
const path_c = try toPosixPath(path);
while (true) {
const res = system.fchmodat(dirfd, &path_c, mode, flags);
switch (system.getErrno(res)) {
.SUCCESS => return,
.INTR => continue,
.BADF => unreachable,
.FAULT => unreachable,
.INVAL => unreachable,
.ACCES => return error.AccessDenied,
.IO => return error.InputOutput,
.LOOP => return error.SymLinkLoop,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOTDIR => return error.FileNotFound,
.PERM => return error.AccessDenied,
.ROFS => return error.ReadOnlyFileSystem,
else => |err| return unexpectedErrno(err),
}
}
}
pub const FChownError = error{
AccessDenied,
InputOutput,
SymLinkLoop,
FileNotFound,
SystemResources,
ReadOnlyFileSystem,
} || UnexpectedError;
pub fn fchown(fd: fd_t, owner: ?uid_t, group: ?gid_t) FChownError!void {
if (builtin.os.tag == .windows or builtin.os.tag == .wasi)
@compileError("Unsupported OS");
while (true) {
const res = system.fchown(fd, owner orelse @as(u32, 0) -% 1, group orelse @as(u32, 0) -% 1);
switch (system.getErrno(res)) {
.SUCCESS => return,
.INTR => continue,
.BADF => unreachable,
.FAULT => unreachable,
.INVAL => unreachable,
.ACCES => return error.AccessDenied,
.IO => return error.InputOutput,
.LOOP => return error.SymLinkLoop,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOTDIR => return error.FileNotFound,
.PERM => return error.AccessDenied,
.ROFS => return error.ReadOnlyFileSystem,
else => |err| return unexpectedErrno(err),
}
}
}
pub const RebootError = error{
PermissionDenied,
} || UnexpectedError;
pub const RebootCommand = switch (builtin.os.tag) {
.linux => union(linux.LINUX_REBOOT.CMD) {
RESTART: void,
HALT: void,
CAD_ON: void,
CAD_OFF: void,
POWER_OFF: void,
RESTART2: [*:0]const u8,
SW_SUSPEND: void,
KEXEC: void,
},
else => @compileError("Unsupported OS"),
};
pub fn reboot(cmd: RebootCommand) RebootError!void {
switch (builtin.os.tag) {
.linux => {
switch (system.getErrno(linux.reboot(
.MAGIC1,
.MAGIC2,
@as(linux.LINUX_REBOOT.CMD, cmd),
switch (cmd) {
.RESTART2 => |s| s,
else => null,
},
))) {
.SUCCESS => {},
.PERM => return error.PermissionDenied,
else => |err| return std.os.unexpectedErrno(err),
}
switch (cmd) {
.CAD_OFF => {},
.CAD_ON => {},
.SW_SUSPEND => {},
.HALT => unreachable,
.KEXEC => unreachable,
.POWER_OFF => unreachable,
.RESTART => unreachable,
.RESTART2 => unreachable,
}
},
else => @compileError("Unsupported OS"),
}
}
pub const GetRandomError = OpenError;
pub fn getrandom(buffer: []u8) GetRandomError!void {
if (builtin.os.tag == .windows) {
return windows.RtlGenRandom(buffer);
}
if (builtin.os.tag == .linux or builtin.os.tag == .freebsd) {
var buf = buffer;
const use_c = builtin.os.tag != .linux or
std.c.versionCheck(std.builtin.Version{ .major = 2, .minor = 25, .patch = 0 }).ok;
while (buf.len != 0) {
const res = if (use_c) blk: {
const rc = std.c.getrandom(buf.ptr, buf.len, 0);
break :blk .{
.num_read = @bitCast(usize, rc),
.err = std.c.getErrno(rc),
};
} else blk: {
const rc = linux.getrandom(buf.ptr, buf.len, 0);
break :blk .{
.num_read = rc,
.err = linux.getErrno(rc),
};
};
switch (res.err) {
.SUCCESS => buf = buf[res.num_read..],
.INVAL => unreachable,
.FAULT => unreachable,
.INTR => continue,
.NOSYS => return getRandomBytesDevURandom(buf),
else => return unexpectedErrno(res.err),
}
}
return;
}
switch (builtin.os.tag) {
.netbsd, .openbsd, .macos, .ios, .tvos, .watchos => {
system.arc4random_buf(buffer.ptr, buffer.len);
return;
},
.wasi => switch (wasi.random_get(buffer.ptr, buffer.len)) {
.SUCCESS => return,
else => |err| return unexpectedErrno(err),
},
else => return getRandomBytesDevURandom(buffer),
}
}
fn getRandomBytesDevURandom(buf: []u8) !void {
const fd = try openZ("/dev/urandom", O.RDONLY | O.CLOEXEC, 0);
defer close(fd);
const st = try fstat(fd);
if (!S.ISCHR(st.mode)) {
return error.NoDevice;
}
const file = std.fs.File{
.handle = fd,
.capable_io_mode = .blocking,
.intended_io_mode = .blocking,
};
const stream = file.reader();
stream.readNoEof(buf) catch return error.Unexpected;
}
pub fn abort() noreturn {
@setCold(true);
if (builtin.os.tag == .windows) {
if (builtin.mode == .Debug) {
@breakpoint();
}
windows.kernel32.ExitProcess(3);
}
if (!builtin.link_libc and builtin.os.tag == .linux) {
raise(SIG.ABRT) catch {};
sigprocmask(SIG.BLOCK, &linux.all_mask, null);
if (!builtin.single_threaded) {
const global = struct {
var abort_entered: bool = false;
};
while (@cmpxchgWeak(bool, &global.abort_entered, false, true, .SeqCst, .SeqCst)) |_| {}
}
const sigact = Sigaction{
.handler = .{ .handler = SIG.DFL },
.mask = empty_sigset,
.flags = 0,
};
sigaction(SIG.ABRT, &sigact, null) catch |err| switch (err) {
error.OperationNotSupported => unreachable,
};
_ = linux.tkill(linux.gettid(), SIG.ABRT);
const sigabrtmask: linux.sigset_t = [_]u32{0} ** 31 ++ [_]u32{1 << (SIG.ABRT - 1)};
sigprocmask(SIG.UNBLOCK, &sigabrtmask, null);
@intToPtr(*allowzero volatile u8, 0).* = 0;
raise(SIG.KILL) catch {};
exit(127);
}
switch (builtin.os.tag) {
.uefi, .wasi, .cuda => @trap(),
else => system.abort(),
}
}
pub const RaiseError = UnexpectedError;
pub fn raise(sig: u8) RaiseError!void {
if (builtin.link_libc) {
switch (errno(system.raise(sig))) {
.SUCCESS => return,
else => |err| return unexpectedErrno(err),
}
}
if (builtin.os.tag == .linux) {
var set: sigset_t = undefined;
sigprocmask(SIG.BLOCK, &linux.app_mask, &set);
const tid = linux.gettid();
const rc = linux.tkill(tid, sig);
sigprocmask(SIG.SETMASK, &set, null);
switch (errno(rc)) {
.SUCCESS => return,
else => |err| return unexpectedErrno(err),
}
}
@compileError("std.os.raise unimplemented for this target");
}
pub const KillError = error{PermissionDenied} || UnexpectedError;
pub fn kill(pid: pid_t, sig: u8) KillError!void {
switch (errno(system.kill(pid, sig))) {
.SUCCESS => return,
.INVAL => unreachable,
.PERM => return error.PermissionDenied,
.SRCH => unreachable,
else => |err| return unexpectedErrno(err),
}
}
pub fn exit(status: u8) noreturn {
if (builtin.link_libc) {
system.exit(status);
}
if (builtin.os.tag == .windows) {
windows.kernel32.ExitProcess(status);
}
if (builtin.os.tag == .wasi) {
wasi.proc_exit(status);
}
if (builtin.os.tag == .linux and !builtin.single_threaded) {
linux.exit_group(status);
}
if (builtin.os.tag == .uefi) {
if (uefi.system_table.boot_services) |bs| {
_ = bs.exit(uefi.handle, @intToEnum(uefi.Status, status), 0, null);
}
uefi.system_table.runtime_services.resetSystem(uefi.tables.ResetType.ResetCold, @intToEnum(uefi.Status, status), 0, null);
}
system.exit(status);
}
pub const ReadError = error{
InputOutput,
SystemResources,
IsDir,
OperationAborted,
BrokenPipe,
ConnectionResetByPeer,
ConnectionTimedOut,
NotOpenForReading,
NetNameDeleted,
WouldBlock,
AccessDenied,
} || UnexpectedError;
pub fn read(fd: fd_t, buf: []u8) ReadError!usize {
if (buf.len == 0) return 0;
if (builtin.os.tag == .windows) {
return windows.ReadFile(fd, buf, null, std.io.default_mode);
}
if (builtin.os.tag == .wasi and !builtin.link_libc) {
const iovs = [1]iovec{iovec{
.iov_base = buf.ptr,
.iov_len = buf.len,
}};
var nread: usize = undefined;
switch (wasi.fd_read(fd, &iovs, iovs.len, &nread)) {
.SUCCESS => return nread,
.INTR => unreachable,
.INVAL => unreachable,
.FAULT => unreachable,
.AGAIN => unreachable,
.BADF => return error.NotOpenForReading,
.IO => return error.InputOutput,
.ISDIR => return error.IsDir,
.NOBUFS => return error.SystemResources,
.NOMEM => return error.SystemResources,
.CONNRESET => return error.ConnectionResetByPeer,
.TIMEDOUT => return error.ConnectionTimedOut,
.NOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
const max_count = switch (builtin.os.tag) {
.linux => 0x7ffff000,
.macos, .ios, .watchos, .tvos => math.maxInt(i32),
else => math.maxInt(isize),
};
const adjusted_len = @min(max_count, buf.len);
while (true) {
const rc = system.read(fd, buf.ptr, adjusted_len);
switch (errno(rc)) {
.SUCCESS => return @intCast(usize, rc),
.INTR => continue,
.INVAL => unreachable,
.FAULT => unreachable,
.AGAIN => return error.WouldBlock,
.BADF => return error.NotOpenForReading,
.IO => return error.InputOutput,
.ISDIR => return error.IsDir,
.NOBUFS => return error.SystemResources,
.NOMEM => return error.SystemResources,
.CONNRESET => return error.ConnectionResetByPeer,
.TIMEDOUT => return error.ConnectionTimedOut,
else => |err| return unexpectedErrno(err),
}
}
}
pub fn readv(fd: fd_t, iov: []const iovec) ReadError!usize {
if (builtin.os.tag == .windows) {
if (iov.len == 0) return @as(usize, 0);
const first = iov[0];
return read(fd, first.iov_base[0..first.iov_len]);
}
if (builtin.os.tag == .wasi and !builtin.link_libc) {
var nread: usize = undefined;
switch (wasi.fd_read(fd, iov.ptr, iov.len, &nread)) {
.SUCCESS => return nread,
.INTR => unreachable,
.INVAL => unreachable,
.FAULT => unreachable,
.AGAIN => unreachable,
.BADF => return error.NotOpenForReading,
.IO => return error.InputOutput,
.ISDIR => return error.IsDir,
.NOBUFS => return error.SystemResources,
.NOMEM => return error.SystemResources,
.NOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
const iov_count = math.cast(u31, iov.len) orelse math.maxInt(u31);
while (true) {
const rc = system.readv(fd, iov.ptr, iov_count);
switch (errno(rc)) {
.SUCCESS => return @intCast(usize, rc),
.INTR => continue,
.INVAL => unreachable,
.FAULT => unreachable,
.AGAIN => return error.WouldBlock,
.BADF => return error.NotOpenForReading,
.IO => return error.InputOutput,
.ISDIR => return error.IsDir,
.NOBUFS => return error.SystemResources,
.NOMEM => return error.SystemResources,
.CONNRESET => return error.ConnectionResetByPeer,
else => |err| return unexpectedErrno(err),
}
}
}
pub const PReadError = ReadError || error{Unseekable};
pub fn pread(fd: fd_t, buf: []u8, offset: u64) PReadError!usize {
if (buf.len == 0) return 0;
if (builtin.os.tag == .windows) {
return windows.ReadFile(fd, buf, offset, std.io.default_mode);
}
if (builtin.os.tag == .wasi and !builtin.link_libc) {
const iovs = [1]iovec{iovec{
.iov_base = buf.ptr,
.iov_len = buf.len,
}};
var nread: usize = undefined;
switch (wasi.fd_pread(fd, &iovs, iovs.len, offset, &nread)) {
.SUCCESS => return nread,
.INTR => unreachable,
.INVAL => unreachable,
.FAULT => unreachable,
.AGAIN => unreachable,
.BADF => return error.NotOpenForReading,
.IO => return error.InputOutput,
.ISDIR => return error.IsDir,
.NOBUFS => return error.SystemResources,
.NOMEM => return error.SystemResources,
.CONNRESET => return error.ConnectionResetByPeer,
.NXIO => return error.Unseekable,
.SPIPE => return error.Unseekable,
.OVERFLOW => return error.Unseekable,
.NOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
const max_count = switch (builtin.os.tag) {
.linux => 0x7ffff000,
.macos, .ios, .watchos, .tvos => math.maxInt(i32),
else => math.maxInt(isize),
};
const adjusted_len = @min(max_count, buf.len);
const pread_sym = if (builtin.os.tag == .linux and builtin.link_libc)
system.pread64
else
system.pread;
const ioffset = @bitCast(i64, offset);
while (true) {
const rc = pread_sym(fd, buf.ptr, adjusted_len, ioffset);
switch (errno(rc)) {
.SUCCESS => return @intCast(usize, rc),
.INTR => continue,
.INVAL => unreachable,
.FAULT => unreachable,
.AGAIN => return error.WouldBlock,
.BADF => return error.NotOpenForReading,
.IO => return error.InputOutput,
.ISDIR => return error.IsDir,
.NOBUFS => return error.SystemResources,
.NOMEM => return error.SystemResources,
.CONNRESET => return error.ConnectionResetByPeer,
.NXIO => return error.Unseekable,
.SPIPE => return error.Unseekable,
.OVERFLOW => return error.Unseekable,
else => |err| return unexpectedErrno(err),
}
}
}
pub const TruncateError = error{
FileTooBig,
InputOutput,
FileBusy,
AccessDenied,
} || UnexpectedError;
pub fn ftruncate(fd: fd_t, length: u64) TruncateError!void {
if (builtin.os.tag == .windows) {
var io_status_block: windows.IO_STATUS_BLOCK = undefined;
var eof_info = windows.FILE_END_OF_FILE_INFORMATION{
.EndOfFile = @bitCast(windows.LARGE_INTEGER, length),
};
const rc = windows.ntdll.NtSetInformationFile(
fd,
&io_status_block,
&eof_info,
@sizeOf(windows.FILE_END_OF_FILE_INFORMATION),
.FileEndOfFileInformation,
);
switch (rc) {
.SUCCESS => return,
.INVALID_HANDLE => unreachable,
.ACCESS_DENIED => return error.AccessDenied,
else => return windows.unexpectedStatus(rc),
}
}
if (builtin.os.tag == .wasi and !builtin.link_libc) {
switch (wasi.fd_filestat_set_size(fd, length)) {
.SUCCESS => return,
.INTR => unreachable,
.FBIG => return error.FileTooBig,
.IO => return error.InputOutput,
.PERM => return error.AccessDenied,
.TXTBSY => return error.FileBusy,
.BADF => unreachable,
.INVAL => unreachable,
.NOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
while (true) {
const ftruncate_sym = if (builtin.os.tag == .linux and builtin.link_libc)
system.ftruncate64
else
system.ftruncate;
const ilen = @bitCast(i64, length);
switch (errno(ftruncate_sym(fd, ilen))) {
.SUCCESS => return,
.INTR => continue,
.FBIG => return error.FileTooBig,
.IO => return error.InputOutput,
.PERM => return error.AccessDenied,
.TXTBSY => return error.FileBusy,
.BADF => unreachable,
.INVAL => unreachable,
else => |err| return unexpectedErrno(err),
}
}
}
pub fn preadv(fd: fd_t, iov: []const iovec, offset: u64) PReadError!usize {
const have_pread_but_not_preadv = switch (builtin.os.tag) {
.windows, .macos, .ios, .watchos, .tvos, .haiku => true,
else => false,
};
if (have_pread_but_not_preadv) {
if (iov.len == 0) return @as(usize, 0);
const first = iov[0];
return pread(fd, first.iov_base[0..first.iov_len], offset);
}
if (builtin.os.tag == .wasi and !builtin.link_libc) {
var nread: usize = undefined;
switch (wasi.fd_pread(fd, iov.ptr, iov.len, offset, &nread)) {
.SUCCESS => return nread,
.INTR => unreachable,
.INVAL => unreachable,
.FAULT => unreachable,
.AGAIN => unreachable,
.BADF => return error.NotOpenForReading,
.IO => return error.InputOutput,
.ISDIR => return error.IsDir,
.NOBUFS => return error.SystemResources,
.NOMEM => return error.SystemResources,
.NXIO => return error.Unseekable,
.SPIPE => return error.Unseekable,
.OVERFLOW => return error.Unseekable,
.NOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
const iov_count = math.cast(u31, iov.len) orelse math.maxInt(u31);
const preadv_sym = if (builtin.os.tag == .linux and builtin.link_libc)
system.preadv64
else
system.preadv;
const ioffset = @bitCast(i64, offset);
while (true) {
const rc = preadv_sym(fd, iov.ptr, iov_count, ioffset);
switch (errno(rc)) {
.SUCCESS => return @bitCast(usize, rc),
.INTR => continue,
.INVAL => unreachable,
.FAULT => unreachable,
.AGAIN => return error.WouldBlock,
.BADF => return error.NotOpenForReading,
.IO => return error.InputOutput,
.ISDIR => return error.IsDir,
.NOBUFS => return error.SystemResources,
.NOMEM => return error.SystemResources,
.NXIO => return error.Unseekable,
.SPIPE => return error.Unseekable,
.OVERFLOW => return error.Unseekable,
else => |err| return unexpectedErrno(err),
}
}
}
pub const WriteError = error{
DiskQuota,
FileTooBig,
InputOutput,
NoSpaceLeft,
DeviceBusy,
InvalidArgument,
AccessDenied,
BrokenPipe,
SystemResources,
OperationAborted,
NotOpenForWriting,
LockViolation,
WouldBlock,
ConnectionResetByPeer,
} || UnexpectedError;
pub fn write(fd: fd_t, bytes: []const u8) WriteError!usize {
if (bytes.len == 0) return 0;
if (builtin.os.tag == .windows) {
return windows.WriteFile(fd, bytes, null, std.io.default_mode);
}
if (builtin.os.tag == .wasi and !builtin.link_libc) {
const ciovs = [_]iovec_const{iovec_const{
.iov_base = bytes.ptr,
.iov_len = bytes.len,
}};
var nwritten: usize = undefined;
switch (wasi.fd_write(fd, &ciovs, ciovs.len, &nwritten)) {
.SUCCESS => return nwritten,
.INTR => unreachable,
.INVAL => unreachable,
.FAULT => unreachable,
.AGAIN => unreachable,
.BADF => return error.NotOpenForWriting,
.DESTADDRREQ => unreachable,
.DQUOT => return error.DiskQuota,
.FBIG => return error.FileTooBig,
.IO => return error.InputOutput,
.NOSPC => return error.NoSpaceLeft,
.PERM => return error.AccessDenied,
.PIPE => return error.BrokenPipe,
.NOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
const max_count = switch (builtin.os.tag) {
.linux => 0x7ffff000,
.macos, .ios, .watchos, .tvos => math.maxInt(i32),
else => math.maxInt(isize),
};
const adjusted_len = @min(max_count, bytes.len);
while (true) {
const rc = system.write(fd, bytes.ptr, adjusted_len);
switch (errno(rc)) {
.SUCCESS => return @intCast(usize, rc),
.INTR => continue,
.INVAL => return error.InvalidArgument,
.FAULT => unreachable,
.AGAIN => return error.WouldBlock,
.BADF => return error.NotOpenForWriting,
.DESTADDRREQ => unreachable,
.DQUOT => return error.DiskQuota,
.FBIG => return error.FileTooBig,
.IO => return error.InputOutput,
.NOSPC => return error.NoSpaceLeft,
.PERM => return error.AccessDenied,
.PIPE => return error.BrokenPipe,
.CONNRESET => return error.ConnectionResetByPeer,
.BUSY => return error.DeviceBusy,
else => |err| return unexpectedErrno(err),
}
}
}
pub fn writev(fd: fd_t, iov: []const iovec_const) WriteError!usize {
if (builtin.os.tag == .windows) {
if (iov.len == 0) return @as(usize, 0);
const first = iov[0];
return write(fd, first.iov_base[0..first.iov_len]);
}
if (builtin.os.tag == .wasi and !builtin.link_libc) {
var nwritten: usize = undefined;
switch (wasi.fd_write(fd, iov.ptr, iov.len, &nwritten)) {
.SUCCESS => return nwritten,
.INTR => unreachable,
.INVAL => unreachable,
.FAULT => unreachable,
.AGAIN => unreachable,
.BADF => return error.NotOpenForWriting,
.DESTADDRREQ => unreachable,
.DQUOT => return error.DiskQuota,
.FBIG => return error.FileTooBig,
.IO => return error.InputOutput,
.NOSPC => return error.NoSpaceLeft,
.PERM => return error.AccessDenied,
.PIPE => return error.BrokenPipe,
.NOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
const iov_count = if (iov.len > IOV_MAX) IOV_MAX else @intCast(u31, iov.len);
while (true) {
const rc = system.writev(fd, iov.ptr, iov_count);
switch (errno(rc)) {
.SUCCESS => return @intCast(usize, rc),
.INTR => continue,
.INVAL => return error.InvalidArgument,
.FAULT => unreachable,
.AGAIN => return error.WouldBlock,
.BADF => return error.NotOpenForWriting,
.DESTADDRREQ => unreachable,
.DQUOT => return error.DiskQuota,
.FBIG => return error.FileTooBig,
.IO => return error.InputOutput,
.NOSPC => return error.NoSpaceLeft,
.PERM => return error.AccessDenied,
.PIPE => return error.BrokenPipe,
.CONNRESET => return error.ConnectionResetByPeer,
.BUSY => return error.DeviceBusy,
else => |err| return unexpectedErrno(err),
}
}
}
pub const PWriteError = WriteError || error{Unseekable};
pub fn pwrite(fd: fd_t, bytes: []const u8, offset: u64) PWriteError!usize {
if (bytes.len == 0) return 0;
if (builtin.os.tag == .windows) {
return windows.WriteFile(fd, bytes, offset, std.io.default_mode);
}
if (builtin.os.tag == .wasi and !builtin.link_libc) {
const ciovs = [1]iovec_const{iovec_const{
.iov_base = bytes.ptr,
.iov_len = bytes.len,
}};
var nwritten: usize = undefined;
switch (wasi.fd_pwrite(fd, &ciovs, ciovs.len, offset, &nwritten)) {
.SUCCESS => return nwritten,
.INTR => unreachable,
.INVAL => unreachable,
.FAULT => unreachable,
.AGAIN => unreachable,
.BADF => return error.NotOpenForWriting,
.DESTADDRREQ => unreachable,
.DQUOT => return error.DiskQuota,
.FBIG => return error.FileTooBig,
.IO => return error.InputOutput,
.NOSPC => return error.NoSpaceLeft,
.PERM => return error.AccessDenied,
.PIPE => return error.BrokenPipe,
.NXIO => return error.Unseekable,
.SPIPE => return error.Unseekable,
.OVERFLOW => return error.Unseekable,
.NOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
const max_count = switch (builtin.os.tag) {
.linux => 0x7ffff000,
.macos, .ios, .watchos, .tvos => math.maxInt(i32),
else => math.maxInt(isize),
};
const adjusted_len = @min(max_count, bytes.len);
const pwrite_sym = if (builtin.os.tag == .linux and builtin.link_libc)
system.pwrite64
else
system.pwrite;
const ioffset = @bitCast(i64, offset);
while (true) {
const rc = pwrite_sym(fd, bytes.ptr, adjusted_len, ioffset);
switch (errno(rc)) {
.SUCCESS => return @intCast(usize, rc),
.INTR => continue,
.INVAL => return error.InvalidArgument,
.FAULT => unreachable,
.AGAIN => return error.WouldBlock,
.BADF => return error.NotOpenForWriting,
.DESTADDRREQ => unreachable,
.DQUOT => return error.DiskQuota,
.FBIG => return error.FileTooBig,
.IO => return error.InputOutput,
.NOSPC => return error.NoSpaceLeft,
.PERM => return error.AccessDenied,
.PIPE => return error.BrokenPipe,
.NXIO => return error.Unseekable,
.SPIPE => return error.Unseekable,
.OVERFLOW => return error.Unseekable,
.BUSY => return error.DeviceBusy,
else => |err| return unexpectedErrno(err),
}
}
}
pub fn pwritev(fd: fd_t, iov: []const iovec_const, offset: u64) PWriteError!usize {
const have_pwrite_but_not_pwritev = switch (builtin.os.tag) {
.windows, .macos, .ios, .watchos, .tvos, .haiku => true,
else => false,
};
if (have_pwrite_but_not_pwritev) {
if (iov.len == 0) return @as(usize, 0);
const first = iov[0];
return pwrite(fd, first.iov_base[0..first.iov_len], offset);
}
if (builtin.os.tag == .wasi and !builtin.link_libc) {
var nwritten: usize = undefined;
switch (wasi.fd_pwrite(fd, iov.ptr, iov.len, offset, &nwritten)) {
.SUCCESS => return nwritten,
.INTR => unreachable,
.INVAL => unreachable,
.FAULT => unreachable,
.AGAIN => unreachable,
.BADF => return error.NotOpenForWriting,
.DESTADDRREQ => unreachable,
.DQUOT => return error.DiskQuota,
.FBIG => return error.FileTooBig,
.IO => return error.InputOutput,
.NOSPC => return error.NoSpaceLeft,
.PERM => return error.AccessDenied,
.PIPE => return error.BrokenPipe,
.NXIO => return error.Unseekable,
.SPIPE => return error.Unseekable,
.OVERFLOW => return error.Unseekable,
.NOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
const pwritev_sym = if (builtin.os.tag == .linux and builtin.link_libc)
system.pwritev64
else
system.pwritev;
const iov_count = if (iov.len > IOV_MAX) IOV_MAX else @intCast(u31, iov.len);
const ioffset = @bitCast(i64, offset);
while (true) {
const rc = pwritev_sym(fd, iov.ptr, iov_count, ioffset);
switch (errno(rc)) {
.SUCCESS => return @intCast(usize, rc),
.INTR => continue,
.INVAL => return error.InvalidArgument,
.FAULT => unreachable,
.AGAIN => return error.WouldBlock,
.BADF => return error.NotOpenForWriting,
.DESTADDRREQ => unreachable,
.DQUOT => return error.DiskQuota,
.FBIG => return error.FileTooBig,
.IO => return error.InputOutput,
.NOSPC => return error.NoSpaceLeft,
.PERM => return error.AccessDenied,
.PIPE => return error.BrokenPipe,
.NXIO => return error.Unseekable,
.SPIPE => return error.Unseekable,
.OVERFLOW => return error.Unseekable,
.BUSY => return error.DeviceBusy,
else => |err| return unexpectedErrno(err),
}
}
}
pub const OpenError = error{
InvalidHandle,
AccessDenied,
SymLinkLoop,
ProcessFdQuotaExceeded,
SystemFdQuotaExceeded,
NoDevice,
FileNotFound,
NameTooLong,
SystemResources,
FileTooBig,
IsDir,
NoSpaceLeft,
NotDir,
PathAlreadyExists,
DeviceBusy,
FileLocksNotSupported,
BadPathName,
InvalidUtf8,
FileBusy,
WouldBlock,
} || UnexpectedError;
pub fn open(file_path: []const u8, flags: u32, perm: mode_t) OpenError!fd_t {
if (builtin.os.tag == .windows) {
const file_path_w = try windows.sliceToPrefixedFileW(file_path);
return openW(file_path_w.span(), flags, perm);
} else if (builtin.os.tag == .wasi and !builtin.link_libc) {
return openat(wasi.AT.FDCWD, file_path, flags, perm);
}
const file_path_c = try toPosixPath(file_path);
return openZ(&file_path_c, flags, perm);
}
pub fn openZ(file_path: [*:0]const u8, flags: u32, perm: mode_t) OpenError!fd_t {
if (builtin.os.tag == .windows) {
const file_path_w = try windows.cStrToPrefixedFileW(file_path);
return openW(file_path_w.span(), flags, perm);
} else if (builtin.os.tag == .wasi and !builtin.link_libc) {
return open(mem.sliceTo(file_path, 0), flags, perm);
}
const open_sym = if (builtin.os.tag == .linux and builtin.link_libc)
system.open64
else
system.open;
while (true) {
const rc = open_sym(file_path, flags, perm);
switch (errno(rc)) {
.SUCCESS => return @intCast(fd_t, rc),
.INTR => continue,
.FAULT => unreachable,
.INVAL => unreachable,
.ACCES => return error.AccessDenied,
.FBIG => return error.FileTooBig,
.OVERFLOW => return error.FileTooBig,
.ISDIR => return error.IsDir,
.LOOP => return error.SymLinkLoop,
.MFILE => return error.ProcessFdQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NFILE => return error.SystemFdQuotaExceeded,
.NODEV => return error.NoDevice,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.NOTDIR => return error.NotDir,
.PERM => return error.AccessDenied,
.EXIST => return error.PathAlreadyExists,
.BUSY => return error.DeviceBusy,
else => |err| return unexpectedErrno(err),
}
}
}
fn openOptionsFromFlagsWindows(flags: u32) windows.OpenFileOptions {
const w = windows;
var access_mask: w.ULONG = w.READ_CONTROL | w.FILE_WRITE_ATTRIBUTES | w.SYNCHRONIZE;
if (flags & O.RDWR != 0) {
access_mask |= w.GENERIC_READ | w.GENERIC_WRITE;
} else if (flags & O.WRONLY != 0) {
access_mask |= w.GENERIC_WRITE;
} else {
access_mask |= w.GENERIC_READ | w.GENERIC_WRITE;
}
const filter: windows.OpenFileOptions.Filter = if (flags & O.DIRECTORY != 0) .dir_only else .file_only;
const follow_symlinks: bool = flags & O.NOFOLLOW == 0;
const creation: w.ULONG = blk: {
if (flags & O.CREAT != 0) {
if (flags & O.EXCL != 0) {
break :blk w.FILE_CREATE;
}
}
break :blk w.FILE_OPEN;
};
return .{
.access_mask = access_mask,
.io_mode = .blocking,
.creation = creation,
.filter = filter,
.follow_symlinks = follow_symlinks,
};
}
pub fn openW(file_path_w: []const u16, flags: u32, perm: mode_t) OpenError!fd_t {
_ = perm;
var options = openOptionsFromFlagsWindows(flags);
options.dir = std.fs.cwd().fd;
return windows.OpenFile(file_path_w, options) catch |err| switch (err) {
error.WouldBlock => unreachable,
error.PipeBusy => unreachable,
else => |e| return e,
};
}
pub fn openat(dir_fd: fd_t, file_path: []const u8, flags: u32, mode: mode_t) OpenError!fd_t {
if (builtin.os.tag == .windows) {
const file_path_w = try windows.sliceToPrefixedFileW(file_path);
return openatW(dir_fd, file_path_w.span(), flags, mode);
} else if (builtin.os.tag == .wasi and !builtin.link_libc) {
const opts = try openOptionsFromFlagsWasi(dir_fd, flags);
const fd = try openatWasi(
dir_fd,
file_path,
opts.lookup_flags,
opts.oflags,
opts.fs_flags,
opts.fs_rights_base,
opts.fs_rights_inheriting,
);
errdefer close(fd);
if (flags & O.WRONLY != 0) {
const info = try fstat(fd);
if (info.filetype == .DIRECTORY)
return error.IsDir;
}
return fd;
}
const file_path_c = try toPosixPath(file_path);
return openatZ(dir_fd, &file_path_c, flags, mode);
}
const WasiOpenOptions = struct {
oflags: wasi.oflags_t,
lookup_flags: wasi.lookupflags_t,
fs_rights_base: wasi.rights_t,
fs_rights_inheriting: wasi.rights_t,
fs_flags: wasi.fdflags_t,
};
fn openOptionsFromFlagsWasi(fd: fd_t, oflag: u32) OpenError!WasiOpenOptions {
const w = std.os.wasi;
var fsb_cur: wasi.fdstat_t = undefined;
_ = switch (w.fd_fdstat_get(fd, &fsb_cur)) {
.SUCCESS => .{},
.BADF => return error.InvalidHandle,
else => |err| return unexpectedErrno(err),
};
var rights: w.rights_t = 0;
if (oflag & O.RDONLY != 0) {
rights |= w.RIGHT.FD_READ | w.RIGHT.FD_READDIR;
}
if (oflag & O.WRONLY != 0) {
rights |= w.RIGHT.FD_DATASYNC | w.RIGHT.FD_WRITE |
w.RIGHT.FD_ALLOCATE | w.RIGHT.FD_FILESTAT_SET_SIZE;
}
rights |= ~(w.RIGHT.FD_DATASYNC | w.RIGHT.FD_READ |
w.RIGHT.FD_WRITE | w.RIGHT.FD_ALLOCATE |
w.RIGHT.FD_READDIR | w.RIGHT.FD_FILESTAT_SET_SIZE);
rights &= fsb_cur.fs_rights_inheriting;
return WasiOpenOptions{
.oflags = @truncate(w.oflags_t, (oflag >> 12)) & 0xfff,
.lookup_flags = if (oflag & O.NOFOLLOW == 0) w.LOOKUP_SYMLINK_FOLLOW else 0,
.fs_rights_base = rights,
.fs_rights_inheriting = fsb_cur.fs_rights_inheriting,
.fs_flags = @truncate(w.fdflags_t, oflag & 0xfff),
};
}
pub fn openatWasi(
dir_fd: fd_t,
file_path: []const u8,
lookup_flags: lookupflags_t,
oflags: oflags_t,
fdflags: fdflags_t,
base: rights_t,
inheriting: rights_t,
) OpenError!fd_t {
while (true) {
var fd: fd_t = undefined;
switch (wasi.path_open(dir_fd, lookup_flags, file_path.ptr, file_path.len, oflags, base, inheriting, fdflags, &fd)) {
.SUCCESS => return fd,
.INTR => continue,
.FAULT => unreachable,
.INVAL => unreachable,
.ACCES => return error.AccessDenied,
.FBIG => return error.FileTooBig,
.OVERFLOW => return error.FileTooBig,
.ISDIR => return error.IsDir,
.LOOP => return error.SymLinkLoop,
.MFILE => return error.ProcessFdQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NFILE => return error.SystemFdQuotaExceeded,
.NODEV => return error.NoDevice,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.NOTDIR => return error.NotDir,
.PERM => return error.AccessDenied,
.EXIST => return error.PathAlreadyExists,
.BUSY => return error.DeviceBusy,
.NOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
}
pub fn openatZ(dir_fd: fd_t, file_path: [*:0]const u8, flags: u32, mode: mode_t) OpenError!fd_t {
if (builtin.os.tag == .windows) {
const file_path_w = try windows.cStrToPrefixedFileW(file_path);
return openatW(dir_fd, file_path_w.span(), flags, mode);
} else if (builtin.os.tag == .wasi and !builtin.link_libc) {
return openat(dir_fd, mem.sliceTo(file_path, 0), flags, mode);
}
const openat_sym = if (builtin.os.tag == .linux and builtin.link_libc)
system.openat64
else
system.openat;
while (true) {
const rc = openat_sym(dir_fd, file_path, flags, mode);
switch (errno(rc)) {
.SUCCESS => return @intCast(fd_t, rc),
.INTR => continue,
.FAULT => unreachable,
.INVAL => unreachable,
.BADF => unreachable,
.ACCES => return error.AccessDenied,
.FBIG => return error.FileTooBig,
.OVERFLOW => return error.FileTooBig,
.ISDIR => return error.IsDir,
.LOOP => return error.SymLinkLoop,
.MFILE => return error.ProcessFdQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NFILE => return error.SystemFdQuotaExceeded,
.NODEV => return error.NoDevice,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.NOTDIR => return error.NotDir,
.PERM => return error.AccessDenied,
.EXIST => return error.PathAlreadyExists,
.BUSY => return error.DeviceBusy,
.OPNOTSUPP => return error.FileLocksNotSupported,
.AGAIN => return error.WouldBlock,
.TXTBSY => return error.FileBusy,
else => |err| return unexpectedErrno(err),
}
}
}
pub fn openatW(dir_fd: fd_t, file_path_w: []const u16, flags: u32, mode: mode_t) OpenError!fd_t {
_ = mode;
var options = openOptionsFromFlagsWindows(flags);
options.dir = dir_fd;
return windows.OpenFile(file_path_w, options) catch |err| switch (err) {
error.WouldBlock => unreachable,
error.PipeBusy => unreachable,
else => |e| return e,
};
}
pub fn dup(old_fd: fd_t) !fd_t {
const rc = system.dup(old_fd);
return switch (errno(rc)) {
.SUCCESS => return @intCast(fd_t, rc),
.MFILE => error.ProcessFdQuotaExceeded,
.BADF => unreachable,
else => |err| return unexpectedErrno(err),
};
}
pub fn dup2(old_fd: fd_t, new_fd: fd_t) !void {
while (true) {
switch (errno(system.dup2(old_fd, new_fd))) {
.SUCCESS => return,
.BUSY, .INTR => continue,
.MFILE => return error.ProcessFdQuotaExceeded,
.INVAL => unreachable,
.BADF => unreachable,
else => |err| return unexpectedErrno(err),
}
}
}
pub const ExecveError = error{
SystemResources,
AccessDenied,
InvalidExe,
FileSystem,
IsDir,
FileNotFound,
NotDir,
FileBusy,
ProcessFdQuotaExceeded,
SystemFdQuotaExceeded,
NameTooLong,
} || UnexpectedError;
pub fn execveZ(
path: [*:0]const u8,
child_argv: [*:null]const ?[*:0]const u8,
envp: [*:null]const ?[*:0]const u8,
) ExecveError {
switch (errno(system.execve(path, child_argv, envp))) {
.SUCCESS => unreachable,
.FAULT => unreachable,
.@"2BIG" => return error.SystemResources,
.MFILE => return error.ProcessFdQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NFILE => return error.SystemFdQuotaExceeded,
.NOMEM => return error.SystemResources,
.ACCES => return error.AccessDenied,
.PERM => return error.AccessDenied,
.INVAL => return error.InvalidExe,
.NOEXEC => return error.InvalidExe,
.IO => return error.FileSystem,
.LOOP => return error.FileSystem,
.ISDIR => return error.IsDir,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.NotDir,
.TXTBSY => return error.FileBusy,
else => |err| switch (builtin.os.tag) {
.macos, .ios, .tvos, .watchos => switch (err) {
.BADEXEC => return error.InvalidExe,
.BADARCH => return error.InvalidExe,
else => return unexpectedErrno(err),
},
.linux, .solaris => switch (err) {
.LIBBAD => return error.InvalidExe,
else => return unexpectedErrno(err),
},
else => return unexpectedErrno(err),
},
}
}
pub const Arg0Expand = enum {
expand,
no_expand,
};
pub fn execvpeZ_expandArg0(
comptime arg0_expand: Arg0Expand,
file: [*:0]const u8,
child_argv: switch (arg0_expand) {
.expand => [*:null]?[*:0]const u8,
.no_expand => [*:null]const ?[*:0]const u8,
},
envp: [*:null]const ?[*:0]const u8,
) ExecveError {
const file_slice = mem.sliceTo(file, 0);
if (mem.indexOfScalar(u8, file_slice, '/') != null) return execveZ(file, child_argv, envp);
const PATH = getenvZ("PATH") orelse "/usr/local/bin:/bin/:/usr/bin";
var path_buf: [MAX_PATH_BYTES]u8 = undefined;
var it = mem.tokenize(u8, PATH, ":");
var seen_eacces = false;
var err: ExecveError = error.FileNotFound;
const prev_arg0 = child_argv[0];
defer switch (arg0_expand) {
.expand => child_argv[0] = prev_arg0,
.no_expand => {},
};
while (it.next()) |search_path| {
const path_len = search_path.len + file_slice.len + 1;
if (path_buf.len < path_len + 1) return error.NameTooLong;
mem.copy(u8, &path_buf, search_path);
path_buf[search_path.len] = '/';
mem.copy(u8, path_buf[search_path.len + 1 ..], file_slice);
path_buf[path_len] = 0;
const full_path = path_buf[0..path_len :0].ptr;
switch (arg0_expand) {
.expand => child_argv[0] = full_path,
.no_expand => {},
}
err = execveZ(full_path, child_argv, envp);
switch (err) {
error.AccessDenied => seen_eacces = true,
error.FileNotFound, error.NotDir => {},
else => |e| return e,
}
}
if (seen_eacces) return error.AccessDenied;
return err;
}
pub fn execvpeZ(
file: [*:0]const u8,
argv_ptr: [*:null]const ?[*:0]const u8,
envp: [*:null]const ?[*:0]const u8,
) ExecveError {
return execvpeZ_expandArg0(.no_expand, file, argv_ptr, envp);
}
pub fn getenv(key: []const u8) ?[]const u8 {
if (builtin.link_libc) {
var small_key_buf: [64]u8 = undefined;
if (key.len < small_key_buf.len) {
mem.copy(u8, &small_key_buf, key);
small_key_buf[key.len] = 0;
const key0 = small_key_buf[0..key.len :0];
return getenvZ(key0);
}
var ptr = std.c.environ;
while (ptr[0]) |line| : (ptr += 1) {
var line_i: usize = 0;
while (line[line_i] != 0 and line[line_i] != '=') : (line_i += 1) {}
const this_key = line[0..line_i];
if (!mem.eql(u8, this_key, key)) continue;
var end_i: usize = line_i;
while (line[end_i] != 0) : (end_i += 1) {}
const value = line[line_i + 1 .. end_i];
return value;
}
return null;
}
if (builtin.os.tag == .windows) {
@compileError("std.os.getenv is unavailable for Windows because environment string is in WTF-16 format. See std.process.getEnvVarOwned for cross-platform API or std.os.getenvW for Windows-specific API.");
}
if (std.start.simplified_logic) return null;
for (environ) |ptr| {
var line_i: usize = 0;
while (ptr[line_i] != 0 and ptr[line_i] != '=') : (line_i += 1) {}
const this_key = ptr[0..line_i];
if (!mem.eql(u8, key, this_key)) continue;
var end_i: usize = line_i;
while (ptr[end_i] != 0) : (end_i += 1) {}
const this_value = ptr[line_i + 1 .. end_i];
return this_value;
}
return null;
}
pub fn getenvZ(key: [*:0]const u8) ?[]const u8 {
if (builtin.link_libc) {
const value = system.getenv(key) orelse return null;
return mem.sliceTo(value, 0);
}
if (builtin.os.tag == .windows) {
@compileError("std.os.getenvZ is unavailable for Windows because environment string is in WTF-16 format. See std.process.getEnvVarOwned for cross-platform API or std.os.getenvW for Windows-specific API.");
}
return getenv(mem.sliceTo(key, 0));
}
pub fn getenvW(key: [*:0]const u16) ?[:0]const u16 {
if (builtin.os.tag != .windows) {
@compileError("std.os.getenvW is a Windows-only API");
}
const key_slice = mem.sliceTo(key, 0);
const ptr = windows.peb().ProcessParameters.Environment;
var i: usize = 0;
while (ptr[i] != 0) {
const key_start = i;
if (ptr[key_start] == '=') i += 1;
while (ptr[i] != 0 and ptr[i] != '=') : (i += 1) {}
const this_key = ptr[key_start..i];
if (ptr[i] == '=') i += 1;
const value_start = i;
while (ptr[i] != 0) : (i += 1) {}
const this_value = ptr[value_start..i :0];
if (windows.eqlIgnoreCaseWTF16(key_slice, this_key)) {
return this_value;
}
i += 1;
}
return null;
}
pub const GetCwdError = error{
NameTooLong,
CurrentWorkingDirectoryUnlinked,
} || UnexpectedError;
pub fn getcwd(out_buffer: []u8) GetCwdError![]u8 {
if (builtin.os.tag == .windows) {
return windows.GetCurrentDirectory(out_buffer);
} else if (builtin.os.tag == .wasi and !builtin.link_libc) {
const path = ".";
if (out_buffer.len < path.len) return error.NameTooLong;
std.mem.copy(u8, out_buffer, path);
return out_buffer[0..path.len];
}
const err = if (builtin.link_libc) blk: {
const c_err = if (std.c.getcwd(out_buffer.ptr, out_buffer.len)) |_| 0 else std.c._errno().*;
break :blk @intToEnum(E, c_err);
} else blk: {
break :blk errno(system.getcwd(out_buffer.ptr, out_buffer.len));
};
switch (err) {
.SUCCESS => return mem.sliceTo(out_buffer, 0),
.FAULT => unreachable,
.INVAL => unreachable,
.NOENT => return error.CurrentWorkingDirectoryUnlinked,
.RANGE => return error.NameTooLong,
else => return unexpectedErrno(err),
}
}
pub const SymLinkError = error{
AccessDenied,
DiskQuota,
PathAlreadyExists,
FileSystem,
SymLinkLoop,
FileNotFound,
SystemResources,
NoSpaceLeft,
ReadOnlyFileSystem,
NotDir,
NameTooLong,
InvalidUtf8,
BadPathName,
} || UnexpectedError;
pub fn symlink(target_path: []const u8, sym_link_path: []const u8) SymLinkError!void {
if (builtin.os.tag == .windows) {
@compileError("symlink is not supported on Windows; use std.os.windows.CreateSymbolicLink instead");
} else if (builtin.os.tag == .wasi and !builtin.link_libc) {
return symlinkat(target_path, wasi.AT.FDCWD, sym_link_path);
}
const target_path_c = try toPosixPath(target_path);
const sym_link_path_c = try toPosixPath(sym_link_path);
return symlinkZ(&target_path_c, &sym_link_path_c);
}
pub fn symlinkZ(target_path: [*:0]const u8, sym_link_path: [*:0]const u8) SymLinkError!void {
if (builtin.os.tag == .windows) {
@compileError("symlink is not supported on Windows; use std.os.windows.CreateSymbolicLink instead");
} else if (builtin.os.tag == .wasi and !builtin.link_libc) {
return symlinkatZ(target_path, fs.cwd().fd, sym_link_path);
}
switch (errno(system.symlink(target_path, sym_link_path))) {
.SUCCESS => return,
.FAULT => unreachable,
.INVAL => unreachable,
.ACCES => return error.AccessDenied,
.PERM => return error.AccessDenied,
.DQUOT => return error.DiskQuota,
.EXIST => return error.PathAlreadyExists,
.IO => return error.FileSystem,
.LOOP => return error.SymLinkLoop,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.NotDir,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.ROFS => return error.ReadOnlyFileSystem,
else => |err| return unexpectedErrno(err),
}
}
pub fn symlinkat(target_path: []const u8, newdirfd: fd_t, sym_link_path: []const u8) SymLinkError!void {
if (builtin.os.tag == .windows) {
@compileError("symlinkat is not supported on Windows; use std.os.windows.CreateSymbolicLink instead");
} else if (builtin.os.tag == .wasi and !builtin.link_libc) {
return symlinkatWasi(target_path, newdirfd, sym_link_path);
}
const target_path_c = try toPosixPath(target_path);
const sym_link_path_c = try toPosixPath(sym_link_path);
return symlinkatZ(&target_path_c, newdirfd, &sym_link_path_c);
}
pub fn symlinkatWasi(target_path: []const u8, newdirfd: fd_t, sym_link_path: []const u8) SymLinkError!void {
switch (wasi.path_symlink(target_path.ptr, target_path.len, newdirfd, sym_link_path.ptr, sym_link_path.len)) {
.SUCCESS => {},
.FAULT => unreachable,
.INVAL => unreachable,
.BADF => unreachable,
.ACCES => return error.AccessDenied,
.PERM => return error.AccessDenied,
.DQUOT => return error.DiskQuota,
.EXIST => return error.PathAlreadyExists,
.IO => return error.FileSystem,
.LOOP => return error.SymLinkLoop,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.NotDir,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.ROFS => return error.ReadOnlyFileSystem,
.NOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
pub fn symlinkatZ(target_path: [*:0]const u8, newdirfd: fd_t, sym_link_path: [*:0]const u8) SymLinkError!void {
if (builtin.os.tag == .windows) {
@compileError("symlinkat is not supported on Windows; use std.os.windows.CreateSymbolicLink instead");
} else if (builtin.os.tag == .wasi and !builtin.link_libc) {
return symlinkat(mem.sliceTo(target_path, 0), newdirfd, mem.sliceTo(sym_link_path, 0));
}
switch (errno(system.symlinkat(target_path, newdirfd, sym_link_path))) {
.SUCCESS => return,
.FAULT => unreachable,
.INVAL => unreachable,
.ACCES => return error.AccessDenied,
.PERM => return error.AccessDenied,
.DQUOT => return error.DiskQuota,
.EXIST => return error.PathAlreadyExists,
.IO => return error.FileSystem,
.LOOP => return error.SymLinkLoop,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.NotDir,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.ROFS => return error.ReadOnlyFileSystem,
else => |err| return unexpectedErrno(err),
}
}
pub const LinkError = UnexpectedError || error{
AccessDenied,
DiskQuota,
PathAlreadyExists,
FileSystem,
SymLinkLoop,
LinkQuotaExceeded,
NameTooLong,
FileNotFound,
SystemResources,
NoSpaceLeft,
ReadOnlyFileSystem,
NotSameFileSystem,
};
pub fn linkZ(oldpath: [*:0]const u8, newpath: [*:0]const u8, flags: i32) LinkError!void {
if (builtin.os.tag == .wasi and !builtin.link_libc) {
return link(mem.sliceTo(oldpath, 0), mem.sliceTo(newpath, 0), flags);
}
switch (errno(system.link(oldpath, newpath, flags))) {
.SUCCESS => return,
.ACCES => return error.AccessDenied,
.DQUOT => return error.DiskQuota,
.EXIST => return error.PathAlreadyExists,
.FAULT => unreachable,
.IO => return error.FileSystem,
.LOOP => return error.SymLinkLoop,
.MLINK => return error.LinkQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.PERM => return error.AccessDenied,
.ROFS => return error.ReadOnlyFileSystem,
.XDEV => return error.NotSameFileSystem,
.INVAL => unreachable,
else => |err| return unexpectedErrno(err),
}
}
pub fn link(oldpath: []const u8, newpath: []const u8, flags: i32) LinkError!void {
if (builtin.os.tag == .wasi and !builtin.link_libc) {
return linkat(wasi.AT.FDCWD, oldpath, wasi.AT.FDCWD, newpath, flags) catch |err| switch (err) {
error.NotDir => unreachable,
else => |e| return e,
};
}
const old = try toPosixPath(oldpath);
const new = try toPosixPath(newpath);
return try linkZ(&old, &new, flags);
}
pub const LinkatError = LinkError || error{NotDir};
pub fn linkatZ(
olddir: fd_t,
oldpath: [*:0]const u8,
newdir: fd_t,
newpath: [*:0]const u8,
flags: i32,
) LinkatError!void {
if (builtin.os.tag == .wasi and !builtin.link_libc) {
return linkat(olddir, mem.sliceTo(oldpath, 0), newdir, mem.sliceTo(newpath, 0), flags);
}
switch (errno(system.linkat(olddir, oldpath, newdir, newpath, flags))) {
.SUCCESS => return,
.ACCES => return error.AccessDenied,
.DQUOT => return error.DiskQuota,
.EXIST => return error.PathAlreadyExists,
.FAULT => unreachable,
.IO => return error.FileSystem,
.LOOP => return error.SymLinkLoop,
.MLINK => return error.LinkQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.NOTDIR => return error.NotDir,
.PERM => return error.AccessDenied,
.ROFS => return error.ReadOnlyFileSystem,
.XDEV => return error.NotSameFileSystem,
.INVAL => unreachable,
else => |err| return unexpectedErrno(err),
}
}
pub fn linkat(
olddir: fd_t,
oldpath: []const u8,
newdir: fd_t,
newpath: []const u8,
flags: i32,
) LinkatError!void {
if (builtin.os.tag == .wasi and !builtin.link_libc) {
const old: RelativePathWasi = .{ .dir_fd = olddir, .relative_path = oldpath };
const new: RelativePathWasi = .{ .dir_fd = newdir, .relative_path = newpath };
return linkatWasi(old, new, flags);
}
const old = try toPosixPath(oldpath);
const new = try toPosixPath(newpath);
return try linkatZ(olddir, &old, newdir, &new, flags);
}
pub fn linkatWasi(old: RelativePathWasi, new: RelativePathWasi, flags: i32) LinkatError!void {
var old_flags: wasi.lookupflags_t = 0;
if (flags & linux.AT.SYMLINK_FOLLOW != 0) old_flags |= wasi.LOOKUP_SYMLINK_FOLLOW;
switch (wasi.path_link(old.dir_fd, old_flags, old.relative_path.ptr, old.relative_path.len, new.dir_fd, new.relative_path.ptr, new.relative_path.len)) {
.SUCCESS => return,
.ACCES => return error.AccessDenied,
.DQUOT => return error.DiskQuota,
.EXIST => return error.PathAlreadyExists,
.FAULT => unreachable,
.IO => return error.FileSystem,
.LOOP => return error.SymLinkLoop,
.MLINK => return error.LinkQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.NOTDIR => return error.NotDir,
.PERM => return error.AccessDenied,
.ROFS => return error.ReadOnlyFileSystem,
.XDEV => return error.NotSameFileSystem,
.INVAL => unreachable,
else => |err| return unexpectedErrno(err),
}
}
pub const UnlinkError = error{
FileNotFound,
AccessDenied,
FileBusy,
FileSystem,
IsDir,
SymLinkLoop,
NameTooLong,
NotDir,
SystemResources,
ReadOnlyFileSystem,
InvalidUtf8,
BadPathName,
} || UnexpectedError;
pub fn unlink(file_path: []const u8) UnlinkError!void {
if (builtin.os.tag == .wasi and !builtin.link_libc) {
return unlinkat(wasi.AT.FDCWD, file_path, 0) catch |err| switch (err) {
error.DirNotEmpty => unreachable,
else => |e| return e,
};
} else if (builtin.os.tag == .windows) {
const file_path_w = try windows.sliceToPrefixedFileW(file_path);
return unlinkW(file_path_w.span());
} else {
const file_path_c = try toPosixPath(file_path);
return unlinkZ(&file_path_c);
}
}
pub fn unlinkZ(file_path: [*:0]const u8) UnlinkError!void {
if (builtin.os.tag == .windows) {
const file_path_w = try windows.cStrToPrefixedFileW(file_path);
return unlinkW(file_path_w.span());
} else if (builtin.os.tag == .wasi and !builtin.link_libc) {
return unlink(mem.sliceTo(file_path, 0));
}
switch (errno(system.unlink(file_path))) {
.SUCCESS => return,
.ACCES => return error.AccessDenied,
.PERM => return error.AccessDenied,
.BUSY => return error.FileBusy,
.FAULT => unreachable,
.INVAL => unreachable,
.IO => return error.FileSystem,
.ISDIR => return error.IsDir,
.LOOP => return error.SymLinkLoop,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.NotDir,
.NOMEM => return error.SystemResources,
.ROFS => return error.ReadOnlyFileSystem,
else => |err| return unexpectedErrno(err),
}
}
pub fn unlinkW(file_path_w: []const u16) UnlinkError!void {
return windows.DeleteFile(file_path_w, .{ .dir = std.fs.cwd().fd });
}
pub const UnlinkatError = UnlinkError || error{
DirNotEmpty,
};
pub fn unlinkat(dirfd: fd_t, file_path: []const u8, flags: u32) UnlinkatError!void {
if (builtin.os.tag == .windows) {
const file_path_w = try windows.sliceToPrefixedFileW(file_path);
return unlinkatW(dirfd, file_path_w.span(), flags);
} else if (builtin.os.tag == .wasi and !builtin.link_libc) {
return unlinkatWasi(dirfd, file_path, flags);
} else {
const file_path_c = try toPosixPath(file_path);
return unlinkatZ(dirfd, &file_path_c, flags);
}
}
pub fn unlinkatWasi(dirfd: fd_t, file_path: []const u8, flags: u32) UnlinkatError!void {
const remove_dir = (flags & AT.REMOVEDIR) != 0;
const res = if (remove_dir)
wasi.path_remove_directory(dirfd, file_path.ptr, file_path.len)
else
wasi.path_unlink_file(dirfd, file_path.ptr, file_path.len);
switch (res) {
.SUCCESS => return,
.ACCES => return error.AccessDenied,
.PERM => return error.AccessDenied,
.BUSY => return error.FileBusy,
.FAULT => unreachable,
.IO => return error.FileSystem,
.ISDIR => return error.IsDir,
.LOOP => return error.SymLinkLoop,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.NotDir,
.NOMEM => return error.SystemResources,
.ROFS => return error.ReadOnlyFileSystem,
.NOTEMPTY => return error.DirNotEmpty,
.NOTCAPABLE => return error.AccessDenied,
.INVAL => unreachable,
.BADF => unreachable,
else => |err| return unexpectedErrno(err),
}
}
pub fn unlinkatZ(dirfd: fd_t, file_path_c: [*:0]const u8, flags: u32) UnlinkatError!void {
if (builtin.os.tag == .windows) {
const file_path_w = try windows.cStrToPrefixedFileW(file_path_c);
return unlinkatW(dirfd, file_path_w.span(), flags);
} else if (builtin.os.tag == .wasi and !builtin.link_libc) {
return unlinkat(dirfd, mem.sliceTo(file_path_c, 0), flags);
}
switch (errno(system.unlinkat(dirfd, file_path_c, flags))) {
.SUCCESS => return,
.ACCES => return error.AccessDenied,
.PERM => return error.AccessDenied,
.BUSY => return error.FileBusy,
.FAULT => unreachable,
.IO => return error.FileSystem,
.ISDIR => return error.IsDir,
.LOOP => return error.SymLinkLoop,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.NotDir,
.NOMEM => return error.SystemResources,
.ROFS => return error.ReadOnlyFileSystem,
.EXIST => return error.DirNotEmpty,
.NOTEMPTY => return error.DirNotEmpty,
.INVAL => unreachable,
.BADF => unreachable,
else => |err| return unexpectedErrno(err),
}
}
pub fn unlinkatW(dirfd: fd_t, sub_path_w: []const u16, flags: u32) UnlinkatError!void {
const remove_dir = (flags & AT.REMOVEDIR) != 0;
return windows.DeleteFile(sub_path_w, .{ .dir = dirfd, .remove_dir = remove_dir });
}
pub const RenameError = error{
AccessDenied,
FileBusy,
DiskQuota,
IsDir,
SymLinkLoop,
LinkQuotaExceeded,
NameTooLong,
FileNotFound,
NotDir,
SystemResources,
NoSpaceLeft,
PathAlreadyExists,
ReadOnlyFileSystem,
RenameAcrossMountPoints,
InvalidUtf8,
BadPathName,
NoDevice,
SharingViolation,
PipeBusy,
} || UnexpectedError;
pub fn rename(old_path: []const u8, new_path: []const u8) RenameError!void {
if (builtin.os.tag == .wasi and !builtin.link_libc) {
return renameat(wasi.AT.FDCWD, old_path, wasi.AT.FDCWD, new_path);
} else if (builtin.os.tag == .windows) {
const old_path_w = try windows.sliceToPrefixedFileW(old_path);
const new_path_w = try windows.sliceToPrefixedFileW(new_path);
return renameW(old_path_w.span().ptr, new_path_w.span().ptr);
} else {
const old_path_c = try toPosixPath(old_path);
const new_path_c = try toPosixPath(new_path);
return renameZ(&old_path_c, &new_path_c);
}
}
pub fn renameZ(old_path: [*:0]const u8, new_path: [*:0]const u8) RenameError!void {
if (builtin.os.tag == .windows) {
const old_path_w = try windows.cStrToPrefixedFileW(old_path);
const new_path_w = try windows.cStrToPrefixedFileW(new_path);
return renameW(old_path_w.span().ptr, new_path_w.span().ptr);
} else if (builtin.os.tag == .wasi and !builtin.link_libc) {
return rename(mem.sliceTo(old_path, 0), mem.sliceTo(new_path, 0));
}
switch (errno(system.rename(old_path, new_path))) {
.SUCCESS => return,
.ACCES => return error.AccessDenied,
.PERM => return error.AccessDenied,
.BUSY => return error.FileBusy,
.DQUOT => return error.DiskQuota,
.FAULT => unreachable,
.INVAL => unreachable,
.ISDIR => return error.IsDir,
.LOOP => return error.SymLinkLoop,
.MLINK => return error.LinkQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.NotDir,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.EXIST => return error.PathAlreadyExists,
.NOTEMPTY => return error.PathAlreadyExists,
.ROFS => return error.ReadOnlyFileSystem,
.XDEV => return error.RenameAcrossMountPoints,
else => |err| return unexpectedErrno(err),
}
}
pub fn renameW(old_path: [*:0]const u16, new_path: [*:0]const u16) RenameError!void {
const flags = windows.MOVEFILE_REPLACE_EXISTING | windows.MOVEFILE_WRITE_THROUGH;
return windows.MoveFileExW(old_path, new_path, flags);
}
pub fn renameat(
old_dir_fd: fd_t,
old_path: []const u8,
new_dir_fd: fd_t,
new_path: []const u8,
) RenameError!void {
if (builtin.os.tag == .windows) {
const old_path_w = try windows.sliceToPrefixedFileW(old_path);
const new_path_w = try windows.sliceToPrefixedFileW(new_path);
return renameatW(old_dir_fd, old_path_w.span(), new_dir_fd, new_path_w.span(), windows.TRUE);
} else if (builtin.os.tag == .wasi and !builtin.link_libc) {
const old: RelativePathWasi = .{ .dir_fd = old_dir_fd, .relative_path = old_path };
const new: RelativePathWasi = .{ .dir_fd = new_dir_fd, .relative_path = new_path };
return renameatWasi(old, new);
} else {
const old_path_c = try toPosixPath(old_path);
const new_path_c = try toPosixPath(new_path);
return renameatZ(old_dir_fd, &old_path_c, new_dir_fd, &new_path_c);
}
}
pub fn renameatWasi(old: RelativePathWasi, new: RelativePathWasi) RenameError!void {
switch (wasi.path_rename(old.dir_fd, old.relative_path.ptr, old.relative_path.len, new.dir_fd, new.relative_path.ptr, new.relative_path.len)) {
.SUCCESS => return,
.ACCES => return error.AccessDenied,
.PERM => return error.AccessDenied,
.BUSY => return error.FileBusy,
.DQUOT => return error.DiskQuota,
.FAULT => unreachable,
.INVAL => unreachable,
.ISDIR => return error.IsDir,
.LOOP => return error.SymLinkLoop,
.MLINK => return error.LinkQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.NotDir,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.EXIST => return error.PathAlreadyExists,
.NOTEMPTY => return error.PathAlreadyExists,
.ROFS => return error.ReadOnlyFileSystem,
.XDEV => return error.RenameAcrossMountPoints,
.NOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
pub fn renameatZ(
old_dir_fd: fd_t,
old_path: [*:0]const u8,
new_dir_fd: fd_t,
new_path: [*:0]const u8,
) RenameError!void {
if (builtin.os.tag == .windows) {
const old_path_w = try windows.cStrToPrefixedFileW(old_path);
const new_path_w = try windows.cStrToPrefixedFileW(new_path);
return renameatW(old_dir_fd, old_path_w.span(), new_dir_fd, new_path_w.span(), windows.TRUE);
} else if (builtin.os.tag == .wasi and !builtin.link_libc) {
return renameat(old_dir_fd, mem.sliceTo(old_path, 0), new_dir_fd, mem.sliceTo(new_path, 0));
}
switch (errno(system.renameat(old_dir_fd, old_path, new_dir_fd, new_path))) {
.SUCCESS => return,
.ACCES => return error.AccessDenied,
.PERM => return error.AccessDenied,
.BUSY => return error.FileBusy,
.DQUOT => return error.DiskQuota,
.FAULT => unreachable,
.INVAL => unreachable,
.ISDIR => return error.IsDir,
.LOOP => return error.SymLinkLoop,
.MLINK => return error.LinkQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.NotDir,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.EXIST => return error.PathAlreadyExists,
.NOTEMPTY => return error.PathAlreadyExists,
.ROFS => return error.ReadOnlyFileSystem,
.XDEV => return error.RenameAcrossMountPoints,
else => |err| return unexpectedErrno(err),
}
}
pub fn renameatW(
old_dir_fd: fd_t,
old_path_w: []const u16,
new_dir_fd: fd_t,
new_path_w: []const u16,
ReplaceIfExists: windows.BOOLEAN,
) RenameError!void {
const src_fd = windows.OpenFile(old_path_w, .{
.dir = old_dir_fd,
.access_mask = windows.SYNCHRONIZE | windows.GENERIC_WRITE | windows.DELETE,
.creation = windows.FILE_OPEN,
.io_mode = .blocking,
.filter = .any,
.follow_symlinks = false,
}) catch |err| switch (err) {
error.WouldBlock => unreachable,
else => |e| return e,
};
defer windows.CloseHandle(src_fd);
const struct_buf_len = @sizeOf(windows.FILE_RENAME_INFORMATION) + (MAX_PATH_BYTES - 1);
var rename_info_buf: [struct_buf_len]u8 align(@alignOf(windows.FILE_RENAME_INFORMATION)) = undefined;
const struct_len = @sizeOf(windows.FILE_RENAME_INFORMATION) - 1 + new_path_w.len * 2;
if (struct_len > struct_buf_len) return error.NameTooLong;
const rename_info = @ptrCast(*windows.FILE_RENAME_INFORMATION, &rename_info_buf);
rename_info.* = .{
.ReplaceIfExists = ReplaceIfExists,
.RootDirectory = if (std.fs.path.isAbsoluteWindowsWTF16(new_path_w)) null else new_dir_fd,
.FileNameLength = @intCast(u32, new_path_w.len * 2),
.FileName = undefined,
};
std.mem.copy(u16, @as([*]u16, &rename_info.FileName)[0..new_path_w.len], new_path_w);
var io_status_block: windows.IO_STATUS_BLOCK = undefined;
const rc = windows.ntdll.NtSetInformationFile(
src_fd,
&io_status_block,
rename_info,
@intCast(u32, struct_len),
.FileRenameInformation,
);
switch (rc) {
.SUCCESS => return,
.INVALID_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
.OBJECT_PATH_SYNTAX_BAD => unreachable,
.ACCESS_DENIED => return error.AccessDenied,
.OBJECT_NAME_NOT_FOUND => return error.FileNotFound,
.OBJECT_PATH_NOT_FOUND => return error.FileNotFound,
.NOT_SAME_DEVICE => return error.RenameAcrossMountPoints,
else => return windows.unexpectedStatus(rc),
}
}
pub fn mkdirat(dir_fd: fd_t, sub_dir_path: []const u8, mode: u32) MakeDirError!void {
if (builtin.os.tag == .windows) {
const sub_dir_path_w = try windows.sliceToPrefixedFileW(sub_dir_path);
return mkdiratW(dir_fd, sub_dir_path_w.span(), mode);
} else if (builtin.os.tag == .wasi and !builtin.link_libc) {
return mkdiratWasi(dir_fd, sub_dir_path, mode);
} else {
const sub_dir_path_c = try toPosixPath(sub_dir_path);
return mkdiratZ(dir_fd, &sub_dir_path_c, mode);
}
}
pub fn mkdiratWasi(dir_fd: fd_t, sub_dir_path: []const u8, mode: u32) MakeDirError!void {
_ = mode;
switch (wasi.path_create_directory(dir_fd, sub_dir_path.ptr, sub_dir_path.len)) {
.SUCCESS => return,
.ACCES => return error.AccessDenied,
.BADF => unreachable,
.PERM => return error.AccessDenied,
.DQUOT => return error.DiskQuota,
.EXIST => return error.PathAlreadyExists,
.FAULT => unreachable,
.LOOP => return error.SymLinkLoop,
.MLINK => return error.LinkQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.NOTDIR => return error.NotDir,
.ROFS => return error.ReadOnlyFileSystem,
.NOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
pub fn mkdiratZ(dir_fd: fd_t, sub_dir_path: [*:0]const u8, mode: u32) MakeDirError!void {
if (builtin.os.tag == .windows) {
const sub_dir_path_w = try windows.cStrToPrefixedFileW(sub_dir_path);
return mkdiratW(dir_fd, sub_dir_path_w.span().ptr, mode);
} else if (builtin.os.tag == .wasi and !builtin.link_libc) {
return mkdirat(dir_fd, mem.sliceTo(sub_dir_path, 0), mode);
}
switch (errno(system.mkdirat(dir_fd, sub_dir_path, mode))) {
.SUCCESS => return,
.ACCES => return error.AccessDenied,
.BADF => unreachable,
.PERM => return error.AccessDenied,
.DQUOT => return error.DiskQuota,
.EXIST => return error.PathAlreadyExists,
.FAULT => unreachable,
.LOOP => return error.SymLinkLoop,
.MLINK => return error.LinkQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.NOTDIR => return error.NotDir,
.ROFS => return error.ReadOnlyFileSystem,
.NOTCONN => return error.FileNotFound,
else => |err| return unexpectedErrno(err),
}
}
pub fn mkdiratW(dir_fd: fd_t, sub_path_w: []const u16, mode: u32) MakeDirError!void {
_ = mode;
const sub_dir_handle = windows.OpenFile(sub_path_w, .{
.dir = dir_fd,
.access_mask = windows.GENERIC_READ | windows.SYNCHRONIZE,
.creation = windows.FILE_CREATE,
.io_mode = .blocking,
.filter = .dir_only,
}) catch |err| switch (err) {
error.IsDir => unreachable,
error.PipeBusy => unreachable,
error.WouldBlock => unreachable,
else => |e| return e,
};
windows.CloseHandle(sub_dir_handle);
}
pub const MakeDirError = error{
AccessDenied,
DiskQuota,
PathAlreadyExists,
SymLinkLoop,
LinkQuotaExceeded,
NameTooLong,
FileNotFound,
SystemResources,
NoSpaceLeft,
NotDir,
ReadOnlyFileSystem,
InvalidUtf8,
BadPathName,
NoDevice,
} || UnexpectedError;
pub fn mkdir(dir_path: []const u8, mode: u32) MakeDirError!void {
if (builtin.os.tag == .wasi and !builtin.link_libc) {
return mkdirat(wasi.AT.FDCWD, dir_path, mode);
} else if (builtin.os.tag == .windows) {
const dir_path_w = try windows.sliceToPrefixedFileW(dir_path);
return mkdirW(dir_path_w.span(), mode);
} else {
const dir_path_c = try toPosixPath(dir_path);
return mkdirZ(&dir_path_c, mode);
}
}
pub fn mkdirZ(dir_path: [*:0]const u8, mode: u32) MakeDirError!void {
if (builtin.os.tag == .windows) {
const dir_path_w = try windows.cStrToPrefixedFileW(dir_path);
return mkdirW(dir_path_w.span(), mode);
} else if (builtin.os.tag == .wasi and !builtin.link_libc) {
return mkdir(mem.sliceTo(dir_path, 0), mode);
}
switch (errno(system.mkdir(dir_path, mode))) {
.SUCCESS => return,
.ACCES => return error.AccessDenied,
.PERM => return error.AccessDenied,
.DQUOT => return error.DiskQuota,
.EXIST => return error.PathAlreadyExists,
.FAULT => unreachable,
.LOOP => return error.SymLinkLoop,
.MLINK => return error.LinkQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.NOTDIR => return error.NotDir,
.ROFS => return error.ReadOnlyFileSystem,
else => |err| return unexpectedErrno(err),
}
}
pub fn mkdirW(dir_path_w: []const u16, mode: u32) MakeDirError!void {
_ = mode;
const sub_dir_handle = windows.OpenFile(dir_path_w, .{
.dir = std.fs.cwd().fd,
.access_mask = windows.GENERIC_READ | windows.SYNCHRONIZE,
.creation = windows.FILE_CREATE,
.io_mode = .blocking,
.filter = .dir_only,
}) catch |err| switch (err) {
error.IsDir => unreachable,
error.PipeBusy => unreachable,
error.WouldBlock => unreachable,
else => |e| return e,
};
windows.CloseHandle(sub_dir_handle);
}
pub const DeleteDirError = error{
AccessDenied,
FileBusy,
SymLinkLoop,
NameTooLong,
FileNotFound,
SystemResources,
NotDir,
DirNotEmpty,
ReadOnlyFileSystem,
InvalidUtf8,
BadPathName,
} || UnexpectedError;
pub fn rmdir(dir_path: []const u8) DeleteDirError!void {
if (builtin.os.tag == .wasi and !builtin.link_libc) {
return unlinkat(wasi.AT.FDCWD, dir_path, AT.REMOVEDIR) catch |err| switch (err) {
error.FileSystem => unreachable,
error.IsDir => unreachable,
else => |e| return e,
};
} else if (builtin.os.tag == .windows) {
const dir_path_w = try windows.sliceToPrefixedFileW(dir_path);
return rmdirW(dir_path_w.span());
} else {
const dir_path_c = try toPosixPath(dir_path);
return rmdirZ(&dir_path_c);
}
}
pub fn rmdirZ(dir_path: [*:0]const u8) DeleteDirError!void {
if (builtin.os.tag == .windows) {
const dir_path_w = try windows.cStrToPrefixedFileW(dir_path);
return rmdirW(dir_path_w.span());
} else if (builtin.os.tag == .wasi and !builtin.link_libc) {
return rmdir(mem.sliceTo(dir_path, 0));
}
switch (errno(system.rmdir(dir_path))) {
.SUCCESS => return,
.ACCES => return error.AccessDenied,
.PERM => return error.AccessDenied,
.BUSY => return error.FileBusy,
.FAULT => unreachable,
.INVAL => return error.BadPathName,
.LOOP => return error.SymLinkLoop,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOTDIR => return error.NotDir,
.EXIST => return error.DirNotEmpty,
.NOTEMPTY => return error.DirNotEmpty,
.ROFS => return error.ReadOnlyFileSystem,
else => |err| return unexpectedErrno(err),
}
}
pub fn rmdirW(dir_path_w: []const u16) DeleteDirError!void {
return windows.DeleteFile(dir_path_w, .{ .dir = std.fs.cwd().fd, .remove_dir = true }) catch |err| switch (err) {
error.IsDir => unreachable,
else => |e| return e,
};
}
pub const ChangeCurDirError = error{
AccessDenied,
FileSystem,
SymLinkLoop,
NameTooLong,
FileNotFound,
SystemResources,
NotDir,
BadPathName,
InvalidUtf8,
} || UnexpectedError;
pub fn chdir(dir_path: []const u8) ChangeCurDirError!void {
if (builtin.os.tag == .wasi and !builtin.link_libc) {
@compileError("WASI does not support os.chdir");
} else if (builtin.os.tag == .windows) {
var utf16_dir_path: [windows.PATH_MAX_WIDE]u16 = undefined;
const len = try std.unicode.utf8ToUtf16Le(utf16_dir_path[0..], dir_path);
if (len > utf16_dir_path.len) return error.NameTooLong;
return chdirW(utf16_dir_path[0..len]);
} else {
const dir_path_c = try toPosixPath(dir_path);
return chdirZ(&dir_path_c);
}
}
pub fn chdirZ(dir_path: [*:0]const u8) ChangeCurDirError!void {
if (builtin.os.tag == .windows) {
var utf16_dir_path: [windows.PATH_MAX_WIDE]u16 = undefined;
const len = try std.unicode.utf8ToUtf16Le(utf16_dir_path[0..], dir_path);
if (len > utf16_dir_path.len) return error.NameTooLong;
return chdirW(utf16_dir_path[0..len]);
} else if (builtin.os.tag == .wasi and !builtin.link_libc) {
return chdir(mem.sliceTo(dir_path, 0));
}
switch (errno(system.chdir(dir_path))) {
.SUCCESS => return,
.ACCES => return error.AccessDenied,
.FAULT => unreachable,
.IO => return error.FileSystem,
.LOOP => return error.SymLinkLoop,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOTDIR => return error.NotDir,
else => |err| return unexpectedErrno(err),
}
}
pub fn chdirW(dir_path: []const u16) ChangeCurDirError!void {
windows.SetCurrentDirectory(dir_path) catch |err| switch (err) {
error.NoDevice => return error.FileSystem,
else => |e| return e,
};
}
pub const FchdirError = error{
AccessDenied,
NotDir,
FileSystem,
} || UnexpectedError;
pub fn fchdir(dirfd: fd_t) FchdirError!void {
while (true) {
switch (errno(system.fchdir(dirfd))) {
.SUCCESS => return,
.ACCES => return error.AccessDenied,
.BADF => unreachable,
.NOTDIR => return error.NotDir,
.INTR => continue,
.IO => return error.FileSystem,
else => |err| return unexpectedErrno(err),
}
}
}
pub const ReadLinkError = error{
AccessDenied,
FileSystem,
SymLinkLoop,
NameTooLong,
FileNotFound,
SystemResources,
NotLink,
NotDir,
InvalidUtf8,
BadPathName,
UnsupportedReparsePointType,
} || UnexpectedError;
pub fn readlink(file_path: []const u8, out_buffer: []u8) ReadLinkError![]u8 {
if (builtin.os.tag == .wasi and !builtin.link_libc) {
return readlinkat(wasi.AT.FDCWD, file_path, out_buffer);
} else if (builtin.os.tag == .windows) {
const file_path_w = try windows.sliceToPrefixedFileW(file_path);
return readlinkW(file_path_w.span(), out_buffer);
} else {
const file_path_c = try toPosixPath(file_path);
return readlinkZ(&file_path_c, out_buffer);
}
}
pub fn readlinkW(file_path: []const u16, out_buffer: []u8) ReadLinkError![]u8 {
return windows.ReadLink(std.fs.cwd().fd, file_path, out_buffer);
}
pub fn readlinkZ(file_path: [*:0]const u8, out_buffer: []u8) ReadLinkError![]u8 {
if (builtin.os.tag == .windows) {
const file_path_w = try windows.cStrToWin32PrefixedFileW(file_path);
return readlinkW(file_path_w.span(), out_buffer);
} else if (builtin.os.tag == .wasi and !builtin.link_libc) {
return readlink(mem.sliceTo(file_path, 0), out_buffer);
}
const rc = system.readlink(file_path, out_buffer.ptr, out_buffer.len);
switch (errno(rc)) {
.SUCCESS => return out_buffer[0..@bitCast(usize, rc)],
.ACCES => return error.AccessDenied,
.FAULT => unreachable,
.INVAL => return error.NotLink,
.IO => return error.FileSystem,
.LOOP => return error.SymLinkLoop,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOTDIR => return error.NotDir,
else => |err| return unexpectedErrno(err),
}
}
pub fn readlinkat(dirfd: fd_t, file_path: []const u8, out_buffer: []u8) ReadLinkError![]u8 {
if (builtin.os.tag == .wasi and !builtin.link_libc) {
return readlinkatWasi(dirfd, file_path, out_buffer);
}
if (builtin.os.tag == .windows) {
const file_path_w = try windows.sliceToPrefixedFileW(file_path);
return readlinkatW(dirfd, file_path_w.span(), out_buffer);
}
const file_path_c = try toPosixPath(file_path);
return readlinkatZ(dirfd, &file_path_c, out_buffer);
}
pub fn readlinkatWasi(dirfd: fd_t, file_path: []const u8, out_buffer: []u8) ReadLinkError![]u8 {
var bufused: usize = undefined;
switch (wasi.path_readlink(dirfd, file_path.ptr, file_path.len, out_buffer.ptr, out_buffer.len, &bufused)) {
.SUCCESS => return out_buffer[0..bufused],
.ACCES => return error.AccessDenied,
.FAULT => unreachable,
.INVAL => return error.NotLink,
.IO => return error.FileSystem,
.LOOP => return error.SymLinkLoop,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOTDIR => return error.NotDir,
.NOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
pub fn readlinkatW(dirfd: fd_t, file_path: []const u16, out_buffer: []u8) ReadLinkError![]u8 {
return windows.ReadLink(dirfd, file_path, out_buffer);
}
pub fn readlinkatZ(dirfd: fd_t, file_path: [*:0]const u8, out_buffer: []u8) ReadLinkError![]u8 {
if (builtin.os.tag == .windows) {
const file_path_w = try windows.cStrToPrefixedFileW(file_path);
return readlinkatW(dirfd, file_path_w.span(), out_buffer);
} else if (builtin.os.tag == .wasi and !builtin.link_libc) {
return readlinkat(dirfd, mem.sliceTo(file_path, 0), out_buffer);
}
const rc = system.readlinkat(dirfd, file_path, out_buffer.ptr, out_buffer.len);
switch (errno(rc)) {
.SUCCESS => return out_buffer[0..@bitCast(usize, rc)],
.ACCES => return error.AccessDenied,
.FAULT => unreachable,
.INVAL => return error.NotLink,
.IO => return error.FileSystem,
.LOOP => return error.SymLinkLoop,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOTDIR => return error.NotDir,
else => |err| return unexpectedErrno(err),
}
}
pub const SetEidError = error{
InvalidUserId,
PermissionDenied,
} || UnexpectedError;
pub const SetIdError = error{ResourceLimitReached} || SetEidError;
pub fn setuid(uid: uid_t) SetIdError!void {
switch (errno(system.setuid(uid))) {
.SUCCESS => return,
.AGAIN => return error.ResourceLimitReached,
.INVAL => return error.InvalidUserId,
.PERM => return error.PermissionDenied,
else => |err| return unexpectedErrno(err),
}
}
pub fn seteuid(uid: uid_t) SetEidError!void {
switch (errno(system.seteuid(uid))) {
.SUCCESS => return,
.INVAL => return error.InvalidUserId,
.PERM => return error.PermissionDenied,
else => |err| return unexpectedErrno(err),
}
}
pub fn setreuid(ruid: uid_t, euid: uid_t) SetIdError!void {
switch (errno(system.setreuid(ruid, euid))) {
.SUCCESS => return,
.AGAIN => return error.ResourceLimitReached,
.INVAL => return error.InvalidUserId,
.PERM => return error.PermissionDenied,
else => |err| return unexpectedErrno(err),
}
}
pub fn setgid(gid: gid_t) SetIdError!void {
switch (errno(system.setgid(gid))) {
.SUCCESS => return,
.AGAIN => return error.ResourceLimitReached,
.INVAL => return error.InvalidUserId,
.PERM => return error.PermissionDenied,
else => |err| return unexpectedErrno(err),
}
}
pub fn setegid(uid: uid_t) SetEidError!void {
switch (errno(system.setegid(uid))) {
.SUCCESS => return,
.INVAL => return error.InvalidUserId,
.PERM => return error.PermissionDenied,
else => |err| return unexpectedErrno(err),
}
}
pub fn setregid(rgid: gid_t, egid: gid_t) SetIdError!void {
switch (errno(system.setregid(rgid, egid))) {
.SUCCESS => return,
.AGAIN => return error.ResourceLimitReached,
.INVAL => return error.InvalidUserId,
.PERM => return error.PermissionDenied,
else => |err| return unexpectedErrno(err),
}
}
pub fn isatty(handle: fd_t) bool {
if (builtin.os.tag == .windows) {
if (isCygwinPty(handle))
return true;
var out: windows.DWORD = undefined;
return windows.kernel32.GetConsoleMode(handle, &out) != 0;
}
if (builtin.link_libc) {
return system.isatty(handle) != 0;
}
if (builtin.os.tag == .wasi) {
var statbuf: fdstat_t = undefined;
const err = system.fd_fdstat_get(handle, &statbuf);
if (err != .SUCCESS) {
return false;
}
if (statbuf.fs_filetype != .CHARACTER_DEVICE or
(statbuf.fs_rights_base & (RIGHT.FD_SEEK | RIGHT.FD_TELL)) != 0)
{
return false;
}
return true;
}
if (builtin.os.tag == .linux) {
while (true) {
var wsz: linux.winsize = undefined;
const fd = @bitCast(usize, @as(isize, handle));
const rc = linux.syscall3(.ioctl, fd, linux.T.IOCGWINSZ, @ptrToInt(&wsz));
switch (linux.getErrno(rc)) {
.SUCCESS => return true,
.INTR => continue,
else => return false,
}
}
}
return system.isatty(handle) != 0;
}
pub fn isCygwinPty(handle: fd_t) bool {
if (builtin.os.tag != .windows) return false;
{
var io_status: windows.IO_STATUS_BLOCK = undefined;
var device_info: windows.FILE_FS_DEVICE_INFORMATION = undefined;
const rc = windows.ntdll.NtQueryVolumeInformationFile(handle, &io_status, &device_info, @sizeOf(windows.FILE_FS_DEVICE_INFORMATION), .FileFsDeviceInformation);
switch (rc) {
.SUCCESS => {},
else => return false,
}
if (device_info.DeviceType != windows.FILE_DEVICE_NAMED_PIPE) return false;
}
const name_bytes_offset = @offsetOf(windows.FILE_NAME_INFO, "FileName");
const num_name_bytes = windows.MAX_PATH * 2;
var name_info_bytes align(@alignOf(windows.FILE_NAME_INFO)) = [_]u8{0} ** (name_bytes_offset + num_name_bytes);
var io_status_block: windows.IO_STATUS_BLOCK = undefined;
const rc = windows.ntdll.NtQueryInformationFile(handle, &io_status_block, &name_info_bytes, @intCast(u32, name_info_bytes.len), .FileNameInformation);
switch (rc) {
.SUCCESS => {},
.INVALID_PARAMETER => unreachable,
else => return false,
}
const name_info = @ptrCast(*const windows.FILE_NAME_INFO, &name_info_bytes[0]);
const name_bytes = name_info_bytes[name_bytes_offset .. name_bytes_offset + @as(usize, name_info.FileNameLength)];
const name_wide = mem.bytesAsSlice(u16, name_bytes);
return (mem.startsWith(u16, name_wide, &[_]u16{ '\\', 'm', 's', 'y', 's', '-' }) or
mem.startsWith(u16, name_wide, &[_]u16{ '\\', 'c', 'y', 'g', 'w', 'i', 'n', '-' })) and
mem.indexOf(u16, name_wide, &[_]u16{ '-', 'p', 't', 'y' }) != null;
}
pub const SocketError = error{
PermissionDenied,
AddressFamilyNotSupported,
ProtocolFamilyNotAvailable,
ProcessFdQuotaExceeded,
SystemFdQuotaExceeded,
SystemResources,
ProtocolNotSupported,
SocketTypeNotSupported,
} || UnexpectedError;
pub fn socket(domain: u32, socket_type: u32, protocol: u32) SocketError!socket_t {
if (builtin.os.tag == .windows) {
const filtered_sock_type = socket_type & ~@as(u32, SOCK.NONBLOCK | SOCK.CLOEXEC);
const flags: u32 = if ((socket_type & SOCK.CLOEXEC) != 0)
windows.ws2_32.WSA_FLAG_NO_HANDLE_INHERIT
else
0;
const rc = try windows.WSASocketW(
@bitCast(i32, domain),
@bitCast(i32, filtered_sock_type),
@bitCast(i32, protocol),
null,
0,
flags,
);
errdefer windows.closesocket(rc) catch unreachable;
if ((socket_type & SOCK.NONBLOCK) != 0) {
var mode: c_ulong = 1;
if (windows.ws2_32.SOCKET_ERROR == windows.ws2_32.ioctlsocket(rc, windows.ws2_32.FIONBIO, &mode)) {
switch (windows.ws2_32.WSAGetLastError()) {
else => unreachable,
}
}
}
return rc;
}
const have_sock_flags = comptime !builtin.target.isDarwin();
const filtered_sock_type = if (!have_sock_flags)
socket_type & ~@as(u32, SOCK.NONBLOCK | SOCK.CLOEXEC)
else
socket_type;
const rc = system.socket(domain, filtered_sock_type, protocol);
switch (errno(rc)) {
.SUCCESS => {
const fd = @intCast(fd_t, rc);
if (!have_sock_flags) {
try setSockFlags(fd, socket_type);
}
return fd;
},
.ACCES => return error.PermissionDenied,
.AFNOSUPPORT => return error.AddressFamilyNotSupported,
.INVAL => return error.ProtocolFamilyNotAvailable,
.MFILE => return error.ProcessFdQuotaExceeded,
.NFILE => return error.SystemFdQuotaExceeded,
.NOBUFS => return error.SystemResources,
.NOMEM => return error.SystemResources,
.PROTONOSUPPORT => return error.ProtocolNotSupported,
.PROTOTYPE => return error.SocketTypeNotSupported,
else => |err| return unexpectedErrno(err),
}
}
pub const ShutdownError = error{
ConnectionAborted,
ConnectionResetByPeer,
BlockingOperationInProgress,
NetworkSubsystemFailed,
SocketNotConnected,
SystemResources,
} || UnexpectedError;
pub const ShutdownHow = enum { recv, send, both };
pub fn shutdown(sock: socket_t, how: ShutdownHow) ShutdownError!void {
if (builtin.os.tag == .windows) {
const result = windows.ws2_32.shutdown(sock, switch (how) {
.recv => windows.ws2_32.SD_RECEIVE,
.send => windows.ws2_32.SD_SEND,
.both => windows.ws2_32.SD_BOTH,
});
if (0 != result) switch (windows.ws2_32.WSAGetLastError()) {
.WSAECONNABORTED => return error.ConnectionAborted,
.WSAECONNRESET => return error.ConnectionResetByPeer,
.WSAEINPROGRESS => return error.BlockingOperationInProgress,
.WSAEINVAL => unreachable,
.WSAENETDOWN => return error.NetworkSubsystemFailed,
.WSAENOTCONN => return error.SocketNotConnected,
.WSAENOTSOCK => unreachable,
.WSANOTINITIALISED => unreachable,
else => |err| return windows.unexpectedWSAError(err),
};
} else {
const rc = system.shutdown(sock, switch (how) {
.recv => SHUT.RD,
.send => SHUT.WR,
.both => SHUT.RDWR,
});
switch (errno(rc)) {
.SUCCESS => return,
.BADF => unreachable,
.INVAL => unreachable,
.NOTCONN => return error.SocketNotConnected,
.NOTSOCK => unreachable,
.NOBUFS => return error.SystemResources,
else => |err| return unexpectedErrno(err),
}
}
}
pub fn closeSocket(sock: socket_t) void {
if (builtin.os.tag == .windows) {
windows.closesocket(sock) catch unreachable;
} else {
close(sock);
}
}
pub const BindError = error{
AccessDenied,
AddressInUse,
AddressNotAvailable,
AddressFamilyNotSupported,
SymLinkLoop,
NameTooLong,
FileNotFound,
SystemResources,
NotDir,
ReadOnlyFileSystem,
NetworkSubsystemFailed,
FileDescriptorNotASocket,
AlreadyBound,
} || UnexpectedError;
pub fn bind(sock: socket_t, addr: *const sockaddr, len: socklen_t) BindError!void {
if (builtin.os.tag == .windows) {
const rc = windows.bind(sock, addr, len);
if (rc == windows.ws2_32.SOCKET_ERROR) {
switch (windows.ws2_32.WSAGetLastError()) {
.WSANOTINITIALISED => unreachable,
.WSAEACCES => return error.AccessDenied,
.WSAEADDRINUSE => return error.AddressInUse,
.WSAEADDRNOTAVAIL => return error.AddressNotAvailable,
.WSAENOTSOCK => return error.FileDescriptorNotASocket,
.WSAEFAULT => unreachable,
.WSAEINVAL => return error.AlreadyBound,
.WSAENOBUFS => return error.SystemResources,
.WSAENETDOWN => return error.NetworkSubsystemFailed,
else => |err| return windows.unexpectedWSAError(err),
}
unreachable;
}
return;
} else {
const rc = system.bind(sock, addr, len);
switch (errno(rc)) {
.SUCCESS => return,
.ACCES, .PERM => return error.AccessDenied,
.ADDRINUSE => return error.AddressInUse,
.BADF => unreachable,
.INVAL => unreachable,
.NOTSOCK => unreachable,
.AFNOSUPPORT => return error.AddressFamilyNotSupported,
.ADDRNOTAVAIL => return error.AddressNotAvailable,
.FAULT => unreachable,
.LOOP => return error.SymLinkLoop,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOTDIR => return error.NotDir,
.ROFS => return error.ReadOnlyFileSystem,
else => |err| return unexpectedErrno(err),
}
}
unreachable;
}
pub const ListenError = error{
AddressInUse,
FileDescriptorNotASocket,
OperationNotSupported,
NetworkSubsystemFailed,
SystemResources,
AlreadyConnected,
SocketNotBound,
} || UnexpectedError;
pub fn listen(sock: socket_t, backlog: u31) ListenError!void {
if (builtin.os.tag == .windows) {
const rc = windows.listen(sock, backlog);
if (rc == windows.ws2_32.SOCKET_ERROR) {
switch (windows.ws2_32.WSAGetLastError()) {
.WSANOTINITIALISED => unreachable,
.WSAENETDOWN => return error.NetworkSubsystemFailed,
.WSAEADDRINUSE => return error.AddressInUse,
.WSAEISCONN => return error.AlreadyConnected,
.WSAEINVAL => return error.SocketNotBound,
.WSAEMFILE, .WSAENOBUFS => return error.SystemResources,
.WSAENOTSOCK => return error.FileDescriptorNotASocket,
.WSAEOPNOTSUPP => return error.OperationNotSupported,
.WSAEINPROGRESS => unreachable,
else => |err| return windows.unexpectedWSAError(err),
}
}
return;
} else {
const rc = system.listen(sock, backlog);
switch (errno(rc)) {
.SUCCESS => return,
.ADDRINUSE => return error.AddressInUse,
.BADF => unreachable,
.NOTSOCK => return error.FileDescriptorNotASocket,
.OPNOTSUPP => return error.OperationNotSupported,
else => |err| return unexpectedErrno(err),
}
}
}
pub const AcceptError = error{
ConnectionAborted,
FileDescriptorNotASocket,
ProcessFdQuotaExceeded,
SystemFdQuotaExceeded,
SystemResources,
SocketNotListening,
ProtocolFailure,
BlockedByFirewall,
WouldBlock,
ConnectionResetByPeer,
NetworkSubsystemFailed,
OperationNotSupported,
} || UnexpectedError;
pub fn accept(
sock: socket_t,
addr: ?*sockaddr,
addr_size: ?*socklen_t,
flags: u32,
) AcceptError!socket_t {
const have_accept4 = comptime !(builtin.target.isDarwin() or builtin.os.tag == .windows);
assert(0 == (flags & ~@as(u32, SOCK.NONBLOCK | SOCK.CLOEXEC)));
const accepted_sock = while (true) {
const rc = if (have_accept4)
system.accept4(sock, addr, addr_size, flags)
else if (builtin.os.tag == .windows)
windows.accept(sock, addr, addr_size)
else
system.accept(sock, addr, addr_size);
if (builtin.os.tag == .windows) {
if (rc == windows.ws2_32.INVALID_SOCKET) {
switch (windows.ws2_32.WSAGetLastError()) {
.WSANOTINITIALISED => unreachable,
.WSAECONNRESET => return error.ConnectionResetByPeer,
.WSAEFAULT => unreachable,
.WSAEINVAL => return error.SocketNotListening,
.WSAEMFILE => return error.ProcessFdQuotaExceeded,
.WSAENETDOWN => return error.NetworkSubsystemFailed,
.WSAENOBUFS => return error.FileDescriptorNotASocket,
.WSAEOPNOTSUPP => return error.OperationNotSupported,
.WSAEWOULDBLOCK => return error.WouldBlock,
else => |err| return windows.unexpectedWSAError(err),
}
} else {
break rc;
}
} else {
switch (errno(rc)) {
.SUCCESS => {
break @intCast(socket_t, rc);
},
.INTR => continue,
.AGAIN => return error.WouldBlock,
.BADF => unreachable,
.CONNABORTED => return error.ConnectionAborted,
.FAULT => unreachable,
.INVAL => return error.SocketNotListening,
.NOTSOCK => unreachable,
.MFILE => return error.ProcessFdQuotaExceeded,
.NFILE => return error.SystemFdQuotaExceeded,
.NOBUFS => return error.SystemResources,
.NOMEM => return error.SystemResources,
.OPNOTSUPP => unreachable,
.PROTO => return error.ProtocolFailure,
.PERM => return error.BlockedByFirewall,
else => |err| return unexpectedErrno(err),
}
}
};
if (!have_accept4) {
try setSockFlags(accepted_sock, flags);
}
return accepted_sock;
}
pub const EpollCreateError = error{
ProcessFdQuotaExceeded,
SystemFdQuotaExceeded,
SystemResources,
} || UnexpectedError;
pub fn epoll_create1(flags: u32) EpollCreateError!i32 {
const rc = system.epoll_create1(flags);
switch (errno(rc)) {
.SUCCESS => return @intCast(i32, rc),
else => |err| return unexpectedErrno(err),
.INVAL => unreachable,
.MFILE => return error.ProcessFdQuotaExceeded,
.NFILE => return error.SystemFdQuotaExceeded,
.NOMEM => return error.SystemResources,
}
}
pub const EpollCtlError = error{
FileDescriptorAlreadyPresentInSet,
OperationCausesCircularLoop,
FileDescriptorNotRegistered,
SystemResources,
UserResourceLimitReached,
FileDescriptorIncompatibleWithEpoll,
} || UnexpectedError;
pub fn epoll_ctl(epfd: i32, op: u32, fd: i32, event: ?*linux.epoll_event) EpollCtlError!void {
const rc = system.epoll_ctl(epfd, op, fd, event);
switch (errno(rc)) {
.SUCCESS => return,
else => |err| return unexpectedErrno(err),
.BADF => unreachable,
.EXIST => return error.FileDescriptorAlreadyPresentInSet,
.INVAL => unreachable,
.LOOP => return error.OperationCausesCircularLoop,
.NOENT => return error.FileDescriptorNotRegistered,
.NOMEM => return error.SystemResources,
.NOSPC => return error.UserResourceLimitReached,
.PERM => return error.FileDescriptorIncompatibleWithEpoll,
}
}
pub fn epoll_wait(epfd: i32, events: []linux.epoll_event, timeout: i32) usize {
while (true) {
const rc = system.epoll_wait(epfd, events.ptr, @intCast(u32, events.len), timeout);
switch (errno(rc)) {
.SUCCESS => return @intCast(usize, rc),
.INTR => continue,
.BADF => unreachable,
.FAULT => unreachable,
.INVAL => unreachable,
else => unreachable,
}
}
}
pub const EventFdError = error{
SystemResources,
ProcessFdQuotaExceeded,
SystemFdQuotaExceeded,
} || UnexpectedError;
pub fn eventfd(initval: u32, flags: u32) EventFdError!i32 {
const rc = system.eventfd(initval, flags);
switch (errno(rc)) {
.SUCCESS => return @intCast(i32, rc),
else => |err| return unexpectedErrno(err),
.INVAL => unreachable,
.MFILE => return error.ProcessFdQuotaExceeded,
.NFILE => return error.SystemFdQuotaExceeded,
.NODEV => return error.SystemResources,
.NOMEM => return error.SystemResources,
}
}
pub const GetSockNameError = error{
SystemResources,
NetworkSubsystemFailed,
SocketNotBound,
FileDescriptorNotASocket,
} || UnexpectedError;
pub fn getsockname(sock: socket_t, addr: *sockaddr, addrlen: *socklen_t) GetSockNameError!void {
if (builtin.os.tag == .windows) {
const rc = windows.getsockname(sock, addr, addrlen);
if (rc == windows.ws2_32.SOCKET_ERROR) {
switch (windows.ws2_32.WSAGetLastError()) {
.WSANOTINITIALISED => unreachable,
.WSAENETDOWN => return error.NetworkSubsystemFailed,
.WSAEFAULT => unreachable,
.WSAENOTSOCK => return error.FileDescriptorNotASocket,
.WSAEINVAL => return error.SocketNotBound,
else => |err| return windows.unexpectedWSAError(err),
}
}
return;
} else {
const rc = system.getsockname(sock, addr, addrlen);
switch (errno(rc)) {
.SUCCESS => return,
else => |err| return unexpectedErrno(err),
.BADF => unreachable,
.FAULT => unreachable,
.INVAL => unreachable,
.NOTSOCK => return error.FileDescriptorNotASocket,
.NOBUFS => return error.SystemResources,
}
}
}
pub fn getpeername(sock: socket_t, addr: *sockaddr, addrlen: *socklen_t) GetSockNameError!void {
if (builtin.os.tag == .windows) {
const rc = windows.getpeername(sock, addr, addrlen);
if (rc == windows.ws2_32.SOCKET_ERROR) {
switch (windows.ws2_32.WSAGetLastError()) {
.WSANOTINITIALISED => unreachable,
.WSAENETDOWN => return error.NetworkSubsystemFailed,
.WSAEFAULT => unreachable,
.WSAENOTSOCK => return error.FileDescriptorNotASocket,
.WSAEINVAL => return error.SocketNotBound,
else => |err| return windows.unexpectedWSAError(err),
}
}
return;
} else {
const rc = system.getpeername(sock, addr, addrlen);
switch (errno(rc)) {
.SUCCESS => return,
else => |err| return unexpectedErrno(err),
.BADF => unreachable,
.FAULT => unreachable,
.INVAL => unreachable,
.NOTSOCK => return error.FileDescriptorNotASocket,
.NOBUFS => return error.SystemResources,
}
}
}
pub const ConnectError = error{
PermissionDenied,
AddressInUse,
AddressNotAvailable,
AddressFamilyNotSupported,
SystemResources,
ConnectionRefused,
NetworkUnreachable,
ConnectionTimedOut,
WouldBlock,
FileNotFound,
ConnectionResetByPeer,
ConnectionPending,
} || UnexpectedError;
pub fn connect(sock: socket_t, sock_addr: *const sockaddr, len: socklen_t) ConnectError!void {
if (builtin.os.tag == .windows) {
const rc = windows.ws2_32.connect(sock, sock_addr, @intCast(i32, len));
if (rc == 0) return;
switch (windows.ws2_32.WSAGetLastError()) {
.WSAEADDRINUSE => return error.AddressInUse,
.WSAEADDRNOTAVAIL => return error.AddressNotAvailable,
.WSAECONNREFUSED => return error.ConnectionRefused,
.WSAECONNRESET => return error.ConnectionResetByPeer,
.WSAETIMEDOUT => return error.ConnectionTimedOut,
.WSAEHOSTUNREACH,
.WSAENETUNREACH,
=> return error.NetworkUnreachable,
.WSAEFAULT => unreachable,
.WSAEINVAL => unreachable,
.WSAEISCONN => unreachable,
.WSAENOTSOCK => unreachable,
.WSAEWOULDBLOCK => unreachable,
.WSAEACCES => unreachable,
.WSAENOBUFS => return error.SystemResources,
.WSAEAFNOSUPPORT => return error.AddressFamilyNotSupported,
else => |err| return windows.unexpectedWSAError(err),
}
return;
}
while (true) {
switch (errno(system.connect(sock, sock_addr, len))) {
.SUCCESS => return,
.ACCES => return error.PermissionDenied,
.PERM => return error.PermissionDenied,
.ADDRINUSE => return error.AddressInUse,
.ADDRNOTAVAIL => return error.AddressNotAvailable,
.AFNOSUPPORT => return error.AddressFamilyNotSupported,
.AGAIN, .INPROGRESS => return error.WouldBlock,
.ALREADY => return error.ConnectionPending,
.BADF => unreachable,
.CONNREFUSED => return error.ConnectionRefused,
.CONNRESET => return error.ConnectionResetByPeer,
.FAULT => unreachable,
.INTR => continue,
.ISCONN => unreachable,
.HOSTUNREACH => return error.NetworkUnreachable,
.NETUNREACH => return error.NetworkUnreachable,
.NOTSOCK => unreachable,
.PROTOTYPE => unreachable,
.TIMEDOUT => return error.ConnectionTimedOut,
.NOENT => return error.FileNotFound,
else => |err| return unexpectedErrno(err),
}
}
}
pub fn getsockoptError(sockfd: fd_t) ConnectError!void {
var err_code: i32 = undefined;
var size: u32 = @sizeOf(u32);
const rc = system.getsockopt(sockfd, SOL.SOCKET, SO.ERROR, @ptrCast([*]u8, &err_code), &size);
assert(size == 4);
switch (errno(rc)) {
.SUCCESS => switch (@intToEnum(E, err_code)) {
.SUCCESS => return,
.ACCES => return error.PermissionDenied,
.PERM => return error.PermissionDenied,
.ADDRINUSE => return error.AddressInUse,
.ADDRNOTAVAIL => return error.AddressNotAvailable,
.AFNOSUPPORT => return error.AddressFamilyNotSupported,
.AGAIN => return error.SystemResources,
.ALREADY => return error.ConnectionPending,
.BADF => unreachable,
.CONNREFUSED => return error.ConnectionRefused,
.FAULT => unreachable,
.ISCONN => unreachable,
.HOSTUNREACH => return error.NetworkUnreachable,
.NETUNREACH => return error.NetworkUnreachable,
.NOTSOCK => unreachable,
.PROTOTYPE => unreachable,
.TIMEDOUT => return error.ConnectionTimedOut,
.CONNRESET => return error.ConnectionResetByPeer,
else => |err| return unexpectedErrno(err),
},
.BADF => unreachable,
.FAULT => unreachable,
.INVAL => unreachable,
.NOPROTOOPT => unreachable,
.NOTSOCK => unreachable,
else => |err| return unexpectedErrno(err),
}
}
pub const WaitPidResult = struct {
pid: pid_t,
status: u32,
};
pub fn waitpid(pid: pid_t, flags: u32) WaitPidResult {
const Status = if (builtin.link_libc) c_int else u32;
var status: Status = undefined;
const coerced_flags = if (builtin.link_libc) @intCast(c_int, flags) else flags;
while (true) {
const rc = system.waitpid(pid, &status, coerced_flags);
switch (errno(rc)) {
.SUCCESS => return .{
.pid = @intCast(pid_t, rc),
.status = @bitCast(u32, status),
},
.INTR => continue,
.CHILD => unreachable,
.INVAL => unreachable,
else => unreachable,
}
}
}
pub fn wait4(pid: pid_t, flags: u32, ru: ?*rusage) WaitPidResult {
const Status = if (builtin.link_libc) c_int else u32;
var status: Status = undefined;
const coerced_flags = if (builtin.link_libc) @intCast(c_int, flags) else flags;
while (true) {
const rc = system.wait4(pid, &status, coerced_flags, ru);
switch (errno(rc)) {
.SUCCESS => return .{
.pid = @intCast(pid_t, rc),
.status = @bitCast(u32, status),
},
.INTR => continue,
.CHILD => unreachable,
.INVAL => unreachable,
else => unreachable,
}
}
}
pub const FStatError = error{
SystemResources,
AccessDenied,
} || UnexpectedError;
pub fn fstat(fd: fd_t) FStatError!Stat {
if (builtin.os.tag == .wasi and !builtin.link_libc) {
var stat: wasi.filestat_t = undefined;
switch (wasi.fd_filestat_get(fd, &stat)) {
.SUCCESS => return Stat.fromFilestat(stat),
.INVAL => unreachable,
.BADF => unreachable,
.NOMEM => return error.SystemResources,
.ACCES => return error.AccessDenied,
.NOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
if (builtin.os.tag == .windows) {
@compileError("fstat is not yet implemented on Windows");
}
const fstat_sym = if (builtin.os.tag == .linux and builtin.link_libc)
system.fstat64
else
system.fstat;
var stat = mem.zeroes(Stat);
switch (errno(fstat_sym(fd, &stat))) {
.SUCCESS => return stat,
.INVAL => unreachable,
.BADF => unreachable,
.NOMEM => return error.SystemResources,
.ACCES => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
pub const FStatAtError = FStatError || error{ NameTooLong, FileNotFound, SymLinkLoop };
pub fn fstatat(dirfd: fd_t, pathname: []const u8, flags: u32) FStatAtError!Stat {
if (builtin.os.tag == .wasi and !builtin.link_libc) {
const wasi_flags = if (flags & linux.AT.SYMLINK_NOFOLLOW == 0) wasi.LOOKUP_SYMLINK_FOLLOW else 0;
return fstatatWasi(dirfd, pathname, wasi_flags);
} else if (builtin.os.tag == .windows) {
@compileError("fstatat is not yet implemented on Windows");
} else {
const pathname_c = try toPosixPath(pathname);
return fstatatZ(dirfd, &pathname_c, flags);
}
}
pub fn fstatatWasi(dirfd: fd_t, pathname: []const u8, flags: u32) FStatAtError!Stat {
var stat: wasi.filestat_t = undefined;
switch (wasi.path_filestat_get(dirfd, flags, pathname.ptr, pathname.len, &stat)) {
.SUCCESS => return Stat.fromFilestat(stat),
.INVAL => unreachable,
.BADF => unreachable,
.NOMEM => return error.SystemResources,
.ACCES => return error.AccessDenied,
.FAULT => unreachable,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.FileNotFound,
.NOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
pub fn fstatatZ(dirfd: fd_t, pathname: [*:0]const u8, flags: u32) FStatAtError!Stat {
if (builtin.os.tag == .wasi and !builtin.link_libc) {
return fstatatWasi(dirfd, mem.sliceTo(pathname), flags);
}
const fstatat_sym = if (builtin.os.tag == .linux and builtin.link_libc)
system.fstatat64
else
system.fstatat;
var stat = mem.zeroes(Stat);
switch (errno(fstatat_sym(dirfd, pathname, &stat, flags))) {
.SUCCESS => return stat,
.INVAL => unreachable,
.BADF => unreachable,
.NOMEM => return error.SystemResources,
.ACCES => return error.AccessDenied,
.PERM => return error.AccessDenied,
.FAULT => unreachable,
.NAMETOOLONG => return error.NameTooLong,
.LOOP => return error.SymLinkLoop,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.FileNotFound,
else => |err| return unexpectedErrno(err),
}
}
pub const KQueueError = error{
ProcessFdQuotaExceeded,
SystemFdQuotaExceeded,
} || UnexpectedError;
pub fn kqueue() KQueueError!i32 {
const rc = system.kqueue();
switch (errno(rc)) {
.SUCCESS => return @intCast(i32, rc),
.MFILE => return error.ProcessFdQuotaExceeded,
.NFILE => return error.SystemFdQuotaExceeded,
else => |err| return unexpectedErrno(err),
}
}
pub const KEventError = error{
AccessDenied,
EventNotFound,
SystemResources,
ProcessNotFound,
Overflow,
};
pub fn kevent(
kq: i32,
changelist: []const Kevent,
eventlist: []Kevent,
timeout: ?*const timespec,
) KEventError!usize {
while (true) {
const rc = system.kevent(
kq,
changelist.ptr,
math.cast(c_int, changelist.len) orelse return error.Overflow,
eventlist.ptr,
math.cast(c_int, eventlist.len) orelse return error.Overflow,
timeout,
);
switch (errno(rc)) {
.SUCCESS => return @intCast(usize, rc),
.ACCES => return error.AccessDenied,
.FAULT => unreachable,
.BADF => unreachable,
.INTR => continue,
.INVAL => unreachable,
.NOENT => return error.EventNotFound,
.NOMEM => return error.SystemResources,
.SRCH => return error.ProcessNotFound,
else => unreachable,
}
}
}
pub const INotifyInitError = error{
ProcessFdQuotaExceeded,
SystemFdQuotaExceeded,
SystemResources,
} || UnexpectedError;
pub fn inotify_init1(flags: u32) INotifyInitError!i32 {
const rc = system.inotify_init1(flags);
switch (errno(rc)) {
.SUCCESS => return @intCast(i32, rc),
.INVAL => unreachable,
.MFILE => return error.ProcessFdQuotaExceeded,
.NFILE => return error.SystemFdQuotaExceeded,
.NOMEM => return error.SystemResources,
else => |err| return unexpectedErrno(err),
}
}
pub const INotifyAddWatchError = error{
AccessDenied,
NameTooLong,
FileNotFound,
SystemResources,
UserResourceLimitReached,
NotDir,
WatchAlreadyExists,
} || UnexpectedError;
pub fn inotify_add_watch(inotify_fd: i32, pathname: []const u8, mask: u32) INotifyAddWatchError!i32 {
const pathname_c = try toPosixPath(pathname);
return inotify_add_watchZ(inotify_fd, &pathname_c, mask);
}
pub fn inotify_add_watchZ(inotify_fd: i32, pathname: [*:0]const u8, mask: u32) INotifyAddWatchError!i32 {
const rc = system.inotify_add_watch(inotify_fd, pathname, mask);
switch (errno(rc)) {
.SUCCESS => return @intCast(i32, rc),
.ACCES => return error.AccessDenied,
.BADF => unreachable,
.FAULT => unreachable,
.INVAL => unreachable,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOSPC => return error.UserResourceLimitReached,
.NOTDIR => return error.NotDir,
.EXIST => return error.WatchAlreadyExists,
else => |err| return unexpectedErrno(err),
}
}
pub fn inotify_rm_watch(inotify_fd: i32, wd: i32) void {
switch (errno(system.inotify_rm_watch(inotify_fd, wd))) {
.SUCCESS => return,
.BADF => unreachable,
.INVAL => unreachable,
else => unreachable,
}
}
pub const MProtectError = error{
AccessDenied,
OutOfMemory,
} || UnexpectedError;
pub fn mprotect(memory: []align(mem.page_size) u8, protection: u32) MProtectError!void {
assert(mem.isAligned(memory.len, mem.page_size));
if (builtin.os.tag == .windows) {
const win_prot: windows.DWORD = switch (@truncate(u3, protection)) {
0b000 => windows.PAGE_NOACCESS,
0b001 => windows.PAGE_READONLY,
0b010 => unreachable,
0b011 => windows.PAGE_READWRITE,
0b100 => windows.PAGE_EXECUTE,
0b101 => windows.PAGE_EXECUTE_READ,
0b110 => unreachable,
0b111 => windows.PAGE_EXECUTE_READWRITE,
};
var old: windows.DWORD = undefined;
windows.VirtualProtect(memory.ptr, memory.len, win_prot, &old) catch |err| switch (err) {
error.InvalidAddress => return error.AccessDenied,
error.Unexpected => return error.Unexpected,
};
} else {
switch (errno(system.mprotect(memory.ptr, memory.len, protection))) {
.SUCCESS => return,
.INVAL => unreachable,
.ACCES => return error.AccessDenied,
.NOMEM => return error.OutOfMemory,
else => |err| return unexpectedErrno(err),
}
}
}
pub const ForkError = error{SystemResources} || UnexpectedError;
pub fn fork() ForkError!pid_t {
const rc = system.fork();
switch (errno(rc)) {
.SUCCESS => return @intCast(pid_t, rc),
.AGAIN => return error.SystemResources,
.NOMEM => return error.SystemResources,
else => |err| return unexpectedErrno(err),
}
}
pub const MMapError = error{
MemoryMappingNotSupported,
AccessDenied,
PermissionDenied,
LockedMemoryLimitExceeded,
ProcessFdQuotaExceeded,
SystemFdQuotaExceeded,
OutOfMemory,
} || UnexpectedError;
pub fn mmap(
ptr: ?[*]align(mem.page_size) u8,
length: usize,
prot: u32,
flags: u32,
fd: fd_t,
offset: u64,
) MMapError![]align(mem.page_size) u8 {
const mmap_sym = if (builtin.os.tag == .linux and builtin.link_libc)
system.mmap64
else
system.mmap;
const ioffset = @bitCast(i64, offset);
const rc = mmap_sym(ptr, length, prot, flags, fd, ioffset);
const err = if (builtin.link_libc) blk: {
if (rc != std.c.MAP.FAILED) return @ptrCast([*]align(mem.page_size) u8, @alignCast(mem.page_size, rc))[0..length];
break :blk @intToEnum(E, system._errno().*);
} else blk: {
const err = errno(rc);
if (err == .SUCCESS) return @intToPtr([*]align(mem.page_size) u8, rc)[0..length];
break :blk err;
};
switch (err) {
.SUCCESS => unreachable,
.TXTBSY => return error.AccessDenied,
.ACCES => return error.AccessDenied,
.PERM => return error.PermissionDenied,
.AGAIN => return error.LockedMemoryLimitExceeded,
.BADF => unreachable,
.OVERFLOW => unreachable,
.NODEV => return error.MemoryMappingNotSupported,
.INVAL => unreachable,
.MFILE => return error.ProcessFdQuotaExceeded,
.NFILE => return error.SystemFdQuotaExceeded,
.NOMEM => return error.OutOfMemory,
else => return unexpectedErrno(err),
}
}
pub fn munmap(memory: []align(mem.page_size) const u8) void {
switch (errno(system.munmap(memory.ptr, memory.len))) {
.SUCCESS => return,
.INVAL => unreachable,
.NOMEM => unreachable,
else => unreachable,
}
}
pub const MSyncError = error{
UnmappedMemory,
} || UnexpectedError;
pub fn msync(memory: []align(mem.page_size) u8, flags: i32) MSyncError!void {
switch (errno(system.msync(memory.ptr, memory.len, flags))) {
.SUCCESS => return,
.NOMEM => return error.UnmappedMemory,
.INVAL => unreachable,
else => unreachable,
}
}
pub const AccessError = error{
PermissionDenied,
FileNotFound,
NameTooLong,
InputOutput,
SystemResources,
BadPathName,
FileBusy,
SymLinkLoop,
ReadOnlyFileSystem,
InvalidUtf8,
} || UnexpectedError;
pub fn access(path: []const u8, mode: u32) AccessError!void {
if (builtin.os.tag == .windows) {
const path_w = try windows.sliceToPrefixedFileW(path);
_ = try windows.GetFileAttributesW(path_w.span().ptr);
return;
} else if (builtin.os.tag == .wasi and !builtin.link_libc) {
return faccessat(wasi.AT.FDCWD, path, mode, 0);
}
const path_c = try toPosixPath(path);
return accessZ(&path_c, mode);
}
pub fn accessZ(path: [*:0]const u8, mode: u32) AccessError!void {
if (builtin.os.tag == .windows) {
const path_w = try windows.cStrToPrefixedFileW(path);
_ = try windows.GetFileAttributesW(path_w.span().ptr);
return;
} else if (builtin.os.tag == .wasi and !builtin.link_libc) {
return access(mem.sliceTo(path, 0), mode);
}
switch (errno(system.access(path, mode))) {
.SUCCESS => return,
.ACCES => return error.PermissionDenied,
.ROFS => return error.ReadOnlyFileSystem,
.LOOP => return error.SymLinkLoop,
.TXTBSY => return error.FileBusy,
.NOTDIR => return error.FileNotFound,
.NOENT => return error.FileNotFound,
.NAMETOOLONG => return error.NameTooLong,
.INVAL => unreachable,
.FAULT => unreachable,
.IO => return error.InputOutput,
.NOMEM => return error.SystemResources,
else => |err| return unexpectedErrno(err),
}
}
pub fn accessW(path: [*:0]const u16, mode: u32) windows.GetFileAttributesError!void {
_ = mode;
const ret = try windows.GetFileAttributesW(path);
if (ret != windows.INVALID_FILE_ATTRIBUTES) {
return;
}
switch (windows.kernel32.GetLastError()) {
.FILE_NOT_FOUND => return error.FileNotFound,
.PATH_NOT_FOUND => return error.FileNotFound,
.ACCESS_DENIED => return error.PermissionDenied,
else => |err| return windows.unexpectedError(err),
}
}
pub fn faccessat(dirfd: fd_t, path: []const u8, mode: u32, flags: u32) AccessError!void {
if (builtin.os.tag == .windows) {
const path_w = try windows.sliceToPrefixedFileW(path);
return faccessatW(dirfd, path_w.span().ptr, mode, flags);
} else if (builtin.os.tag == .wasi and !builtin.link_libc) {
var resolved = RelativePathWasi{ .dir_fd = dirfd, .relative_path = path };
const file = blk: {
break :blk fstatat(dirfd, path, flags);
} catch |err| switch (err) {
error.AccessDenied => return error.PermissionDenied,
else => |e| return e,
};
if (mode != F_OK) {
var directory: wasi.fdstat_t = undefined;
if (wasi.fd_fdstat_get(resolved.dir_fd, &directory) != .SUCCESS) {
return error.PermissionDenied;
}
var rights: wasi.rights_t = 0;
if (mode & R_OK != 0) {
rights |= if (file.filetype == .DIRECTORY)
wasi.RIGHT.FD_READDIR
else
wasi.RIGHT.FD_READ;
}
if (mode & W_OK != 0) {
rights |= wasi.RIGHT.FD_WRITE;
}
if ((rights & directory.fs_rights_inheriting) != rights) {
return error.PermissionDenied;
}
}
return;
}
const path_c = try toPosixPath(path);
return faccessatZ(dirfd, &path_c, mode, flags);
}
pub fn faccessatZ(dirfd: fd_t, path: [*:0]const u8, mode: u32, flags: u32) AccessError!void {
if (builtin.os.tag == .windows) {
const path_w = try windows.cStrToPrefixedFileW(path);
return faccessatW(dirfd, path_w.span().ptr, mode, flags);
} else if (builtin.os.tag == .wasi and !builtin.link_libc) {
return faccessat(dirfd, mem.sliceTo(path, 0), mode, flags);
}
switch (errno(system.faccessat(dirfd, path, mode, flags))) {
.SUCCESS => return,
.ACCES => return error.PermissionDenied,
.ROFS => return error.ReadOnlyFileSystem,
.LOOP => return error.SymLinkLoop,
.TXTBSY => return error.FileBusy,
.NOTDIR => return error.FileNotFound,
.NOENT => return error.FileNotFound,
.NAMETOOLONG => return error.NameTooLong,
.INVAL => unreachable,
.FAULT => unreachable,
.IO => return error.InputOutput,
.NOMEM => return error.SystemResources,
else => |err| return unexpectedErrno(err),
}
}
pub fn faccessatW(dirfd: fd_t, sub_path_w: [*:0]const u16, mode: u32, flags: u32) AccessError!void {
_ = mode;
_ = flags;
if (sub_path_w[0] == '.' and sub_path_w[1] == 0) {
return;
}
if (sub_path_w[0] == '.' and sub_path_w[1] == '.' and sub_path_w[2] == 0) {
return;
}
const path_len_bytes = math.cast(u16, mem.sliceTo(sub_path_w, 0).len * 2) orelse return error.NameTooLong;
var nt_name = windows.UNICODE_STRING{
.Length = path_len_bytes,
.MaximumLength = path_len_bytes,
.Buffer = @constCast(sub_path_w),
};
var attr = windows.OBJECT_ATTRIBUTES{
.Length = @sizeOf(windows.OBJECT_ATTRIBUTES),
.RootDirectory = if (std.fs.path.isAbsoluteWindowsW(sub_path_w)) null else dirfd,
.Attributes = 0,
.ObjectName = &nt_name,
.SecurityDescriptor = null,
.SecurityQualityOfService = null,
};
var basic_info: windows.FILE_BASIC_INFORMATION = undefined;
switch (windows.ntdll.NtQueryAttributesFile(&attr, &basic_info)) {
.SUCCESS => return,
.OBJECT_NAME_NOT_FOUND => return error.FileNotFound,
.OBJECT_PATH_NOT_FOUND => return error.FileNotFound,
.OBJECT_NAME_INVALID => unreachable,
.INVALID_PARAMETER => unreachable,
.ACCESS_DENIED => return error.PermissionDenied,
.OBJECT_PATH_SYNTAX_BAD => unreachable,
else => |rc| return windows.unexpectedStatus(rc),
}
}
pub const PipeError = error{
SystemFdQuotaExceeded,
ProcessFdQuotaExceeded,
} || UnexpectedError;
pub fn pipe() PipeError![2]fd_t {
var fds: [2]fd_t = undefined;
switch (errno(system.pipe(&fds))) {
.SUCCESS => return fds,
.INVAL => unreachable,
.FAULT => unreachable,
.NFILE => return error.SystemFdQuotaExceeded,
.MFILE => return error.ProcessFdQuotaExceeded,
else => |err| return unexpectedErrno(err),
}
}
pub fn pipe2(flags: u32) PipeError![2]fd_t {
if (@hasDecl(system, "pipe2")) {
var fds: [2]fd_t = undefined;
switch (errno(system.pipe2(&fds, flags))) {
.SUCCESS => return fds,
.INVAL => unreachable,
.FAULT => unreachable,
.NFILE => return error.SystemFdQuotaExceeded,
.MFILE => return error.ProcessFdQuotaExceeded,
else => |err| return unexpectedErrno(err),
}
}
var fds: [2]fd_t = try pipe();
errdefer {
close(fds[0]);
close(fds[1]);
}
if (flags == 0)
return fds;
if (flags & O.CLOEXEC != 0) {
for (fds) |fd| {
switch (errno(system.fcntl(fd, F.SETFD, @as(u32, FD_CLOEXEC)))) {
.SUCCESS => {},
.INVAL => unreachable,
.BADF => unreachable,
else => |err| return unexpectedErrno(err),
}
}
}
const new_flags = flags & ~@as(u32, O.CLOEXEC);
if (new_flags != 0) {
for (fds) |fd| {
switch (errno(system.fcntl(fd, F.SETFL, new_flags))) {
.SUCCESS => {},
.INVAL => unreachable,
.BADF => unreachable,
else => |err| return unexpectedErrno(err),
}
}
}
return fds;
}
pub const SysCtlError = error{
PermissionDenied,
SystemResources,
NameTooLong,
UnknownName,
} || UnexpectedError;
pub fn sysctl(
name: []const c_int,
oldp: ?*anyopaque,
oldlenp: ?*usize,
newp: ?*anyopaque,
newlen: usize,
) SysCtlError!void {
if (builtin.os.tag == .wasi or builtin.os.tag == .haiku) {
@compileError("unsupported OS");
}
const name_len = math.cast(c_uint, name.len) orelse return error.NameTooLong;
switch (errno(system.sysctl(name.ptr, name_len, oldp, oldlenp, newp, newlen))) {
.SUCCESS => return,
.FAULT => unreachable,
.PERM => return error.PermissionDenied,
.NOMEM => return error.SystemResources,
.NOENT => return error.UnknownName,
else => |err| return unexpectedErrno(err),
}
}
pub fn sysctlbynameZ(
name: [*:0]const u8,
oldp: ?*anyopaque,
oldlenp: ?*usize,
newp: ?*anyopaque,
newlen: usize,
) SysCtlError!void {
if (builtin.os.tag == .wasi or builtin.os.tag == .haiku) {
@compileError("unsupported OS");
}
switch (errno(system.sysctlbyname(name, oldp, oldlenp, newp, newlen))) {
.SUCCESS => return,
.FAULT => unreachable,
.PERM => return error.PermissionDenied,
.NOMEM => return error.SystemResources,
.NOENT => return error.UnknownName,
else => |err| return unexpectedErrno(err),
}
}
pub fn gettimeofday(tv: ?*timeval, tz: ?*timezone) void {
switch (errno(system.gettimeofday(tv, tz))) {
.SUCCESS => return,
.INVAL => unreachable,
else => unreachable,
}
}
pub const SeekError = error{
Unseekable,
AccessDenied,
} || UnexpectedError;
pub fn lseek_SET(fd: fd_t, offset: u64) SeekError!void {
if (builtin.os.tag == .linux and !builtin.link_libc and @sizeOf(usize) == 4) {
var result: u64 = undefined;
switch (errno(system.llseek(fd, offset, &result, SEEK.SET))) {
.SUCCESS => return,
.BADF => unreachable,
.INVAL => return error.Unseekable,
.OVERFLOW => return error.Unseekable,
.SPIPE => return error.Unseekable,
.NXIO => return error.Unseekable,
else => |err| return unexpectedErrno(err),
}
}
if (builtin.os.tag == .windows) {
return windows.SetFilePointerEx_BEGIN(fd, offset);
}
if (builtin.os.tag == .wasi and !builtin.link_libc) {
var new_offset: wasi.filesize_t = undefined;
switch (wasi.fd_seek(fd, @bitCast(wasi.filedelta_t, offset), .SET, &new_offset)) {
.SUCCESS => return,
.BADF => unreachable,
.INVAL => return error.Unseekable,
.OVERFLOW => return error.Unseekable,
.SPIPE => return error.Unseekable,
.NXIO => return error.Unseekable,
.NOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
const lseek_sym = if (builtin.os.tag == .linux and builtin.link_libc)
system.lseek64
else
system.lseek;
const ioffset = @bitCast(i64, offset);
switch (errno(lseek_sym(fd, ioffset, SEEK.SET))) {
.SUCCESS => return,
.BADF => unreachable,
.INVAL => return error.Unseekable,
.OVERFLOW => return error.Unseekable,
.SPIPE => return error.Unseekable,
.NXIO => return error.Unseekable,
else => |err| return unexpectedErrno(err),
}
}
pub fn lseek_CUR(fd: fd_t, offset: i64) SeekError!void {
if (builtin.os.tag == .linux and !builtin.link_libc and @sizeOf(usize) == 4) {
var result: u64 = undefined;
switch (errno(system.llseek(fd, @bitCast(u64, offset), &result, SEEK.CUR))) {
.SUCCESS => return,
.BADF => unreachable,
.INVAL => return error.Unseekable,
.OVERFLOW => return error.Unseekable,
.SPIPE => return error.Unseekable,
.NXIO => return error.Unseekable,
else => |err| return unexpectedErrno(err),
}
}
if (builtin.os.tag == .windows) {
return windows.SetFilePointerEx_CURRENT(fd, offset);
}
if (builtin.os.tag == .wasi and !builtin.link_libc) {
var new_offset: wasi.filesize_t = undefined;
switch (wasi.fd_seek(fd, offset, .CUR, &new_offset)) {
.SUCCESS => return,
.BADF => unreachable,
.INVAL => return error.Unseekable,
.OVERFLOW => return error.Unseekable,
.SPIPE => return error.Unseekable,
.NXIO => return error.Unseekable,
.NOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
const lseek_sym = if (builtin.os.tag == .linux and builtin.link_libc)
system.lseek64
else
system.lseek;
const ioffset = @bitCast(i64, offset);
switch (errno(lseek_sym(fd, ioffset, SEEK.CUR))) {
.SUCCESS => return,
.BADF => unreachable,
.INVAL => return error.Unseekable,
.OVERFLOW => return error.Unseekable,
.SPIPE => return error.Unseekable,
.NXIO => return error.Unseekable,
else => |err| return unexpectedErrno(err),
}
}
pub fn lseek_END(fd: fd_t, offset: i64) SeekError!void {
if (builtin.os.tag == .linux and !builtin.link_libc and @sizeOf(usize) == 4) {
var result: u64 = undefined;
switch (errno(system.llseek(fd, @bitCast(u64, offset), &result, SEEK.END))) {
.SUCCESS => return,
.BADF => unreachable,
.INVAL => return error.Unseekable,
.OVERFLOW => return error.Unseekable,
.SPIPE => return error.Unseekable,
.NXIO => return error.Unseekable,
else => |err| return unexpectedErrno(err),
}
}
if (builtin.os.tag == .windows) {
return windows.SetFilePointerEx_END(fd, offset);
}
if (builtin.os.tag == .wasi and !builtin.link_libc) {
var new_offset: wasi.filesize_t = undefined;
switch (wasi.fd_seek(fd, offset, .END, &new_offset)) {
.SUCCESS => return,
.BADF => unreachable,
.INVAL => return error.Unseekable,
.OVERFLOW => return error.Unseekable,
.SPIPE => return error.Unseekable,
.NXIO => return error.Unseekable,
.NOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
const lseek_sym = if (builtin.os.tag == .linux and builtin.link_libc)
system.lseek64
else
system.lseek;
const ioffset = @bitCast(i64, offset);
switch (errno(lseek_sym(fd, ioffset, SEEK.END))) {
.SUCCESS => return,
.BADF => unreachable,
.INVAL => return error.Unseekable,
.OVERFLOW => return error.Unseekable,
.SPIPE => return error.Unseekable,
.NXIO => return error.Unseekable,
else => |err| return unexpectedErrno(err),
}
}
pub fn lseek_CUR_get(fd: fd_t) SeekError!u64 {
if (builtin.os.tag == .linux and !builtin.link_libc and @sizeOf(usize) == 4) {
var result: u64 = undefined;
switch (errno(system.llseek(fd, 0, &result, SEEK.CUR))) {
.SUCCESS => return result,
.BADF => unreachable,
.INVAL => return error.Unseekable,
.OVERFLOW => return error.Unseekable,
.SPIPE => return error.Unseekable,
.NXIO => return error.Unseekable,
else => |err| return unexpectedErrno(err),
}
}
if (builtin.os.tag == .windows) {
return windows.SetFilePointerEx_CURRENT_get(fd);
}
if (builtin.os.tag == .wasi and !builtin.link_libc) {
var new_offset: wasi.filesize_t = undefined;
switch (wasi.fd_seek(fd, 0, .CUR, &new_offset)) {
.SUCCESS => return new_offset,
.BADF => unreachable,
.INVAL => return error.Unseekable,
.OVERFLOW => return error.Unseekable,
.SPIPE => return error.Unseekable,
.NXIO => return error.Unseekable,
.NOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
const lseek_sym = if (builtin.os.tag == .linux and builtin.link_libc)
system.lseek64
else
system.lseek;
const rc = lseek_sym(fd, 0, SEEK.CUR);
switch (errno(rc)) {
.SUCCESS => return @bitCast(u64, rc),
.BADF => unreachable,
.INVAL => return error.Unseekable,
.OVERFLOW => return error.Unseekable,
.SPIPE => return error.Unseekable,
.NXIO => return error.Unseekable,
else => |err| return unexpectedErrno(err),
}
}
pub const FcntlError = error{
PermissionDenied,
FileBusy,
ProcessFdQuotaExceeded,
Locked,
DeadLock,
LockedRegionLimitExceeded,
} || UnexpectedError;
pub fn fcntl(fd: fd_t, cmd: i32, arg: usize) FcntlError!usize {
while (true) {
const rc = system.fcntl(fd, cmd, arg);
switch (errno(rc)) {
.SUCCESS => return @intCast(usize, rc),
.INTR => continue,
.AGAIN, .ACCES => return error.Locked,
.BADF => unreachable,
.BUSY => return error.FileBusy,
.INVAL => unreachable,
.PERM => return error.PermissionDenied,
.MFILE => return error.ProcessFdQuotaExceeded,
.NOTDIR => unreachable,
.DEADLK => return error.DeadLock,
.NOLCK => return error.LockedRegionLimitExceeded,
else => |err| return unexpectedErrno(err),
}
}
}
fn setSockFlags(sock: socket_t, flags: u32) !void {
if ((flags & SOCK.CLOEXEC) != 0) {
if (builtin.os.tag == .windows) {
} else {
var fd_flags = fcntl(sock, F.GETFD, 0) catch |err| switch (err) {
error.FileBusy => unreachable,
error.Locked => unreachable,
error.PermissionDenied => unreachable,
error.DeadLock => unreachable,
error.LockedRegionLimitExceeded => unreachable,
else => |e| return e,
};
fd_flags |= FD_CLOEXEC;
_ = fcntl(sock, F.SETFD, fd_flags) catch |err| switch (err) {
error.FileBusy => unreachable,
error.Locked => unreachable,
error.PermissionDenied => unreachable,
error.DeadLock => unreachable,
error.LockedRegionLimitExceeded => unreachable,
else => |e| return e,
};
}
}
if ((flags & SOCK.NONBLOCK) != 0) {
if (builtin.os.tag == .windows) {
var mode: c_ulong = 1;
if (windows.ws2_32.ioctlsocket(sock, windows.ws2_32.FIONBIO, &mode) == windows.ws2_32.SOCKET_ERROR) {
switch (windows.ws2_32.WSAGetLastError()) {
.WSANOTINITIALISED => unreachable,
.WSAENETDOWN => return error.NetworkSubsystemFailed,
.WSAENOTSOCK => return error.FileDescriptorNotASocket,
else => |err| return windows.unexpectedWSAError(err),
}
}
} else {
var fl_flags = fcntl(sock, F.GETFL, 0) catch |err| switch (err) {
error.FileBusy => unreachable,
error.Locked => unreachable,
error.PermissionDenied => unreachable,
error.DeadLock => unreachable,
error.LockedRegionLimitExceeded => unreachable,
else => |e| return e,
};
fl_flags |= O.NONBLOCK;
_ = fcntl(sock, F.SETFL, fl_flags) catch |err| switch (err) {
error.FileBusy => unreachable,
error.Locked => unreachable,
error.PermissionDenied => unreachable,
error.DeadLock => unreachable,
error.LockedRegionLimitExceeded => unreachable,
else => |e| return e,
};
}
}
}
pub const FlockError = error{
WouldBlock,
SystemResources,
FileLocksNotSupported,
} || UnexpectedError;
pub fn flock(fd: fd_t, operation: i32) FlockError!void {
while (true) {
const rc = system.flock(fd, operation);
switch (errno(rc)) {
.SUCCESS => return,
.BADF => unreachable,
.INTR => continue,
.INVAL => unreachable,
.NOLCK => return error.SystemResources,
.AGAIN => return error.WouldBlock,
.OPNOTSUPP => return error.FileLocksNotSupported,
else => |err| return unexpectedErrno(err),
}
}
}
pub const RealPathError = error{
FileNotFound,
AccessDenied,
NameTooLong,
NotSupported,
NotDir,
SymLinkLoop,
InputOutput,
FileTooBig,
IsDir,
ProcessFdQuotaExceeded,
SystemFdQuotaExceeded,
NoDevice,
SystemResources,
NoSpaceLeft,
FileSystem,
BadPathName,
DeviceBusy,
SharingViolation,
PipeBusy,
InvalidHandle,
InvalidUtf8,
PathAlreadyExists,
} || UnexpectedError;
pub fn realpath(pathname: []const u8, out_buffer: *[MAX_PATH_BYTES]u8) RealPathError![]u8 {
if (builtin.os.tag == .windows) {
const pathname_w = try windows.sliceToPrefixedFileW(pathname);
return realpathW(pathname_w.span(), out_buffer);
} else if (builtin.os.tag == .wasi and !builtin.link_libc) {
@compileError("WASI does not support os.realpath");
}
const pathname_c = try toPosixPath(pathname);
return realpathZ(&pathname_c, out_buffer);
}
pub fn realpathZ(pathname: [*:0]const u8, out_buffer: *[MAX_PATH_BYTES]u8) RealPathError![]u8 {
if (builtin.os.tag == .windows) {
const pathname_w = try windows.cStrToPrefixedFileW(pathname);
return realpathW(pathname_w.span(), out_buffer);
} else if (builtin.os.tag == .wasi and !builtin.link_libc) {
return realpath(mem.sliceTo(pathname, 0), out_buffer);
}
if (!builtin.link_libc) {
const flags = if (builtin.os.tag == .linux) O.PATH | O.NONBLOCK | O.CLOEXEC else O.NONBLOCK | O.CLOEXEC;
const fd = openZ(pathname, flags, 0) catch |err| switch (err) {
error.FileLocksNotSupported => unreachable,
error.WouldBlock => unreachable,
error.FileBusy => unreachable,
error.InvalidHandle => unreachable,
else => |e| return e,
};
defer close(fd);
return getFdPath(fd, out_buffer);
}
const result_path = std.c.realpath(pathname, out_buffer) orelse switch (@intToEnum(E, std.c._errno().*)) {
.SUCCESS => unreachable,
.INVAL => unreachable,
.BADF => unreachable,
.FAULT => unreachable,
.ACCES => return error.AccessDenied,
.NOENT => return error.FileNotFound,
.OPNOTSUPP => return error.NotSupported,
.NOTDIR => return error.NotDir,
.NAMETOOLONG => return error.NameTooLong,
.LOOP => return error.SymLinkLoop,
.IO => return error.InputOutput,
else => |err| return unexpectedErrno(err),
};
return mem.sliceTo(result_path, 0);
}
pub fn realpathW(pathname: []const u16, out_buffer: *[MAX_PATH_BYTES]u8) RealPathError![]u8 {
const w = windows;
const dir = std.fs.cwd().fd;
const access_mask = w.GENERIC_READ | w.SYNCHRONIZE;
const share_access = w.FILE_SHARE_READ;
const creation = w.FILE_OPEN;
const h_file = blk: {
const res = w.OpenFile(pathname, .{
.dir = dir,
.access_mask = access_mask,
.share_access = share_access,
.creation = creation,
.io_mode = .blocking,
}) catch |err| switch (err) {
error.IsDir => break :blk w.OpenFile(pathname, .{
.dir = dir,
.access_mask = access_mask,
.share_access = share_access,
.creation = creation,
.io_mode = .blocking,
.filter = .dir_only,
}) catch |er| switch (er) {
error.WouldBlock => unreachable,
else => |e2| return e2,
},
error.WouldBlock => unreachable,
else => |e| return e,
};
break :blk res;
};
defer w.CloseHandle(h_file);
return getFdPath(h_file, out_buffer);
}
pub fn getFdPath(fd: fd_t, out_buffer: *[MAX_PATH_BYTES]u8) RealPathError![]u8 {
switch (builtin.os.tag) {
.windows => {
var wide_buf: [windows.PATH_MAX_WIDE]u16 = undefined;
const wide_slice = try windows.GetFinalPathNameByHandle(fd, .{}, wide_buf[0..]);
const end_index = std.unicode.utf16leToUtf8(out_buffer, wide_slice) catch unreachable;
return out_buffer[0..end_index];
},
.macos, .ios, .watchos, .tvos => {
@memset(out_buffer[0..MAX_PATH_BYTES], 0);
switch (errno(system.fcntl(fd, F.GETPATH, out_buffer))) {
.SUCCESS => {},
.BADF => return error.FileNotFound,
.NOSPC => return error.NameTooLong,
else => |err| return unexpectedErrno(err),
}
const len = mem.indexOfScalar(u8, out_buffer[0..], @as(u8, 0)) orelse MAX_PATH_BYTES;
return out_buffer[0..len];
},
.linux => {
var procfs_buf: ["/proc/self/fd/-2147483648\x00".len]u8 = undefined;
const proc_path = std.fmt.bufPrintZ(procfs_buf[0..], "/proc/self/fd/{d}", .{fd}) catch unreachable;
const target = readlinkZ(proc_path, out_buffer) catch |err| {
switch (err) {
error.UnsupportedReparsePointType => unreachable,
error.NotLink => unreachable,
else => |e| return e,
}
};
return target;
},
.solaris => {
var procfs_buf: ["/proc/self/path/-2147483648\x00".len]u8 = undefined;
const proc_path = std.fmt.bufPrintZ(procfs_buf[0..], "/proc/self/path/{d}", .{fd}) catch unreachable;
const target = readlinkZ(proc_path, out_buffer) catch |err| switch (err) {
error.UnsupportedReparsePointType => unreachable,
error.NotLink => unreachable,
else => |e| return e,
};
return target;
},
.freebsd => {
if (comptime builtin.os.version_range.semver.max.order(.{ .major = 13, .minor = 0 }) == .gt) {
var kfile: system.kinfo_file = undefined;
kfile.structsize = system.KINFO_FILE_SIZE;
switch (errno(system.fcntl(fd, system.F.KINFO, @ptrToInt(&kfile)))) {
.SUCCESS => {},
.BADF => return error.FileNotFound,
else => |err| return unexpectedErrno(err),
}
const len = mem.indexOfScalar(u8, &kfile.path, 0) orelse MAX_PATH_BYTES;
if (len == 0) return error.NameTooLong;
mem.copy(u8, out_buffer, kfile.path[0..len]);
return out_buffer[0..len];
} else {
var mib = [4]c_int{ CTL.KERN, KERN.PROC, KERN.PROC_FILEDESC, system.getpid() };
var len: usize = undefined;
sysctl(&mib, null, &len, null, 0) catch |err| switch (err) {
error.PermissionDenied => unreachable,
error.SystemResources => return error.SystemResources,
error.NameTooLong => unreachable,
error.UnknownName => unreachable,
else => return error.Unexpected,
};
len = len * 4 / 3;
const buf = std.heap.c_allocator.alloc(u8, len) catch return error.SystemResources;
defer std.heap.c_allocator.free(buf);
len = buf.len;
sysctl(&mib, &buf[0], &len, null, 0) catch |err| switch (err) {
error.PermissionDenied => unreachable,
error.SystemResources => return error.SystemResources,
error.NameTooLong => unreachable,
error.UnknownName => unreachable,
else => return error.Unexpected,
};
var i: usize = 0;
while (i < len) {
const kf: *align(1) system.kinfo_file = @ptrCast(*align(1) system.kinfo_file, &buf[i]);
if (kf.fd == fd) {
len = mem.indexOfScalar(u8, &kf.path, 0) orelse MAX_PATH_BYTES;
if (len == 0) return error.NameTooLong;
mem.copy(u8, out_buffer, kf.path[0..len]);
return out_buffer[0..len];
}
i += @intCast(usize, kf.structsize);
}
return error.InvalidHandle;
}
},
.dragonfly => {
if (comptime builtin.os.version_range.semver.max.order(.{ .major = 6, .minor = 0 }) == .lt) {
@compileError("querying for canonical path of a handle is unsupported on this host");
}
@memset(out_buffer[0..MAX_PATH_BYTES], 0);
switch (errno(system.fcntl(fd, F.GETPATH, out_buffer))) {
.SUCCESS => {},
.BADF => return error.FileNotFound,
.RANGE => return error.NameTooLong,
else => |err| return unexpectedErrno(err),
}
const len = mem.indexOfScalar(u8, out_buffer[0..], @as(u8, 0)) orelse MAX_PATH_BYTES;
return out_buffer[0..len];
},
.netbsd => {
if (comptime builtin.os.version_range.semver.max.order(.{ .major = 10, .minor = 0 }) == .lt) {
@compileError("querying for canonical path of a handle is unsupported on this host");
}
@memset(out_buffer[0..MAX_PATH_BYTES], 0);
switch (errno(system.fcntl(fd, F.GETPATH, out_buffer))) {
.SUCCESS => {},
.ACCES => return error.AccessDenied,
.BADF => return error.FileNotFound,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.RANGE => return error.NameTooLong,
else => |err| return unexpectedErrno(err),
}
const len = mem.indexOfScalar(u8, out_buffer[0..], @as(u8, 0)) orelse MAX_PATH_BYTES;
return out_buffer[0..len];
},
else => @compileError("querying for canonical path of a handle is unsupported on this host"),
}
}
pub fn nanosleep(seconds: u64, nanoseconds: u64) void {
var req = timespec{
.tv_sec = math.cast(isize, seconds) orelse math.maxInt(isize),
.tv_nsec = math.cast(isize, nanoseconds) orelse math.maxInt(isize),
};
var rem: timespec = undefined;
while (true) {
switch (errno(system.nanosleep(&req, &rem))) {
.FAULT => unreachable,
.INVAL => {
return;
},
.INTR => {
req = rem;
continue;
},
else => return,
}
}
}
pub fn dl_iterate_phdr(
context: anytype,
comptime Error: type,
comptime callback: fn (info: *dl_phdr_info, size: usize, context: @TypeOf(context)) Error!void,
) Error!void {
const Context = @TypeOf(context);
switch (builtin.object_format) {
.elf, .c => {},
else => @compileError("dl_iterate_phdr is not available for this target"),
}
if (builtin.link_libc) {
switch (system.dl_iterate_phdr(struct {
fn callbackC(info: *dl_phdr_info, size: usize, data: ?*anyopaque) callconv(.C) c_int {
const context_ptr = @ptrCast(*const Context, @alignCast(@alignOf(*const Context), data));
callback(info, size, context_ptr.*) catch |err| return @errorToInt(err);
return 0;
}
}.callbackC, @intToPtr(?*anyopaque, @ptrToInt(&context)))) {
0 => return,
else => |err| return @errSetCast(Error, @intToError(@intCast(u16, err))),
}
}
const elf_base = std.process.getBaseAddress();
const ehdr = @intToPtr(*elf.Ehdr, elf_base);
assert(mem.eql(u8, ehdr.e_ident[0..4], elf.MAGIC));
const n_phdr = ehdr.e_phnum;
const phdrs = (@intToPtr([*]elf.Phdr, elf_base + ehdr.e_phoff))[0..n_phdr];
var it = dl.linkmap_iterator(phdrs) catch unreachable;
if (it.end()) {
const base_address = for (phdrs) |*phdr| {
if (phdr.p_type == elf.PT_PHDR) {
break @ptrToInt(phdrs.ptr) - phdr.p_vaddr;
}
} else unreachable;
var info = dl_phdr_info{
.dlpi_addr = base_address,
.dlpi_name = "/proc/self/exe",
.dlpi_phdr = phdrs.ptr,
.dlpi_phnum = ehdr.e_phnum,
};
return callback(&info, @sizeOf(dl_phdr_info), context);
}
while (it.next()) |entry| {
var dlpi_phdr: [*]elf.Phdr = undefined;
var dlpi_phnum: u16 = undefined;
if (entry.l_addr != 0) {
const elf_header = @intToPtr(*elf.Ehdr, entry.l_addr);
dlpi_phdr = @intToPtr([*]elf.Phdr, entry.l_addr + elf_header.e_phoff);
dlpi_phnum = elf_header.e_phnum;
} else {
dlpi_phdr = @intToPtr([*]elf.Phdr, elf_base + ehdr.e_phoff);
dlpi_phnum = ehdr.e_phnum;
}
var info = dl_phdr_info{
.dlpi_addr = entry.l_addr,
.dlpi_name = entry.l_name,
.dlpi_phdr = dlpi_phdr,
.dlpi_phnum = dlpi_phnum,
};
try callback(&info, @sizeOf(dl_phdr_info), context);
}
}
pub const ClockGetTimeError = error{UnsupportedClock} || UnexpectedError;
pub fn clock_gettime(clk_id: i32, tp: *timespec) ClockGetTimeError!void {
if (builtin.os.tag == .wasi and !builtin.link_libc) {
var ts: timestamp_t = undefined;
switch (system.clock_time_get(@bitCast(u32, clk_id), 1, &ts)) {
.SUCCESS => {
tp.* = .{
.tv_sec = @intCast(i64, ts / std.time.ns_per_s),
.tv_nsec = @intCast(isize, ts % std.time.ns_per_s),
};
},
.INVAL => return error.UnsupportedClock,
else => |err| return unexpectedErrno(err),
}
return;
}
if (builtin.os.tag == .windows) {
if (clk_id == CLOCK.REALTIME) {
var ft: windows.FILETIME = undefined;
windows.kernel32.GetSystemTimeAsFileTime(&ft);
const ft64 = (@as(u64, ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
const ft_per_s = std.time.ns_per_s / 100;
tp.* = .{
.tv_sec = @intCast(i64, ft64 / ft_per_s) + std.time.epoch.windows,
.tv_nsec = @intCast(c_long, ft64 % ft_per_s) * 100,
};
return;
} else {
return error.UnsupportedClock;
}
}
switch (errno(system.clock_gettime(clk_id, tp))) {
.SUCCESS => return,
.FAULT => unreachable,
.INVAL => return error.UnsupportedClock,
else => |err| return unexpectedErrno(err),
}
}
pub fn clock_getres(clk_id: i32, res: *timespec) ClockGetTimeError!void {
if (builtin.os.tag == .wasi and !builtin.link_libc) {
var ts: timestamp_t = undefined;
switch (system.clock_res_get(@bitCast(u32, clk_id), &ts)) {
.SUCCESS => res.* = .{
.tv_sec = @intCast(i64, ts / std.time.ns_per_s),
.tv_nsec = @intCast(isize, ts % std.time.ns_per_s),
},
.INVAL => return error.UnsupportedClock,
else => |err| return unexpectedErrno(err),
}
return;
}
switch (errno(system.clock_getres(clk_id, res))) {
.SUCCESS => return,
.FAULT => unreachable,
.INVAL => return error.UnsupportedClock,
else => |err| return unexpectedErrno(err),
}
}
pub const SchedGetAffinityError = error{PermissionDenied} || UnexpectedError;
pub fn sched_getaffinity(pid: pid_t) SchedGetAffinityError!cpu_set_t {
var set: cpu_set_t = undefined;
if (builtin.os.tag == .linux) {
switch (errno(system.sched_getaffinity(pid, @sizeOf(cpu_set_t), &set))) {
.SUCCESS => return set,
.FAULT => unreachable,
.INVAL => unreachable,
.SRCH => unreachable,
.PERM => return error.PermissionDenied,
else => |err| return unexpectedErrno(err),
}
} else if (builtin.os.tag == .freebsd) {
switch (errno(freebsd.cpuset_getaffinity(freebsd.CPU_LEVEL_WHICH, freebsd.CPU_WHICH_PID, pid, @sizeOf(cpu_set_t), &set))) {
.SUCCESS => return set,
.FAULT => unreachable,
.INVAL => unreachable,
.SRCH => unreachable,
.EDEADLK => unreachable,
.PERM => return error.PermissionDenied,
else => |err| return unexpectedErrno(err),
}
} else {
@compileError("unsupported platform");
}
}
pub fn toPosixPath(file_path: []const u8) ![MAX_PATH_BYTES - 1:0]u8 {
if (std.debug.runtime_safety) assert(std.mem.indexOfScalar(u8, file_path, 0) == null);
var path_with_null: [MAX_PATH_BYTES - 1:0]u8 = undefined;
if (file_path.len >= MAX_PATH_BYTES) return error.NameTooLong;
@memcpy(path_with_null[0..file_path.len], file_path);
path_with_null[file_path.len] = 0;
return path_with_null;
}
pub const unexpected_error_tracing = builtin.zig_backend == .stage2_llvm and builtin.mode == .Debug;
pub const UnexpectedError = error{
Unexpected,
};
pub fn unexpectedErrno(err: E) UnexpectedError {
if (unexpected_error_tracing) {
std.debug.print("unexpected errno: {d}\n", .{@enumToInt(err)});
std.debug.dumpCurrentStackTrace(null);
}
return error.Unexpected;
}
pub const SigaltstackError = error{
SizeTooSmall,
PermissionDenied,
} || UnexpectedError;
pub fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) SigaltstackError!void {
switch (errno(system.sigaltstack(ss, old_ss))) {
.SUCCESS => return,
.FAULT => unreachable,
.INVAL => unreachable,
.NOMEM => return error.SizeTooSmall,
.PERM => return error.PermissionDenied,
else => |err| return unexpectedErrno(err),
}
}
pub fn sigaction(sig: u6, noalias act: ?*const Sigaction, noalias oact: ?*Sigaction) error{OperationNotSupported}!void {
switch (errno(system.sigaction(sig, act, oact))) {
.SUCCESS => return,
.INVAL, .NOSYS => return error.OperationNotSupported,
else => unreachable,
}
}
pub fn sigprocmask(flags: u32, noalias set: ?*const sigset_t, noalias oldset: ?*sigset_t) void {
switch (errno(system.sigprocmask(flags, set, oldset))) {
.SUCCESS => return,
.FAULT => unreachable,
.INVAL => unreachable,
else => unreachable,
}
}
pub const FutimensError = error{
AccessDenied,
PermissionDenied,
ReadOnlyFileSystem,
} || UnexpectedError;
pub fn futimens(fd: fd_t, times: *const [2]timespec) FutimensError!void {
if (builtin.os.tag == .wasi and !builtin.link_libc) {
const atim = times[0].toTimestamp();
const mtim = times[1].toTimestamp();
switch (wasi.fd_filestat_set_times(fd, atim, mtim, wasi.FILESTAT_SET_ATIM | wasi.FILESTAT_SET_MTIM)) {
.SUCCESS => return,
.ACCES => return error.AccessDenied,
.PERM => return error.PermissionDenied,
.BADF => unreachable,
.FAULT => unreachable,
.INVAL => unreachable,
.ROFS => return error.ReadOnlyFileSystem,
else => |err| return unexpectedErrno(err),
}
}
switch (errno(system.futimens(fd, times))) {
.SUCCESS => return,
.ACCES => return error.AccessDenied,
.PERM => return error.PermissionDenied,
.BADF => unreachable,
.FAULT => unreachable,
.INVAL => unreachable,
.ROFS => return error.ReadOnlyFileSystem,
else => |err| return unexpectedErrno(err),
}
}
pub const GetHostNameError = error{PermissionDenied} || UnexpectedError;
pub fn gethostname(name_buffer: *[HOST_NAME_MAX]u8) GetHostNameError![]u8 {
if (builtin.link_libc) {
switch (errno(system.gethostname(name_buffer, name_buffer.len))) {
.SUCCESS => return mem.sliceTo(name_buffer, 0),
.FAULT => unreachable,
.NAMETOOLONG => unreachable,
.PERM => return error.PermissionDenied,
else => |err| return unexpectedErrno(err),
}
}
if (builtin.os.tag == .linux) {
const uts = uname();
const hostname = mem.sliceTo(&uts.nodename, 0);
mem.copy(u8, name_buffer, hostname);
return name_buffer[0..hostname.len];
}
@compileError("TODO implement gethostname for this OS");
}
pub fn uname() utsname {
var uts: utsname = undefined;
switch (errno(system.uname(&uts))) {
.SUCCESS => return uts,
.FAULT => unreachable,
else => unreachable,
}
}
pub fn res_mkquery(
op: u4,
dname: []const u8,
class: u8,
ty: u8,
data: []const u8,
newrr: ?[*]const u8,
buf: []u8,
) usize {
_ = data;
_ = newrr;
var name = dname;
if (mem.endsWith(u8, name, ".")) name.len -= 1;
assert(name.len <= 253);
const n = 17 + name.len + @boolToInt(name.len != 0);
var q: [280]u8 = undefined;
@memset(q[0..n], 0);
q[2] = @as(u8, op) * 8 + 1;
q[5] = 1;
mem.copy(u8, q[13..], name);
var i: usize = 13;
var j: usize = undefined;
while (q[i] != 0) : (i = j + 1) {
j = i;
while (q[j] != 0 and q[j] != '.') : (j += 1) {}
if (j - i - 1 > 62) unreachable;
q[i - 1] = @intCast(u8, j - i);
}
q[i + 1] = ty;
q[i + 3] = class;
var ts: timespec = undefined;
clock_gettime(CLOCK.REALTIME, &ts) catch {};
const UInt = std.meta.Int(.unsigned, @bitSizeOf(@TypeOf(ts.tv_nsec)));
const unsec = @bitCast(UInt, ts.tv_nsec);
const id = @truncate(u32, unsec + unsec / 65536);
q[0] = @truncate(u8, id / 256);
q[1] = @truncate(u8, id);
mem.copy(u8, buf, q[0..n]);
return n;
}
pub const SendError = error{
AccessDenied,
WouldBlock,
FastOpenAlreadyInProgress,
ConnectionResetByPeer,
MessageTooBig,
SystemResources,
BrokenPipe,
FileDescriptorNotASocket,
NetworkUnreachable,
NetworkSubsystemFailed,
} || UnexpectedError;
pub const SendMsgError = SendError || error{
AddressFamilyNotSupported,
SymLinkLoop,
NameTooLong,
FileNotFound,
NotDir,
SocketNotConnected,
AddressNotAvailable,
};
pub fn sendmsg(
sockfd: socket_t,
msg: *const msghdr_const,
flags: u32,
) SendMsgError!usize {
while (true) {
const rc = system.sendmsg(sockfd, msg, flags);
if (builtin.os.tag == .windows) {
if (rc == windows.ws2_32.SOCKET_ERROR) {
switch (windows.ws2_32.WSAGetLastError()) {
.WSAEACCES => return error.AccessDenied,
.WSAEADDRNOTAVAIL => return error.AddressNotAvailable,
.WSAECONNRESET => return error.ConnectionResetByPeer,
.WSAEMSGSIZE => return error.MessageTooBig,
.WSAENOBUFS => return error.SystemResources,
.WSAENOTSOCK => return error.FileDescriptorNotASocket,
.WSAEAFNOSUPPORT => return error.AddressFamilyNotSupported,
.WSAEDESTADDRREQ => unreachable,
.WSAEFAULT => unreachable,
.WSAEHOSTUNREACH => return error.NetworkUnreachable,
.WSAEINVAL => unreachable,
.WSAENETDOWN => return error.NetworkSubsystemFailed,
.WSAENETRESET => return error.ConnectionResetByPeer,
.WSAENETUNREACH => return error.NetworkUnreachable,
.WSAENOTCONN => return error.SocketNotConnected,
.WSAESHUTDOWN => unreachable,
.WSAEWOULDBLOCK => return error.WouldBlock,
.WSANOTINITIALISED => unreachable,
else => |err| return windows.unexpectedWSAError(err),
}
} else {
return @intCast(usize, rc);
}
} else {
switch (errno(rc)) {
.SUCCESS => return @intCast(usize, rc),
.ACCES => return error.AccessDenied,
.AGAIN => return error.WouldBlock,
.ALREADY => return error.FastOpenAlreadyInProgress,
.BADF => unreachable,
.CONNRESET => return error.ConnectionResetByPeer,
.DESTADDRREQ => unreachable,
.FAULT => unreachable,
.INTR => continue,
.INVAL => unreachable,
.ISCONN => unreachable,
.MSGSIZE => return error.MessageTooBig,
.NOBUFS => return error.SystemResources,
.NOMEM => return error.SystemResources,
.NOTSOCK => unreachable,
.OPNOTSUPP => unreachable,
.PIPE => return error.BrokenPipe,
.AFNOSUPPORT => return error.AddressFamilyNotSupported,
.LOOP => return error.SymLinkLoop,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.NotDir,
.HOSTUNREACH => return error.NetworkUnreachable,
.NETUNREACH => return error.NetworkUnreachable,
.NOTCONN => return error.SocketNotConnected,
.NETDOWN => return error.NetworkSubsystemFailed,
else => |err| return unexpectedErrno(err),
}
}
}
}
pub const SendToError = SendMsgError || error{
UnreachableAddress,
};
pub fn sendto(
sockfd: socket_t,
buf: []const u8,
flags: u32,
dest_addr: ?*const sockaddr,
addrlen: socklen_t,
) SendToError!usize {
if (builtin.os.tag == .windows) {
switch (windows.ws2_32.sendto(sockfd, buf.ptr, buf.len, flags, dest_addr, addrlen)) {
windows.ws2_32.SOCKET_ERROR => switch (windows.ws2_32.WSAGetLastError()) {
.WSAEACCES => return error.AccessDenied,
.WSAEADDRNOTAVAIL => return error.AddressNotAvailable,
.WSAECONNRESET => return error.ConnectionResetByPeer,
.WSAEMSGSIZE => return error.MessageTooBig,
.WSAENOBUFS => return error.SystemResources,
.WSAENOTSOCK => return error.FileDescriptorNotASocket,
.WSAEAFNOSUPPORT => return error.AddressFamilyNotSupported,
.WSAEDESTADDRREQ => unreachable,
.WSAEFAULT => unreachable,
.WSAEHOSTUNREACH => return error.NetworkUnreachable,
.WSAEINVAL => unreachable,
.WSAENETDOWN => return error.NetworkSubsystemFailed,
.WSAENETRESET => return error.ConnectionResetByPeer,
.WSAENETUNREACH => return error.NetworkUnreachable,
.WSAENOTCONN => return error.SocketNotConnected,
.WSAESHUTDOWN => unreachable,
.WSAEWOULDBLOCK => return error.WouldBlock,
.WSANOTINITIALISED => unreachable,
else => |err| return windows.unexpectedWSAError(err),
},
else => |rc| return @intCast(usize, rc),
}
}
while (true) {
const rc = system.sendto(sockfd, buf.ptr, buf.len, flags, dest_addr, addrlen);
switch (errno(rc)) {
.SUCCESS => return @intCast(usize, rc),
.ACCES => return error.AccessDenied,
.AGAIN => return error.WouldBlock,
.ALREADY => return error.FastOpenAlreadyInProgress,
.BADF => unreachable,
.CONNRESET => return error.ConnectionResetByPeer,
.DESTADDRREQ => unreachable,
.FAULT => unreachable,
.INTR => continue,
.INVAL => return error.UnreachableAddress,
.ISCONN => unreachable,
.MSGSIZE => return error.MessageTooBig,
.NOBUFS => return error.SystemResources,
.NOMEM => return error.SystemResources,
.NOTSOCK => unreachable,
.OPNOTSUPP => unreachable,
.PIPE => return error.BrokenPipe,
.AFNOSUPPORT => return error.AddressFamilyNotSupported,
.LOOP => return error.SymLinkLoop,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOTDIR => return error.NotDir,
.HOSTUNREACH => return error.NetworkUnreachable,
.NETUNREACH => return error.NetworkUnreachable,
.NOTCONN => return error.SocketNotConnected,
.NETDOWN => return error.NetworkSubsystemFailed,
else => |err| return unexpectedErrno(err),
}
}
}
pub fn send(
sockfd: socket_t,
buf: []const u8,
flags: u32,
) SendError!usize {
return sendto(sockfd, buf, flags, null, 0) catch |err| switch (err) {
error.AddressFamilyNotSupported => unreachable,
error.SymLinkLoop => unreachable,
error.NameTooLong => unreachable,
error.FileNotFound => unreachable,
error.NotDir => unreachable,
error.NetworkUnreachable => unreachable,
error.AddressNotAvailable => unreachable,
error.SocketNotConnected => unreachable,
error.UnreachableAddress => unreachable,
else => |e| return e,
};
}
pub const SendFileError = PReadError || WriteError || SendError;
fn count_iovec_bytes(iovs: []const iovec_const) usize {
var count: usize = 0;
for (iovs) |iov| {
count += iov.iov_len;
}
return count;
}
pub fn sendfile(
out_fd: fd_t,
in_fd: fd_t,
in_offset: u64,
in_len: u64,
headers: []const iovec_const,
trailers: []const iovec_const,
flags: u32,
) SendFileError!usize {
var header_done = false;
var total_written: usize = 0;
const size_t = std.meta.Int(.unsigned, @typeInfo(usize).Int.bits - 1);
const max_count = switch (builtin.os.tag) {
.linux => 0x7ffff000,
.macos, .ios, .watchos, .tvos => math.maxInt(i32),
else => math.maxInt(size_t),
};
switch (builtin.os.tag) {
.linux => sf: {
const call_sf = comptime if (builtin.link_libc)
std.c.versionCheck(.{ .major = 2, .minor = 1 }).ok
else
builtin.os.version_range.linux.range.max.order(.{ .major = 2, .minor = 2 }) != .lt;
if (!call_sf) break :sf;
if (headers.len != 0) {
const amt = try writev(out_fd, headers);
total_written += amt;
if (amt < count_iovec_bytes(headers)) return total_written;
header_done = true;
}
const adjusted_count_tmp = if (in_len == 0) max_count else @min(in_len, @as(size_t, max_count));
const adjusted_count = @intCast(usize, adjusted_count_tmp);
const sendfile_sym = if (builtin.link_libc)
system.sendfile64
else
system.sendfile;
while (true) {
var offset: off_t = @bitCast(off_t, in_offset);
const rc = sendfile_sym(out_fd, in_fd, &offset, adjusted_count);
switch (errno(rc)) {
.SUCCESS => {
const amt = @bitCast(usize, rc);
total_written += amt;
if (in_len == 0 and amt == 0) {
break;
} else if (amt < in_len) {
return total_written;
} else {
break;
}
},
.BADF => unreachable,
.FAULT => unreachable,
.OVERFLOW => unreachable,
.NOTCONN => return error.BrokenPipe,
.INVAL, .NOSYS => {
break :sf;
},
.AGAIN => if (std.event.Loop.instance) |loop| {
loop.waitUntilFdWritable(out_fd);
continue;
} else {
return error.WouldBlock;
},
.IO => return error.InputOutput,
.PIPE => return error.BrokenPipe,
.NOMEM => return error.SystemResources,
.NXIO => return error.Unseekable,
.SPIPE => return error.Unseekable,
else => |err| {
unexpectedErrno(err) catch {};
break :sf;
},
}
}
if (trailers.len != 0) {
total_written += try writev(out_fd, trailers);
}
return total_written;
},
.freebsd => sf: {
var hdtr_data: std.c.sf_hdtr = undefined;
var hdtr: ?*std.c.sf_hdtr = null;
if (headers.len != 0 or trailers.len != 0) {
const hdr_cnt = math.cast(u31, headers.len) orelse math.maxInt(u31);
if (headers.len > hdr_cnt) return writev(out_fd, headers);
const trl_cnt = math.cast(u31, trailers.len) orelse math.maxInt(u31);
hdtr_data = std.c.sf_hdtr{
.headers = headers.ptr,
.hdr_cnt = hdr_cnt,
.trailers = trailers.ptr,
.trl_cnt = trl_cnt,
};
hdtr = &hdtr_data;
}
const adjusted_count = @min(in_len, max_count);
while (true) {
var sbytes: off_t = undefined;
const offset = @bitCast(off_t, in_offset);
const err = errno(system.sendfile(in_fd, out_fd, offset, adjusted_count, hdtr, &sbytes, flags));
const amt = @bitCast(usize, sbytes);
switch (err) {
.SUCCESS => return amt,
.BADF => unreachable,
.FAULT => unreachable,
.NOTCONN => return error.BrokenPipe,
.INVAL, .OPNOTSUPP, .NOTSOCK, .NOSYS => {
break :sf;
},
.INTR => if (amt != 0) return amt else continue,
.AGAIN => if (amt != 0) {
return amt;
} else if (std.event.Loop.instance) |loop| {
loop.waitUntilFdWritable(out_fd);
continue;
} else {
return error.WouldBlock;
},
.BUSY => if (amt != 0) {
return amt;
} else if (std.event.Loop.instance) |loop| {
loop.waitUntilFdReadable(in_fd);
continue;
} else {
return error.WouldBlock;
},
.IO => return error.InputOutput,
.NOBUFS => return error.SystemResources,
.PIPE => return error.BrokenPipe,
else => {
unexpectedErrno(err) catch {};
if (amt != 0) {
return amt;
} else {
break :sf;
}
},
}
}
},
.macos, .ios, .tvos, .watchos => sf: {
var hdtr_data: std.c.sf_hdtr = undefined;
var hdtr: ?*std.c.sf_hdtr = null;
if (headers.len != 0 or trailers.len != 0) {
const hdr_cnt = math.cast(u31, headers.len) orelse math.maxInt(u31);
if (headers.len > hdr_cnt) return writev(out_fd, headers);
const trl_cnt = math.cast(u31, trailers.len) orelse math.maxInt(u31);
hdtr_data = std.c.sf_hdtr{
.headers = headers.ptr,
.hdr_cnt = hdr_cnt,
.trailers = trailers.ptr,
.trl_cnt = trl_cnt,
};
hdtr = &hdtr_data;
}
const adjusted_count_temporary = @min(in_len, @as(u63, max_count));
const adjusted_count = @intCast(u63, adjusted_count_temporary);
while (true) {
var sbytes: off_t = adjusted_count;
const signed_offset = @bitCast(i64, in_offset);
const err = errno(system.sendfile(in_fd, out_fd, signed_offset, &sbytes, hdtr, flags));
const amt = @bitCast(usize, sbytes);
switch (err) {
.SUCCESS => return amt,
.BADF => unreachable,
.FAULT => unreachable,
.INVAL => unreachable,
.NOTCONN => return error.BrokenPipe,
.OPNOTSUPP, .NOTSOCK, .NOSYS => break :sf,
.INTR => if (amt != 0) return amt else continue,
.AGAIN => if (amt != 0) {
return amt;
} else if (std.event.Loop.instance) |loop| {
loop.waitUntilFdWritable(out_fd);
continue;
} else {
return error.WouldBlock;
},
.IO => return error.InputOutput,
.PIPE => return error.BrokenPipe,
else => {
unexpectedErrno(err) catch {};
if (amt != 0) {
return amt;
} else {
break :sf;
}
},
}
}
},
else => {},
}
if (headers.len != 0 and !header_done) {
const amt = try writev(out_fd, headers);
total_written += amt;
if (amt < count_iovec_bytes(headers)) return total_written;
}
rw: {
var buf: [8 * 4096]u8 = undefined;
const adjusted_count_tmp = if (in_len == 0) buf.len else @min(buf.len, in_len);
const adjusted_count = @intCast(usize, adjusted_count_tmp);
const amt_read = try pread(in_fd, buf[0..adjusted_count], in_offset);
if (amt_read == 0) {
if (in_len == 0) {
break :rw;
} else {
return total_written;
}
}
const amt_written = try write(out_fd, buf[0..amt_read]);
total_written += amt_written;
if (amt_written < in_len or in_len == 0) return total_written;
}
if (trailers.len != 0) {
total_written += try writev(out_fd, trailers);
}
return total_written;
}
pub const CopyFileRangeError = error{
FileTooBig,
InputOutput,
FilesOpenedWithWrongFlags,
IsDir,
OutOfMemory,
NoSpaceLeft,
Unseekable,
PermissionDenied,
SwapFile,
CorruptedData,
} || PReadError || PWriteError || UnexpectedError;
var has_copy_file_range_syscall = std.atomic.Atomic(bool).init(true);
pub fn copy_file_range(fd_in: fd_t, off_in: u64, fd_out: fd_t, off_out: u64, len: usize, flags: u32) CopyFileRangeError!usize {
if ((comptime builtin.os.isAtLeast(.freebsd, .{ .major = 13, .minor = 0 }) orelse false) or
((comptime builtin.os.isAtLeast(.linux, .{ .major = 4, .minor = 5 }) orelse false and
std.c.versionCheck(.{ .major = 2, .minor = 27, .patch = 0 }).ok) and
has_copy_file_range_syscall.load(.Monotonic)))
{
var off_in_copy = @bitCast(i64, off_in);
var off_out_copy = @bitCast(i64, off_out);
while (true) {
const rc = system.copy_file_range(fd_in, &off_in_copy, fd_out, &off_out_copy, len, flags);
if (builtin.os.tag == .freebsd) {
switch (system.getErrno(rc)) {
.SUCCESS => return @intCast(usize, rc),
.BADF => return error.FilesOpenedWithWrongFlags,
.FBIG => return error.FileTooBig,
.IO => return error.InputOutput,
.ISDIR => return error.IsDir,
.NOSPC => return error.NoSpaceLeft,
.INVAL => break,
.INTEGRITY => return error.CorruptedData,
.INTR => continue,
else => |err| return unexpectedErrno(err),
}
} else {
switch (system.getErrno(rc)) {
.SUCCESS => return @intCast(usize, rc),
.BADF => return error.FilesOpenedWithWrongFlags,
.FBIG => return error.FileTooBig,
.IO => return error.InputOutput,
.ISDIR => return error.IsDir,
.NOSPC => return error.NoSpaceLeft,
.INVAL => break,
.NOMEM => return error.OutOfMemory,
.OVERFLOW => return error.Unseekable,
.PERM => return error.PermissionDenied,
.TXTBSY => return error.SwapFile,
.XDEV => break,
.NOSYS => {
has_copy_file_range_syscall.store(false, .Monotonic);
break;
},
else => |err| return unexpectedErrno(err),
}
}
}
}
var buf: [8 * 4096]u8 = undefined;
const adjusted_count = @min(buf.len, len);
const amt_read = try pread(fd_in, buf[0..adjusted_count], off_in);
if (amt_read == 0) return @as(usize, 0);
return pwrite(fd_out, buf[0..amt_read], off_out);
}
pub const PollError = error{
NetworkSubsystemFailed,
SystemResources,
} || UnexpectedError;
pub fn poll(fds: []pollfd, timeout: i32) PollError!usize {
while (true) {
const fds_count = math.cast(nfds_t, fds.len) orelse return error.SystemResources;
const rc = system.poll(fds.ptr, fds_count, timeout);
if (builtin.os.tag == .windows) {
if (rc == windows.ws2_32.SOCKET_ERROR) {
switch (windows.ws2_32.WSAGetLastError()) {
.WSANOTINITIALISED => unreachable,
.WSAENETDOWN => return error.NetworkSubsystemFailed,
.WSAENOBUFS => return error.SystemResources,
else => |err| return windows.unexpectedWSAError(err),
}
} else {
return @intCast(usize, rc);
}
} else {
switch (errno(rc)) {
.SUCCESS => return @intCast(usize, rc),
.FAULT => unreachable,
.INTR => continue,
.INVAL => unreachable,
.NOMEM => return error.SystemResources,
else => |err| return unexpectedErrno(err),
}
}
unreachable;
}
}
pub const PPollError = error{
SignalInterrupt,
SystemResources,
} || UnexpectedError;
pub fn ppoll(fds: []pollfd, timeout: ?*const timespec, mask: ?*const sigset_t) PPollError!usize {
var ts: timespec = undefined;
var ts_ptr: ?*timespec = null;
if (timeout) |timeout_ns| {
ts_ptr = &ts;
ts = timeout_ns.*;
}
const fds_count = math.cast(nfds_t, fds.len) orelse return error.SystemResources;
const rc = system.ppoll(fds.ptr, fds_count, ts_ptr, mask);
switch (errno(rc)) {
.SUCCESS => return @intCast(usize, rc),
.FAULT => unreachable,
.INTR => return error.SignalInterrupt,
.INVAL => unreachable,
.NOMEM => return error.SystemResources,
else => |err| return unexpectedErrno(err),
}
}
pub const RecvFromError = error{
WouldBlock,
ConnectionRefused,
SystemResources,
ConnectionResetByPeer,
SocketNotBound,
MessageTooBig,
NetworkSubsystemFailed,
SocketNotConnected,
} || UnexpectedError;
pub fn recv(sock: socket_t, buf: []u8, flags: u32) RecvFromError!usize {
return recvfrom(sock, buf, flags, null, null);
}
pub fn recvfrom(
sockfd: socket_t,
buf: []u8,
flags: u32,
src_addr: ?*sockaddr,
addrlen: ?*socklen_t,
) RecvFromError!usize {
while (true) {
const rc = system.recvfrom(sockfd, buf.ptr, buf.len, flags, src_addr, addrlen);
if (builtin.os.tag == .windows) {
if (rc == windows.ws2_32.SOCKET_ERROR) {
switch (windows.ws2_32.WSAGetLastError()) {
.WSANOTINITIALISED => unreachable,
.WSAECONNRESET => return error.ConnectionResetByPeer,
.WSAEINVAL => return error.SocketNotBound,
.WSAEMSGSIZE => return error.MessageTooBig,
.WSAENETDOWN => return error.NetworkSubsystemFailed,
.WSAENOTCONN => return error.SocketNotConnected,
.WSAEWOULDBLOCK => return error.WouldBlock,
else => |err| return windows.unexpectedWSAError(err),
}
} else {
return @intCast(usize, rc);
}
} else {
switch (errno(rc)) {
.SUCCESS => return @intCast(usize, rc),
.BADF => unreachable,
.FAULT => unreachable,
.INVAL => unreachable,
.NOTCONN => return error.SocketNotConnected,
.NOTSOCK => unreachable,
.INTR => continue,
.AGAIN => return error.WouldBlock,
.NOMEM => return error.SystemResources,
.CONNREFUSED => return error.ConnectionRefused,
.CONNRESET => return error.ConnectionResetByPeer,
else => |err| return unexpectedErrno(err),
}
}
}
}
pub const DnExpandError = error{InvalidDnsPacket};
pub fn dn_expand(
msg: []const u8,
comp_dn: []const u8,
exp_dn: []u8,
) DnExpandError!usize {
var p = comp_dn.ptr;
var len: usize = std.math.maxInt(usize);
const end = msg.ptr + msg.len;
if (p == end or exp_dn.len == 0) return error.InvalidDnsPacket;
var dest = exp_dn.ptr;
const dend = dest + @min(exp_dn.len, 254);
var i: usize = 0;
while (i < msg.len) : (i += 2) {
if ((p[0] & 0xc0) != 0) {
if (p + 1 == end) return error.InvalidDnsPacket;
var j = ((p[0] & @as(usize, 0x3f)) << 8) | p[1];
if (len == std.math.maxInt(usize)) len = @ptrToInt(p) + 2 - @ptrToInt(comp_dn.ptr);
if (j >= msg.len) return error.InvalidDnsPacket;
p = msg.ptr + j;
} else if (p[0] != 0) {
if (dest != exp_dn.ptr) {
dest[0] = '.';
dest += 1;
}
var j = p[0];
p += 1;
if (j >= @ptrToInt(end) - @ptrToInt(p) or j >= @ptrToInt(dend) - @ptrToInt(dest)) {
return error.InvalidDnsPacket;
}
while (j != 0) {
j -= 1;
dest[0] = p[0];
dest += 1;
p += 1;
}
} else {
dest[0] = 0;
if (len == std.math.maxInt(usize)) len = @ptrToInt(p) + 1 - @ptrToInt(comp_dn.ptr);
return len;
}
}
return error.InvalidDnsPacket;
}
pub const SetSockOptError = error{
AlreadyConnected,
InvalidProtocolOption,
TimeoutTooBig,
SystemResources,
PermissionDenied,
NetworkSubsystemFailed,
FileDescriptorNotASocket,
SocketNotBound,
NoDevice,
} || UnexpectedError;
pub fn setsockopt(fd: socket_t, level: u32, optname: u32, opt: []const u8) SetSockOptError!void {
if (builtin.os.tag == .windows) {
const rc = windows.ws2_32.setsockopt(fd, @intCast(i32, level), @intCast(i32, optname), opt.ptr, @intCast(i32, opt.len));
if (rc == windows.ws2_32.SOCKET_ERROR) {
switch (windows.ws2_32.WSAGetLastError()) {
.WSANOTINITIALISED => unreachable,
.WSAENETDOWN => return error.NetworkSubsystemFailed,
.WSAEFAULT => unreachable,
.WSAENOTSOCK => return error.FileDescriptorNotASocket,
.WSAEINVAL => return error.SocketNotBound,
else => |err| return windows.unexpectedWSAError(err),
}
}
return;
} else {
switch (errno(system.setsockopt(fd, level, optname, opt.ptr, @intCast(socklen_t, opt.len)))) {
.SUCCESS => {},
.BADF => unreachable,
.NOTSOCK => unreachable,
.INVAL => unreachable,
.FAULT => unreachable,
.DOM => return error.TimeoutTooBig,
.ISCONN => return error.AlreadyConnected,
.NOPROTOOPT => return error.InvalidProtocolOption,
.NOMEM => return error.SystemResources,
.NOBUFS => return error.SystemResources,
.PERM => return error.PermissionDenied,
.NODEV => return error.NoDevice,
else => |err| return unexpectedErrno(err),
}
}
}
pub const MemFdCreateError = error{
SystemFdQuotaExceeded,
ProcessFdQuotaExceeded,
OutOfMemory,
SystemOutdated,
} || UnexpectedError;
pub fn memfd_createZ(name: [*:0]const u8, flags: u32) MemFdCreateError!fd_t {
switch (builtin.os.tag) {
.linux => {
const use_c = std.c.versionCheck(.{ .major = 2, .minor = 27, .patch = 0 }).ok;
const sys = if (use_c) std.c else linux;
const getErrno = if (use_c) std.c.getErrno else linux.getErrno;
const rc = sys.memfd_create(name, flags);
switch (getErrno(rc)) {
.SUCCESS => return @intCast(fd_t, rc),
.FAULT => unreachable,
.INVAL => unreachable,
.NFILE => return error.SystemFdQuotaExceeded,
.MFILE => return error.ProcessFdQuotaExceeded,
.NOMEM => return error.OutOfMemory,
.NOSYS => return error.SystemOutdated,
else => |err| return unexpectedErrno(err),
}
},
.freebsd => {
if (comptime builtin.os.version_range.semver.max.order(.{ .major = 13, .minor = 0 }) == .lt)
@compileError("memfd_create is unavailable on FreeBSD < 13.0");
const rc = system.memfd_create(name, flags);
switch (errno(rc)) {
.SUCCESS => return rc,
.BADF => unreachable,
.INVAL => unreachable,
.MFILE => return error.ProcessFdQuotaExceeded,
.NFILE => return error.SystemFdQuotaExceeded,
.NOSYS => return error.SystemOutdated,
else => |err| return unexpectedErrno(err),
}
},
else => @compileError("target OS does not support memfd_create()"),
}
}
pub const MFD_NAME_PREFIX = "memfd:";
pub const MFD_MAX_NAME_LEN = NAME_MAX - MFD_NAME_PREFIX.len;
fn toMemFdPath(name: []const u8) ![MFD_MAX_NAME_LEN:0]u8 {
var path_with_null: [MFD_MAX_NAME_LEN:0]u8 = undefined;
if (name.len >= MFD_MAX_NAME_LEN) return error.NameTooLong;
mem.copy(u8, &path_with_null, name);
path_with_null[name.len] = 0;
return path_with_null;
}
pub fn memfd_create(name: []const u8, flags: u32) !fd_t {
const name_t = try toMemFdPath(name);
return memfd_createZ(&name_t, flags);
}
pub fn getrusage(who: i32) rusage {
var result: rusage = undefined;
const rc = system.getrusage(who, &result);
switch (errno(rc)) {
.SUCCESS => return result,
.INVAL => unreachable,
.FAULT => unreachable,
else => unreachable,
}
}
pub const TermiosGetError = error{NotATerminal} || UnexpectedError;
pub fn tcgetattr(handle: fd_t) TermiosGetError!termios {
while (true) {
var term: termios = undefined;
switch (errno(system.tcgetattr(handle, &term))) {
.SUCCESS => return term,
.INTR => continue,
.BADF => unreachable,
.NOTTY => return error.NotATerminal,
else => |err| return unexpectedErrno(err),
}
}
}
pub const TermiosSetError = TermiosGetError || error{ProcessOrphaned};
pub fn tcsetattr(handle: fd_t, optional_action: TCSA, termios_p: termios) TermiosSetError!void {
while (true) {
switch (errno(system.tcsetattr(handle, optional_action, &termios_p))) {
.SUCCESS => return,
.BADF => unreachable,
.INTR => continue,
.INVAL => unreachable,
.NOTTY => return error.NotATerminal,
.IO => return error.ProcessOrphaned,
else => |err| return unexpectedErrno(err),
}
}
}
pub const IoCtl_SIOCGIFINDEX_Error = error{
FileSystem,
InterfaceNotFound,
} || UnexpectedError;
pub fn ioctl_SIOCGIFINDEX(fd: fd_t, ifr: *ifreq) IoCtl_SIOCGIFINDEX_Error!void {
while (true) {
switch (errno(system.ioctl(fd, SIOCGIFINDEX, @ptrToInt(ifr)))) {
.SUCCESS => return,
.INVAL => unreachable,
.NOTTY => unreachable,
.NXIO => unreachable,
.BADF => unreachable,
.FAULT => unreachable,
.INTR => continue,
.IO => return error.FileSystem,
.NODEV => return error.InterfaceNotFound,
else => |err| return unexpectedErrno(err),
}
}
}
pub fn signalfd(fd: fd_t, mask: *const sigset_t, flags: u32) !fd_t {
const rc = system.signalfd(fd, mask, flags);
switch (errno(rc)) {
.SUCCESS => return @intCast(fd_t, rc),
.BADF, .INVAL => unreachable,
.NFILE => return error.SystemFdQuotaExceeded,
.NOMEM => return error.SystemResources,
.MFILE => return error.ProcessResources,
.NODEV => return error.InodeMountFail,
.NOSYS => return error.SystemOutdated,
else => |err| return unexpectedErrno(err),
}
}
pub const SyncError = error{
InputOutput,
NoSpaceLeft,
DiskQuota,
AccessDenied,
} || UnexpectedError;
pub fn sync() void {
system.sync();
}
pub fn syncfs(fd: fd_t) SyncError!void {
const rc = system.syncfs(fd);
switch (errno(rc)) {
.SUCCESS => return,
.BADF, .INVAL, .ROFS => unreachable,
.IO => return error.InputOutput,
.NOSPC => return error.NoSpaceLeft,
.DQUOT => return error.DiskQuota,
else => |err| return unexpectedErrno(err),
}
}
pub fn fsync(fd: fd_t) SyncError!void {
if (builtin.os.tag == .windows) {
if (windows.kernel32.FlushFileBuffers(fd) != 0)
return;
switch (windows.kernel32.GetLastError()) {
.SUCCESS => return,
.INVALID_HANDLE => unreachable,
.ACCESS_DENIED => return error.AccessDenied,
.UNEXP_NET_ERR => return error.InputOutput,
else => return error.InputOutput,
}
}
const rc = system.fsync(fd);
switch (errno(rc)) {
.SUCCESS => return,
.BADF, .INVAL, .ROFS => unreachable,
.IO => return error.InputOutput,
.NOSPC => return error.NoSpaceLeft,
.DQUOT => return error.DiskQuota,
else => |err| return unexpectedErrno(err),
}
}
pub fn fdatasync(fd: fd_t) SyncError!void {
if (builtin.os.tag == .windows) {
return fsync(fd) catch |err| switch (err) {
SyncError.AccessDenied => return,
else => return err,
};
}
const rc = system.fdatasync(fd);
switch (errno(rc)) {
.SUCCESS => return,
.BADF, .INVAL, .ROFS => unreachable,
.IO => return error.InputOutput,
.NOSPC => return error.NoSpaceLeft,
.DQUOT => return error.DiskQuota,
else => |err| return unexpectedErrno(err),
}
}
pub const PrctlError = error{
AccessDenied,
InvalidFileDescriptor,
InvalidAddress,
UnsupportedFeature,
OperationNotSupported,
PermissionDenied,
} || UnexpectedError;
pub fn prctl(option: PR, args: anytype) PrctlError!u31 {
if (@typeInfo(@TypeOf(args)) != .Struct)
@compileError("Expected tuple or struct argument, found " ++ @typeName(@TypeOf(args)));
if (args.len > 4)
@compileError("prctl takes a maximum of 4 optional arguments");
var buf: [4]usize = undefined;
{
comptime var i = 0;
inline while (i < args.len) : (i += 1) buf[i] = args[i];
}
const rc = system.prctl(@enumToInt(option), buf[0], buf[1], buf[2], buf[3]);
switch (errno(rc)) {
.SUCCESS => return @intCast(u31, rc),
.ACCES => return error.AccessDenied,
.BADF => return error.InvalidFileDescriptor,
.FAULT => return error.InvalidAddress,
.INVAL => unreachable,
.NODEV, .NXIO => return error.UnsupportedFeature,
.OPNOTSUPP => return error.OperationNotSupported,
.PERM, .BUSY => return error.PermissionDenied,
.RANGE => unreachable,
else => |err| return unexpectedErrno(err),
}
}
pub const GetrlimitError = UnexpectedError;
pub fn getrlimit(resource: rlimit_resource) GetrlimitError!rlimit {
const getrlimit_sym = if (builtin.os.tag == .linux and builtin.link_libc)
system.getrlimit64
else
system.getrlimit;
var limits: rlimit = undefined;
switch (errno(getrlimit_sym(resource, &limits))) {
.SUCCESS => return limits,
.FAULT => unreachable,
.INVAL => unreachable,
else => |err| return unexpectedErrno(err),
}
}
pub const SetrlimitError = error{ PermissionDenied, LimitTooBig } || UnexpectedError;
pub fn setrlimit(resource: rlimit_resource, limits: rlimit) SetrlimitError!void {
const setrlimit_sym = if (builtin.os.tag == .linux and builtin.link_libc)
system.setrlimit64
else
system.setrlimit;
switch (errno(setrlimit_sym(resource, &limits))) {
.SUCCESS => return,
.FAULT => unreachable,
.INVAL => return error.LimitTooBig,
.PERM => return error.PermissionDenied,
else => |err| return unexpectedErrno(err),
}
}
pub const MincoreError = error{
SystemResources,
InvalidAddress,
InvalidSyscall,
OutOfMemory,
MincoreUnavailable,
} || UnexpectedError;
pub fn mincore(ptr: [*]align(mem.page_size) u8, length: usize, vec: [*]u8) MincoreError!void {
return switch (errno(system.mincore(ptr, length, vec))) {
.SUCCESS => {},
.AGAIN => error.SystemResources,
.FAULT => error.InvalidAddress,
.INVAL => error.InvalidSyscall,
.NOMEM => error.OutOfMemory,
.NOSYS => error.MincoreUnavailable,
else => |err| unexpectedErrno(err),
};
}
pub const MadviseError = error{
AccessDenied,
PermissionDenied,
SystemResources,
InvalidSyscall,
WouldExceedMaximumResidentSetSize,
OutOfMemory,
MadviseUnavailable,
Unexpected,
};
pub fn madvise(ptr: [*]align(mem.page_size) u8, length: usize, advice: u32) MadviseError!void {
switch (errno(system.madvise(ptr, length, advice))) {
.SUCCESS => return,
.ACCES => return error.AccessDenied,
.AGAIN => return error.SystemResources,
.BADF => unreachable,
.INVAL => return error.InvalidSyscall,
.IO => return error.WouldExceedMaximumResidentSetSize,
.NOMEM => return error.OutOfMemory,
.NOSYS => return error.MadviseUnavailable,
else => |err| return unexpectedErrno(err),
}
}
pub const PerfEventOpenError = error{
TooBig,
PermissionDenied,
DeviceBusy,
ProcessResources,
EventRequiresUnsupportedCpuFeature,
TooManyBreakpoints,
SampleStackNotSupported,
EventNotSupported,
SampleMaxStackOverflow,
ProcessNotFound,
} || UnexpectedError;
pub fn perf_event_open(
attr: *linux.perf_event_attr,
pid: pid_t,
cpu: i32,
group_fd: fd_t,
flags: usize,
) PerfEventOpenError!fd_t {
const rc = system.perf_event_open(attr, pid, cpu, group_fd, flags);
switch (errno(rc)) {
.SUCCESS => return @intCast(fd_t, rc),
.@"2BIG" => return error.TooBig,
.ACCES => return error.PermissionDenied,
.BADF => unreachable,
.BUSY => return error.DeviceBusy,
.FAULT => unreachable,
.INVAL => unreachable,
.INTR => unreachable,
.MFILE => return error.ProcessResources,
.NODEV => return error.EventRequiresUnsupportedCpuFeature,
.NOENT => unreachable,
.NOSPC => return error.TooManyBreakpoints,
.NOSYS => return error.SampleStackNotSupported,
.OPNOTSUPP => return error.EventNotSupported,
.OVERFLOW => return error.SampleMaxStackOverflow,
.PERM => return error.PermissionDenied,
.SRCH => return error.ProcessNotFound,
else => |err| return unexpectedErrno(err),
}
}
pub const TimerFdCreateError = error{
AccessDenied,
ProcessFdQuotaExceeded,
SystemFdQuotaExceeded,
NoDevice,
SystemResources,
} || UnexpectedError;
pub const TimerFdGetError = error{InvalidHandle} || UnexpectedError;
pub const TimerFdSetError = TimerFdGetError || error{Canceled};
pub fn timerfd_create(clokid: i32, flags: u32) TimerFdCreateError!fd_t {
var rc = linux.timerfd_create(clokid, flags);
return switch (errno(rc)) {
.SUCCESS => @intCast(fd_t, rc),
.INVAL => unreachable,
.MFILE => return error.ProcessFdQuotaExceeded,
.NFILE => return error.SystemFdQuotaExceeded,
.NODEV => return error.NoDevice,
.NOMEM => return error.SystemResources,
.PERM => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
};
}
pub fn timerfd_settime(fd: i32, flags: u32, new_value: *const linux.itimerspec, old_value: ?*linux.itimerspec) TimerFdSetError!void {
var rc = linux.timerfd_settime(fd, flags, new_value, old_value);
return switch (errno(rc)) {
.SUCCESS => {},
.BADF => error.InvalidHandle,
.FAULT => unreachable,
.INVAL => unreachable,
.CANCELED => error.Canceled,
else => |err| return unexpectedErrno(err),
};
}
pub fn timerfd_gettime(fd: i32) TimerFdGetError!linux.itimerspec {
var curr_value: linux.itimerspec = undefined;
var rc = linux.timerfd_gettime(fd, &curr_value);
return switch (errno(rc)) {
.SUCCESS => return curr_value,
.BADF => error.InvalidHandle,
.FAULT => unreachable,
.INVAL => unreachable,
else => |err| return unexpectedErrno(err),
};
}
pub const PtraceError = error{
DeviceBusy,
InputOutput,
Overflow,
ProcessNotFound,
PermissionDenied,
} || UnexpectedError;
pub fn ptrace(request: u32, pid: pid_t, addr: usize, signal: usize) PtraceError!void {
if (builtin.os.tag == .windows or builtin.os.tag == .wasi)
@compileError("Unsupported OS");
return switch (builtin.os.tag) {
.linux => switch (errno(linux.ptrace(request, pid, addr, signal, 0))) {
.SUCCESS => {},
.SRCH => error.ProcessNotFound,
.FAULT => unreachable,
.INVAL => unreachable,
.IO => return error.InputOutput,
.PERM => error.PermissionDenied,
.BUSY => error.DeviceBusy,
else => |err| return unexpectedErrno(err),
},
.macos, .ios, .tvos, .watchos => switch (errno(darwin.ptrace(
math.cast(i32, request) orelse return error.Overflow,
pid,
@intToPtr(?[*]u8, addr),
math.cast(i32, signal) orelse return error.Overflow,
))) {
.SUCCESS => {},
.SRCH => error.ProcessNotFound,
.INVAL => unreachable,
.PERM => error.PermissionDenied,
.BUSY => error.DeviceBusy,
else => |err| return unexpectedErrno(err),
},
else => switch (errno(system.ptrace(request, pid, addr, signal))) {
.SUCCESS => {},
.SRCH => error.ProcessNotFound,
.INVAL => unreachable,
.PERM => error.PermissionDenied,
.BUSY => error.DeviceBusy,
else => |err| return unexpectedErrno(err),
},
};
}