(* System calls on Linux for x86-64. Other targets supply their own Sys, with the same exports. *) module Sys; import SYSTEM; const stdin* = 0; (* standard input's file descriptor *) stdout* = 1; (* standard output's *) stderr* = 2; (* standard error's *) (* the bytes Out keeps before it writes them; a target with little memory keeps fewer *) outSize* = 4096; (* signals, by their numbers on Linux *) sigHup* = 1; sigInt* = 2; sigQuit* = 3; sigKill* = 9; sigPipe* = 13; sigTerm* = 15; sigChld* = 17; sigCont* = 18; sigStop* = 19; sigTstp* = 20; sigTtin* = 21; sigTtou* = 22; sigWinch* = 28; sigUsr1* = 10; sigUsr2* = 12; sigAlrm* = 14; (* the limits limit and setLimit take, by their numbers on Linux *) limitCpu* = 0; (* seconds of the processor *) limitFileSize* = 1; (* bytes in a file it writes *) limitData* = 2; (* bytes of its data *) limitStack* = 3; (* bytes of its stack *) limitCore* = 4; (* bytes of a core dump *) limitProcs* = 6; (* processes of its user *) limitFiles* = 7; (* one more than its highest fd *) limitMemory* = 9; (* bytes of its address space *) (* errors, minus Linux's errnos, as on every target *) errPerm* = -1; errNoEntry* = -2; errNoProcess* = -3; errIntr* = -4; errIo* = -5; errBadFd* = -9; errChild* = -10; errAgain* = -11; errNoMemory* = -12; errDenied* = -13; errExists* = -17; errNotDir* = -20; errIsDir* = -21; errInvalid* = -22; errNotTerminal* = -25; errNoSpace* = -28; errReadOnly* = -30; errPipe* = -32; errNameTooLong* = -36; errNotEmpty* = -39; errLoop* = -40; errAddrInUse* = -98; errNetUnreach* = -101; errConnAborted* = -103; errConnReset* = -104; errTimedOut* = -110; errRefused* = -111; errHostUnreach* = -113; errInProgress* = -115; type (* One descriptor poll waits on: whether to wait to read from it, to write to it, or both, and, when poll returns, whether it may be. One that has reached its end, has failed or isn't open is ready too, so that a read or a write finds out. *) Poll* = record fd*: INT; (* the file descriptor; a negative one is never ready *) read*: BOOL; (* wait until it has something to read *) write*: BOOL; (* wait until it has room to write *) ready*: BOOL; (* set by poll: a read or a write on it won't wait *) end; (* What open is asked for: reading, writing or both, and what else it does to the file; nonblocking, that open doesn't wait (for a fifo's other end) and reads and writes on the file don't either. *) Access* = (reading, writing, creating, exclusive, truncating, appending, executing, nonblocking); Accesses* = set of Access; (* what open is given *) (* What info says of a file. *) Info* = record size*: I64; (* in bytes *) mtime*: I64; (* its contents' last change, in ns since 1970 *) seconds*: I64; (* mtime in whole seconds, rounded down: exact past 2262 and before 1677, where mtime wraps *) mode*: INT; (* its permission bits, rwxrwxrwx *) dir*: BOOL; (* a directory *) file*: BOOL; (* not a directory, device, pipe or socket *) symlink*: BOOL; (* the path itself is a symbolic link *) ino*: U64; (* its inode, which a rename keeps and a new file doesn't *) dev*: U64; (* the file system it is on; with ino, it names the file *) links*: U64; (* how many names it has: 1 for a file no hard link shares *) special*: INT; (* its set-user-id, set-group-id and sticky bits, as chmod takes them: 800H, 400H, 200H *) uid*: INT; (* its owner's user number *) gid*: INT; (* its group's number *) end; (* What a directory says a name in it is, without asking the file: a regular file, a directory, a symbolic link, or something else (a device, pipe or socket); unknown where the file system doesn't say, and linkInfo must be asked. *) Kind* = (unknown, isFile, isDir, isLink, isOther); (* An open directory: getdents64's records, read a block at a time. *) Dir* = record fd, pos, len: INT; kind: Kind; (* of the name nextEntry gave last *) buf: [8192]U8; end; (* A program for spawn to start. *) Program* = record path*: []const U8; args*: [][]const U8; (* the first is its name *) env*: [][]const U8; (* NAME=value, each added to this environment *) onlyEnv*: BOOL; (* env is its whole environment *) dir*: []const U8; (* its working directory; "" for this program's *) fds*: [3]INT; (* stdin, stdout, stderr; 0 for this program's *) group*: INT; (* its group: 0 for this program's, -1 a new one *) foreground*: BOOL; (* its group gets the terminal on standard input *) tty*: INT; (* a pseudo-terminal to start a session on, or 0 *) more*: []INT; (* fds above 2 passed on to it at the same numbers *) keepIgnored*: BOOL; (* signals this program ignores stay ignored in it *) end; (* How a program that wait waited for changed. *) Status* = (running, exited, killed, stopped); (* struct termios as the kernel's TCGETS fills it: 36 bytes *) Termios = record iflag, oflag, cflag, lflag: U32; line: U8; cc: [19]U8; end; (* A terminal's modes, as getMode reads them and setMode sets them. *) Mode* = record t: Termios; end; Winsize = record rows, cols, xpixel, ypixel: U16; end; Pollfd = record fd: I32; events, revents: I16; end; (* struct sockaddr_un: AF_UNIX, then the path and its zero *) SockaddrUn = record family: U16; path: [108]U8; end; (* struct sockaddr_in or sockaddr_in6: AF_INET and the IPv4 address in data[0..4], or AF_INET6 and the IPv6 one in data[4..20] *) Sockaddr = record family: U16; port: [2]U8; data: [24]U8; end; (* Whom a datagram came from, as receive says and reply takes: the address recvfrom fills in, and its size. *) Peer* = record a: Sockaddr; size: INT; end; (* Who is at the other end of a connected socket, as peer says. *) Remote* = record unix*: BOOL; (* a Unix socket: uid and pid say who; no addr or port *) ipv6*: BOOL; (* addr is an IPv6 address, 16 bytes; else an IPv4 one, 4 bytes then zeros *) addr*: [16]U8; (* an IP peer's address *) port*: INT; (* an IP peer's port *) uid*, pid*: INT; (* a Unix peer's user and process, as the system recorded them when it connected *) end; (* struct msghdr, what sendmsg and recvmsg take: no address, one buffer, and a control message; the sizes and flags are ints with room after them, kept zero *) Msghdr = record name: ^U8; nameSize: INT; iov: ^Iovec; iovLen: INT; control: ^U8; controlSize: INT; flags: INT; end; Iovec = record base: ^U8; size: INT; end; (* struct cmsghdr, SCM_RIGHTS's: its size, counted to the last fd, then the fds, as many as sendFds sends *) Rights = record size: INT; level, kind: I32; fds: [16]I32; end; Timespec = record sec, nsec: I64; end; (* struct sigaction, as rt_sigaction takes it *) Action = record handler: proc(sig: INT); flags: U64; restorer: proc; mask: U64; end; var cwd: [4096]U8; (* what workDir gives *) linked: [4096]U8; (* what readLink gives *) saved: Termios; (* the terminal as rawMode found it *) caughtSigs: U64; (* the signals catch has blocked, bit n - 1 for signal n *) sigFd: INT; (* the signalfd that gives them, once caughtSigs isn't empty *) noted: [65]INT; (* 1 at sig when a signal handle took has come, until came asks *) uts: [390]U8; (* struct utsname, which hostName gives the nodename of *) (* the environment setEnv made, nil while it is the one the program started with; its variables, and the pointers it has room for *) envp: ^^U8; envLen, envCap: INT; envText: ^U8; (* where setEnv puts its next NAME=value *) envLeft: INT; (* and the bytes left there *) (* Writes s to the file descriptor fd; the number of bytes written, or minus an errno. *) proc write*(fd: INT; s: []const U8): INT; begin if LEN(s) = 0 then return 0; end; return SYSTEM.SYSCALL(1, fd, SYSTEM.PTR(s), LEN(s)); end; (* Reads into buf from fd; the number of bytes read, 0 at the end, or minus an errno. *) proc read*(fd: INT; buf: []U8): INT; begin if LEN(buf) = 0 then return 0; end; return SYSTEM.SYSCALL(0, fd, SYSTEM.ADR(buf[0]), LEN(buf)); end; (* path, a C string in buf, or false if it doesn't fit. *) proc cstr(path: []const U8; buf: []U8): BOOL; begin if LEN(path) >= LEN(buf) then return false; end; COPY(buf, path); buf[LEN(path)] := 0; return true; end; (* open's flags for how, with O_CLOEXEC; Linux's numbers *) proc flags(how: Accesses): I32; var f: I32; begin f := 80000H; (* O_CLOEXEC, with O_RDONLY *) if writing in how then f := 1; (* O_WRONLY *) if reading in how then f := 2; end; (* O_RDWR *) end; if creating in how then f := f | 40H; end; if exclusive in how then f := f | 80H; end; if truncating in how then f := f | 200H; end; if appending in how then f := f | 400H; end; if nonblocking in how then f := f | 800H; end; (* O_NONBLOCK *) return f; end; (* The file at path, opened as how asks: its file descriptor, closed in a program exec starts, or minus an errno. A file it creates has the permission bits mode, less those the umask takes away. *) proc openMode*(path: []const U8; how: Accesses; mode: INT): INT; var buf: [4096]U8; begin if executing in how then return -22; end; (* EINVAL: access asks it, open can't *) if not cstr(path, buf) then return -36; end; (* ENAMETOOLONG *) return SYSTEM.SYSCALL(2, SYSTEM.ADR(buf), flags(how), mode); end; (* openMode with 644: a file it creates is readable by all, writable by its owner. *) proc open*(path: []const U8; how: Accesses): INT; begin return openMode(path, how, 1A4H); (* 644 *) end; (* The file at path, opened for reading, closed in a program exec starts. *) proc openRead*(path: []const U8): INT; begin return open(path, {reading}); end; (* The file at path, made empty or new, opened for writing, closed in a program exec starts. *) proc create*(path: []const U8): INT; begin return open(path, {writing, creating, truncating}); end; (* Moves fd to pos from the start of its file, or from the end if fromEnd: the new position, or minus an errno. *) proc seek*(fd: INT; pos: I64; fromEnd: BOOL): I64; begin if fromEnd then return SYSTEM.SYSCALL(8, fd, pos, 2); end; (* lseek, SEEK_END *) return SYSTEM.SYSCALL(8, fd, pos, 0); (* SEEK_SET *) end; (* Where in its file fd is, without moving: the next read or write's position, or minus an errno. *) proc position*(fd: INT): I64; begin return SYSTEM.SYSCALL(8, fd, 0, 1); (* lseek, SEEK_CUR *) end; (* The file fd makes size bytes long, cut or filled with zeros; its position stays. 0, or minus an errno. *) proc truncate*(fd: INT; size: I64): INT; begin return SYSTEM.SYSCALL(77, fd, size); (* ftruncate *) end; (* Returns once what was written to fd is on the disk: 0, or minus an errno. *) proc sync*(fd: INT): INT; begin return SYSTEM.SYSCALL(74, fd); (* fsync *) end; (* Returns once everything written to the file system that holds fd is on the disk, as a sync of each file would, but at once: 0, or minus an errno. *) proc syncAll*(fd: INT): INT; begin return SYSTEM.SYSCALL(306, fd); (* syncfs *) end; (* Takes the lock on the open file fd, which only one program holds at a time, and which goes when fd is closed or the program ends, however it ends. If another program holds it, waits for it if wait, and otherwise returns -11 (EAGAIN). 0, or minus an errno. *) proc lock*(fd: INT; wait: BOOL): INT; begin if wait then return SYSTEM.SYSCALL(73, fd, 2); end; (* flock, LOCK_EX *) return SYSTEM.SYSCALL(73, fd, 2 | 4); (* LOCK_EX | LOCK_NB *) end; (* Takes the lock on the open file fd as lock does, but shared: any number of programs may hold it so at once, as readers do, while none holds it as lock takes it. 0, or minus an errno. *) proc lockShared*(fd: INT; wait: BOOL): INT; begin if wait then return SYSTEM.SYSCALL(73, fd, 1); end; (* flock, LOCK_SH *) return SYSTEM.SYSCALL(73, fd, 1 | 4); (* LOCK_SH | LOCK_NB *) end; (* Closes the file descriptor fd. *) proc close*(fd: INT); begin _ := SYSTEM.SYSCALL(3, fd); end; (* Closes the file descriptor fd, as close does, and says whether that failed: 0, or minus an errno. A file system may report only at the close that what was written to the file never reached it, -28 (ENOSPC) or -122 (EDQUOT) say, as NFS does; a program that must know its writes landed asks so. The fd is closed either way, so it is never closed again, after -4 (EINTR) too. *) proc closeChecked*(fd: INT): INT; begin return SYSTEM.SYSCALL(3, fd); end; (* A new file descriptor for the file fd is open on, the lowest free: it, or minus an errno. *) proc dup*(fd: INT): INT; begin return SYSTEM.SYSCALL(32, fd); (* dup *) end; (* Makes the file descriptor into stand for the file fd is open on, closing what into was first: into, or minus an errno. *) proc dupTo*(fd, into: INT): INT; begin return SYSTEM.SYSCALL(33, fd, into); (* dup2 *) end; (* A new file descriptor for the file fd is open on, the lowest free from least on, and closed on exec: it, or minus an errno. A shell keeps its own at 10 and above, out of the way of those a script names. *) proc dupAbove*(fd, least: INT): INT; begin return SYSTEM.SYSCALL(72, fd, 1030, least); (* fcntl: F_DUPFD_CLOEXEC *) end; (* Whether fd stays open in the program exec runs in this one's place: yes, or no, closed then, as the fds open, pipe and socket give are at first. 0, or minus an errno. *) proc keepOnExec*(fd: INT; yes: BOOL): INT; var f: INT; begin f := SYSTEM.SYSCALL(72, fd, 1); (* fcntl: F_GETFD *) if f < 0 then return f; end; if yes then f := f & ~1; else f := f | 1; end; (* FD_CLOEXEC *) return SYSTEM.SYSCALL(72, fd, 2, f); (* F_SETFD *) end; (* size bytes of fresh, zeroed memory from the system, a multiple of pages, or nil. *) proc mmap*(size: INT): ^U8; var p: INT; begin p := SYSTEM.SYSCALL(9, 0, size, 3, 22H, -1, 0); (* read, write; private, anonymous *) if p < 0 then return nil; end; return ^U8(p); end; (* Gives back to the system the size bytes at p that mmap gave. *) proc munmap*(p: ^U8; size: INT); begin _ := SYSTEM.SYSCALL(11, p, size); end; (* A file in memory, with no name, of size zeroed bytes: its fd, or minus an errno. It is closed in a program exec starts. *) proc memFile*(size: INT): INT; var name: [4]U8; fd, r: INT; begin _ := cstr("raz", name); (* the name /proc shows *) fd := SYSTEM.SYSCALL(319, SYSTEM.ADR(name[0]), 1); (* memfd_create, MFD_CLOEXEC *) if fd < 0 then return fd; end; r := SYSTEM.SYSCALL(77, fd, size); (* ftruncate *) if r < 0 then close(fd); return r; end; return fd; end; (* The first size bytes of the file fd, mapped to be read and written, and shared: what this program writes there, every program that maps the file sees. nil if it can't be; munmap gives them back. *) proc mapFile*(fd, size: INT): ^U8; var p: INT; begin p := SYSTEM.SYSCALL(9, 0, size, 3, 1, fd, 0); (* mmap: read, write; MAP_SHARED *) if p < 0 then return nil; end; return ^U8(p); end; (* The first size bytes of the file fd, which may be open only to read, mapped to be read only: writing there stops the program. nil if it can't be; munmap gives them back. *) proc mapRead*(fd, size: INT): ^U8; var p: INT; begin p := SYSTEM.SYSCALL(9, 0, size, 1, 2, fd, 0); (* mmap: read; MAP_PRIVATE *) if p < 0 then return nil; end; return ^U8(p); end; (* Lets the pages from p, size bytes from a page boundary, be read and written as read and write say; neither, and touching them stops the program. 0, or minus an errno. *) proc protect*(p: ^U8; size: INT; read, write: BOOL): INT; var prot: INT; begin prot := 0; (* PROT_NONE *) if read then prot := 1; end; if write then prot := prot | 2; end; return SYSTEM.SYSCALL(10, p, size, prot); (* mprotect *) end; (* Whether the file descriptor fd is a terminal: whether it has a terminal's settings to read (ioctl TCGETS). *) proc isTerminal*(fd: INT): BOOL; var t: [8]INT; (* struct termios: 60 bytes *) begin return SYSTEM.SYSCALL(16, fd, 5401H, SYSTEM.ADR(t)) = 0; end; (* Renames old to new, replacing what new names: 0, or minus an errno. *) proc rename*(old, new: []const U8): INT; var a, b: [4096]U8; begin if not cstr(old, a) or not cstr(new, b) then return -36; end; return SYSTEM.SYSCALL(82, SYSTEM.ADR(a), SYSTEM.ADR(b)); end; (* Removes the file at path; not a directory. *) proc remove*(path: []const U8): INT; var a: [4096]U8; begin if not cstr(path, a) then return -36; end; return SYSTEM.SYSCALL(87, SYSTEM.ADR(a)); (* unlink *) end; (* Makes a directory at path, readable by all, writable by its owner. *) proc makeDir*(path: []const U8): INT; var a: [4096]U8; begin if not cstr(path, a) then return -36; end; return SYSTEM.SYSCALL(83, SYSTEM.ADR(a), 1EDH); (* mkdir, mode 755 *) end; (* Makes a directory at path with the permission bits mode, less those the umask takes away: 1C0H (700) for one only its owner may enter. Of the bits above them Linux keeps only sticky, 200H. *) proc makeDirMode*(path: []const U8; mode: INT): INT; var a: [4096]U8; begin if not cstr(path, a) then return -36; end; return SYSTEM.SYSCALL(83, SYSTEM.ADR(a), mode); (* mkdir *) end; (* Makes a fifo (a named pipe) at path with the permission bits mode, less those the umask takes away. 0, or minus an errno. *) proc makeFifo*(path: []const U8; mode: INT): INT; var a: [4096]U8; begin if not cstr(path, a) then return -36; end; return SYSTEM.SYSCALL(133, SYSTEM.ADR(a), 1000H | (mode & 1FFH), 0); (* mknod, S_IFIFO *) end; (* Sets the owner and group of what path names, following a symbolic link: a user or group number, or -1 to leave it as it is. Only root may give a file away. 0, or minus an errno. *) proc chown*(path: []const U8; uid, gid: INT): INT; var a: [4096]U8; begin if not cstr(path, a) then return -36; end; return SYSTEM.SYSCALL(92, SYSTEM.ADR(a), uid, gid); (* chown *) end; (* Removes the directory at path, which must be empty. *) proc removeDir*(path: []const U8): INT; var a: [4096]U8; begin if not cstr(path, a) then return -36; end; return SYSTEM.SYSCALL(84, SYSTEM.ADR(a)); (* rmdir *) end; (* Sets the permission bits of what path names. *) proc chmod*(path: []const U8; mode: INT): INT; var a: [4096]U8; begin if not cstr(path, a) then return -36; end; return SYSTEM.SYSCALL(90, SYSTEM.ADR(a), mode); end; (* Sets when the contents of what path names last changed, and when it was last read, to sec seconds and nsec nanoseconds since 1970, as a program copying a file keeps its time: Info.seconds gives sec back, whatever the time. *) proc setTime*(path: []const U8; sec: I64; nsec: INT): INT; var a: [4096]U8; t: [2]Timespec; begin if not cstr(path, a) then return -36; end; if (nsec < 0) or (nsec >= 1000000000) then return -22; end; (* EINVAL *) t[0].sec := sec; t[0].nsec := nsec; t[1] := t[0]; return SYSTEM.SYSCALL(280, -100, SYSTEM.ADR(a), SYSTEM.ADR(t), 0); (* utimensat, from the working directory *) end; (* 0 if this user, by its real ids, may do with path what how asks: reading, writing and executing; minus an errno, -13 (EACCES) if not. An empty how asks only whether path is there. *) proc access*(path: []const U8; how: Accesses): INT; var a: [4096]U8; m: INT; begin if not cstr(path, a) then return -36; end; m := 0; (* F_OK *) if reading in how then m := m | 4; end; (* R_OK *) if writing in how then m := m | 2; end; (* W_OK *) if executing in how then m := m | 1; end; (* X_OK *) return SYSTEM.SYSCALL(21, SYSTEM.ADR(a), m); (* access *) end; (* Sets the bits taken from every file this program, and the programs it starts, make: the mask it was. *) proc umask*(mask: INT): INT; begin return SYSTEM.SYSCALL(95, mask & 1FFH); (* umask *) end; (* Makes path a symbolic link to target. *) proc symlink*(target, path: []const U8): INT; var a, b: [4096]U8; begin if not cstr(target, a) or not cstr(path, b) then return -36; end; return SYSTEM.SYSCALL(88, SYSTEM.ADR(a), SYSTEM.ADR(b)); end; (* What the symbolic link at path names, good until the next call; and 0, or minus an errno. *) proc readLink*(path: []const U8): ([]const U8, INT); var a: [4096]U8; n: INT; begin if not cstr(path, a) then return "", -36; end; n := SYSTEM.SYSCALL(89, SYSTEM.ADR(a), SYSTEM.ADR(linked), LEN(linked)); (* readlink *) if n < 0 then return "", n; end; if n = LEN(linked) then return "", -36; end; (* it may be cut short *) return linked[0..n], 0; end; (* An Info from a struct stat, all but symlink. *) proc fromStat(st: [18]INT): Info; var i: Info; begin i.size := st[6]; (* st_size *) i.dev := U64(st[0]); (* st_dev *) i.ino := U64(st[1]); (* st_ino *) i.links := U64(st[2]); (* st_nlink *) i.mtime := st[11] * 1000000000 + st[12]; (* st_mtim *) i.seconds := st[11]; i.mode := st[3] & 1FFH; i.special := st[3] & 0E00H; i.uid := (st[3] shr 32) & 0FFFFFFFFH; (* st_uid *) i.gid := st[4] & 0FFFFFFFFH; (* st_gid *) i.dir := st[3] & 0F000H = 4000H; (* S_IFDIR *) i.file := st[3] & 0F000H = 8000H; (* S_IFREG *) return i; end; (* The size of what path names, whether it is a directory or a regular file, following a symbolic link, and whether path is one; and 0, or minus an errno. *) proc info*(path: []const U8): (Info, INT); var a: [4096]U8; st: [18]INT; i: Info; r: INT; isLink: BOOL; (* struct stat: 144 bytes *) begin if not cstr(path, a) then return i, -36; end; r := SYSTEM.SYSCALL(6, SYSTEM.ADR(a), SYSTEM.ADR(st)); (* lstat *) if r # 0 then return i, r; end; isLink := st[3] & 0F000H = 0A000H; (* st_mode is S_IFLNK *) r := SYSTEM.SYSCALL(4, SYSTEM.ADR(a), SYSTEM.ADR(st)); (* stat *) if r # 0 then return i, r; end; i := fromStat(st); i.symlink := isLink; return i, 0; end; (* info of path itself: if it is a symbolic link, of the link, not of what it names, so that symlink is true, dir and file false, and the size the length of what it names. *) proc linkInfo*(path: []const U8): (Info, INT); var a: [4096]U8; st: [18]INT; i: Info; r: INT; begin if not cstr(path, a) then return i, -36; end; r := SYSTEM.SYSCALL(6, SYSTEM.ADR(a), SYSTEM.ADR(st)); (* lstat *) if r # 0 then return i, r; end; i := fromStat(st); i.symlink := st[3] & 0F000H = 0A000H; (* S_IFLNK *) return i, 0; end; (* info of the file open on fd, which is never a link. *) proc infoOf*(fd: INT): (Info, INT); var st: [18]INT; i: Info; r: INT; begin r := SYSTEM.SYSCALL(5, fd, SYSTEM.ADR(st)); (* fstat *) if r # 0 then return i, r; end; return fromStat(st), 0; end; (* The bytes free to an ordinary user on path's file system, and the bytes in all. *) proc space*(path: []const U8): (I64, I64, INT); var a: [4096]U8; st: [15]INT; r, unit: INT; (* struct statfs: 120 bytes *) begin if not cstr(path, a) then return 0, 0, -36; end; r := SYSTEM.SYSCALL(137, SYSTEM.ADR(a), SYSTEM.ADR(st)); (* statfs *) if r # 0 then return 0, 0, r; end; unit := st[9]; (* f_frsize, the unit blocks are counted in *) if unit = 0 then unit := st[1]; end; (* f_bsize *) return st[4] * unit, st[2] * unit, 0; (* f_bavail, f_blocks *) end; (* The Kind of a d_type, as getdents64 and readdir give it: DT_REG is 8, DT_DIR 4, DT_LNK 10, DT_UNKNOWN 0, and the rest (pipes, devices, sockets) other things. *) proc kindOf(t: U8): Kind; begin if t = 8 then return isFile; elsif t = 4 then return isDir; elsif t = 10 then return isLink; elsif t = 0 then return unknown; end; return isOther; end; (* Opens the directory at path, for nextEntry. *) proc openDir*(var d: Dir; path: []const U8): INT; var a: [4096]U8; begin d.kind := unknown; d.pos := 0; d.len := 0; if not cstr(path, a) then return -36; end; d.fd := SYSTEM.SYSCALL(2, SYSTEM.ADR(a), 90000H); (* open, O_RDONLY, O_DIRECTORY, O_CLOEXEC *) if d.fd < 0 then return d.fd; end; return 0; end; (* The next name in the directory, good until the next call, but . and .., in no order; false at the end. *) proc nextEntry*(var d: Dir): ([]const U8, BOOL); var n, at: INT; begin while true do if d.pos >= d.len then d.len := SYSTEM.SYSCALL(217, d.fd, SYSTEM.ADR(d.buf), LEN(d.buf)); (* getdents64 *) d.pos := 0; if d.len <= 0 then return "", false; end; end; (* a record: d_ino and d_off, 8 bytes each; d_reclen, 2; d_type, 1; then d_name, ending in a zero *) at := d.pos + 19; n := 0; while d.buf[at + n] # 0 do INC(n); end; d.kind := kindOf(d.buf[d.pos + 18]); INC(d.pos, INT(d.buf[d.pos + 16]) + INT(d.buf[d.pos + 17]) * 256); if (d.buf[at..at + n] # ".") and (d.buf[at..at + n] # "..") then return d.buf[at..at + n], true; end; end; return "", false; end; (* What the name nextEntry gave last is, as the directory says, so that a walk needn't ask each file with linkInfo; unknown where the file system doesn't say. A link is isLink, whatever it names. *) proc entryKind*(const d: Dir): Kind; begin return d.kind; end; (* Closes the directory d that openDir opened. *) proc closeDir*(var d: Dir); begin _ := SYSTEM.SYSCALL(3, d.fd); end; (* Puts the terminal on fd into raw mode: no echo, no lines, no signals, no flow control, no CR to NL, no NL to CR NL; false if fd isn't a terminal. *) proc rawMode*(fd: INT): BOOL; var t: Termios; begin if SYSTEM.SYSCALL(16, fd, 5401H, SYSTEM.ADR(saved)) # 0 then return false; end; (* TCGETS *) t := saved; t.iflag := t.iflag & ~U32(5EBH); (* IGNBRK BRKINT PARMRK ISTRIP INLCR IGNCR ICRNL IXON *) t.oflag := t.oflag & ~U32(1); (* OPOST *) t.cflag := t.cflag & ~U32(130H) | 30H; (* CS8, no PARENB *) t.lflag := t.lflag & ~U32(804BH); (* ISIG ICANON ECHO ECHONL IEXTEN *) t.cc[5] := 0; (* VTIME: no time limit *) t.cc[6] := 1; (* VMIN: a byte at least *) return SYSTEM.SYSCALL(16, fd, 5402H, SYSTEM.ADR(t)) = 0; (* TCSETS *) end; (* The terminal on fd as rawMode found it. *) proc restoreMode*(fd: INT); begin _ := SYSTEM.SYSCALL(16, fd, 5402H, SYSTEM.ADR(saved)); end; (* The modes of the terminal on fd, as a shell keeps them for each job; and 0, or minus an errno, -25 (ENOTTY) if it isn't a terminal. *) proc getMode*(fd: INT): (Mode, INT); var m: Mode; r: INT; begin r := SYSTEM.SYSCALL(16, fd, 5401H, SYSTEM.ADR(m.t)); (* TCGETS *) return m, r; end; (* Gives the terminal on fd the modes m, once what was written to it is sent: 0, or minus an errno. *) proc setMode*(fd: INT; m: Mode): INT; begin return SYSTEM.SYSCALL(16, fd, 5403H, SYSTEM.ADR(m.t)); (* TCSETSW *) end; (* The columns and rows of the terminal on fd; 80 by 24 if it doesn't say. *) proc termSize*(fd: INT): (INT, INT); var w: Winsize; begin if (SYSTEM.SYSCALL(16, fd, 5413H, SYSTEM.ADR(w)) # 0) or (w.cols = 0) or (w.rows = 0) then (* TIOCGWINSZ *) return 80, 24; end; return INT(w.cols), INT(w.rows); end; (* Whether fd has something to read within ms milliseconds; ms < 0 waits as long as it takes. *) proc ready*(fd, ms: INT): BOOL; var p: Pollfd; begin p := {fd: I32(fd), events: 1}; (* POLLIN *) return SYSTEM.SYSCALL(7, SYSTEM.ADR(p), 1, ms) > 0; (* poll *) end; (* The clock that only goes forward, in nanoseconds: for how long something takes. *) proc clock*: I64; var t: Timespec; begin _ := SYSTEM.SYSCALL(228, 1, SYSTEM.ADR(t)); (* clock_gettime: CLOCK_MONOTONIC *) return t.sec * 1000000000 + t.nsec; end; (* The time in nanoseconds since 1970-01-01, UTC. *) proc now*: I64; var t: Timespec; begin _ := SYSTEM.SYSCALL(228, 0, SYSTEM.ADR(t)); (* clock_gettime: CLOCK_REALTIME *) return t.sec * 1000000000 + t.nsec; end; (* Waits ms milliseconds. *) proc sleep*(ms: INT); var t: Timespec; at: I64; begin at := clock() + I64(ms) * 1000000; t := {sec: at div 1000000000, nsec: at mod 1000000000}; repeat until SYSTEM.SYSCALL(230, 1, 1, SYSTEM.ADR(t), 0) # -4; (* clock_nanosleep until t, again after EINTR *) end; (* Ends the program: random bytes can't be faked. *) proc noRandom; begin _ := write(stderr, "Sys.random: the kernel gave no random bytes\n"); _ := SYSTEM.SYSCALL(231, 2); (* exit *) end; (* Fills b with random bytes, from the kernel. Random bytes can't be faked, so if the kernel can't give them (no getrandom, or a filter refusing it) it says so on standard error and ends the program by exit with status 2. *) proc random*(b: []U8); var n, r: INT; begin n := 0; while n < LEN(b) do (* a signal may cut it short *) r := SYSTEM.SYSCALL(318, SYSTEM.ADR(b[n]), LEN(b) - n, 0); (* getrandom *) if r > 0 then INC(n, r); elsif r # errIntr then noRandom(); end; end; end; (* A socket of family and kind, connected to the address at a, of size bytes, or, if serving, bound to it and taking connections: its file descriptor, or minus an errno. It is closed in a program exec starts. *) proc socket(family, kind: INT; a: ^U8; size: INT; serving: BOOL): INT; var fd, r, one: INT; begin fd := SYSTEM.SYSCALL(41, family, kind | 80000H, 0); (* socket, SOCK_CLOEXEC *) if fd < 0 then return fd; end; if serving then one := 1; (* so that a server can start again at once *) _ := SYSTEM.SYSCALL(54, fd, 1, 2, SYSTEM.ADR(one), 4); (* setsockopt: SOL_SOCKET, SO_REUSEADDR *) r := SYSTEM.SYSCALL(49, fd, a, size); (* bind *) if (r = 0) and (kind = 1) then (* a stream socket takes connections; *) r := SYSTEM.SYSCALL(50, fd, 4096); (* one of datagrams only receives *) end; else r := SYSTEM.SYSCALL(42, fd, a, size); (* connect *) end; if r < 0 then close(fd); return r; end; return fd; end; (* path as a Unix socket's address in a, and the address's length, or -36 (ENAMETOOLONG) if it is too long. A path that starts with a zero byte is one of Linux's abstract names, which has no file and no trailing zero: its length ends with the name's. *) proc unixAddr(path: []const U8; a: ^SockaddrUn): INT; begin if LEN(path) >= LEN(a^.path) then return -36; end; a^.family := 1; (* AF_UNIX *) COPY(a^.path, path); if (LEN(path) > 0) and (path[0] = 0) then return 2 + LEN(path); end; return SIZE(SockaddrUn); end; (* A stream socket connected to the Unix socket at path. *) proc connect*(path: []const U8): INT; var a: SockaddrUn; size: INT; begin size := unixAddr(path, SYSTEM.ADR(a)); if size < 0 then return size; end; return socket(1, 1, ^U8(SYSTEM.ADR(a)), size, false); (* SOCK_STREAM *) end; (* A stream socket made at path, which must not be there yet, taking connections. *) proc listen*(path: []const U8): INT; var a: SockaddrUn; size: INT; begin size := unixAddr(path, SYSTEM.ADR(a)); if size < 0 then return size; end; return socket(1, 1, ^U8(SYSTEM.ADR(a)), size, true); end; (* The value of the hexadecimal digit c, or -1 if it isn't one. *) proc hexDigit(c: U8): INT; begin if (c >= '0') and (c <= '9') then return INT(c - '0'); end; if (c >= 'a') and (c <= 'f') then return INT(c - 'a') + 10; end; if (c >= 'A') and (c <= 'F') then return INT(c - 'A') + 10; end; return -1; end; (* The IPv4 address s, four numbers and dots, in out's 4 bytes, or false if it isn't one. *) proc ipv4(s: []const U8; out: []U8): BOOL; var b: [4]U8; n, i, v, d: INT; begin i := 0; for n := 0 to 3 do if n > 0 then if (i = LEN(s)) or (s[i] # '.') then return false; end; INC(i); end; v := 0; d := 0; while (i < LEN(s)) and (d < 3) and (s[i] >= '0') and (s[i] <= '9') do v := v * 10 + INT(s[i] - '0'); INC(i); INC(d); end; if (d = 0) or (v > 255) then return false; end; b[n] := U8(v); end; if i # LEN(s) then return false; end; for i := 0 to 3 do out[i] := b[i]; end; return true; end; (* The IPv6 address s, groups of hexadecimal digits and colons, one :: standing for groups of zeros, in out's 16 bytes, or false if it isn't one. *) proc ipv6(s: []const U8; out: []U8): BOOL; var g: [8]INT; n, gap, i, v, d, k: INT; begin n := 0; gap := -1; (* the group the :: is before *) i := 0; if (LEN(s) >= 2) and (s[0..2] = "::") then gap := 0; i := 2; end; while i < LEN(s) do if n = 8 then return false; end; v := 0; d := 0; while (i < LEN(s)) and (d < 5) and (hexDigit(s[i]) >= 0) do v := v * 16 + hexDigit(s[i]); INC(i); INC(d); end; if (d = 0) or (d > 4) then return false; end; g[n] := v; INC(n); if i < LEN(s) then if s[i] # ':' then return false; end; INC(i); if i = LEN(s) then return false; end; if s[i] = ':' then if gap >= 0 then return false; end; gap := n; INC(i); end; end; end; if ((gap < 0) and (n < 8)) or ((gap >= 0) and (n = 8)) then return false; end; for i := 0 to 15 do out[i] := 0; end; for i := 0 to n - 1 do k := i; if (gap >= 0) and (i >= gap) then k := i + 8 - n; end; (* after the zeros *) out[2 * k] := U8(g[i] shr 8); out[2 * k + 1] := U8(g[i] & 255); end; return true; end; (* addr, an IPv4 or IPv6 address as numbers, and port, in a: the size of its struct sockaddr_in or sockaddr_in6, or 0 if either is wrong. *) proc inetAddr(addr: []const U8; port: INT; a: ^Sockaddr): INT; begin if (port < 0) or (port > 65535) then return 0; end; a^.port[0] := U8(port shr 8); (* in the network's order, the high byte first *) a^.port[1] := U8(port & 255); if ipv4(addr, a^.data[0..4]) then a^.family := 2; return 16; end; (* AF_INET *) if ipv6(addr, a^.data[4..20]) then a^.family := 10; return 28; end; (* AF_INET6 *) return 0; end; (* A socket of kind at addr and port, as socket makes it; -22 (EINVAL) if they are wrong. *) proc inet(addr: []const U8; port, kind: INT; serving: BOOL): INT; var a: Sockaddr; size: INT; begin size := inetAddr(addr, port, SYSTEM.ADR(a)); if size = 0 then return -22; end; return socket(INT(a.family), kind, ^U8(SYSTEM.ADR(a)), size, serving); end; (* A stream socket connected to port at addr, an IPv4 or IPv6 address as numbers. *) proc connectTcp*(addr: []const U8; port: INT): INT; begin return inet(addr, port, 1, false); (* SOCK_STREAM *) end; (* A socket of datagrams to and from port at addr. *) proc connectUdp*(addr: []const U8; port: INT): INT; begin return inet(addr, port, 2, false); (* SOCK_DGRAM *) end; (* A stream socket taking connections on port at addr; "0.0.0.0" or "::" is every address the machine has. *) proc listenTcp*(addr: []const U8; port: INT): INT; begin return inet(addr, port, 1, true); end; (* A socket of datagrams on port at addr, from anyone, for receive and reply. *) proc listenUdp*(addr: []const U8; port: INT): INT; begin return inet(addr, port, 2, true); end; (* The next connection to the socket fd, waiting for one: a socket of its own, closed in a program exec starts; or minus an errno. *) proc accept*(fd: INT): INT; begin return SYSTEM.SYSCALL(288, fd, 0, 0, 80000H); (* accept4, SOCK_CLOEXEC *) end; (* Ends this side's writing to the socket fd, so that the other end reads an end of input and can still answer on it. 0, or minus an errno. *) proc closeWrite*(fd: INT): INT; begin return SYSTEM.SYSCALL(48, fd, 1); (* shutdown, SHUT_WR *) end; (* Who is at the other end of the connected socket fd, and 0; or minus an errno. *) proc peer*(fd: INT): (Remote, INT); var r: Remote; a: Sockaddr; size, credSize: I32; cred: [3]I32; e: INT; begin r := {unix: false, ipv6: false}; size := I32(SIZE(Sockaddr)); e := SYSTEM.SYSCALL(52, fd, SYSTEM.ADR(a), SYSTEM.ADR(size)); (* getpeername *) if e < 0 then return r, e; end; if a.family = 1 then (* AF_UNIX: ask who made the connection *) credSize := I32(4 * LEN(cred)); e := SYSTEM.SYSCALL(55, fd, 1, 17, SYSTEM.ADR(cred), SYSTEM.ADR(credSize)); (* getsockopt: SOL_SOCKET, SO_PEERCRED *) if e < 0 then return r, e; end; r.unix := true; r.pid := INT(cred[0]); r.uid := INT(cred[1]); else r.port := (INT(a.port[0]) shl 8) | INT(a.port[1]); if a.family = 10 then (* AF_INET6 *) r.ipv6 := true; COPY(r.addr[0..16], a.data[4..20]); else COPY(r.addr[0..4], a.data[0..4]); end; end; return r, 0; end; (* Two connected stream sockets, as a Unix socket and the one that connects to it make: their fds and 0, closed in a program exec starts; or -1, -1 and minus an errno. *) proc socketPair*: (INT, INT, INT); var fds: [2]I32; r: INT; begin r := SYSTEM.SYSCALL(53, 1, 1 | 80000H, 0, SYSTEM.ADR(fds)); (* socketpair: AF_UNIX, SOCK_STREAM, SOCK_CLOEXEC *) if r < 0 then return -1, -1, r; end; return INT(fds[0]), INT(fds[1]), 0; end; (* Writes s to the socket fd, as write does, but returns -32 (EPIPE) where write would stop the program with SIGPIPE: when the other end has closed it. *) proc send*(fd: INT; s: []const U8): INT; begin if LEN(s) = 0 then return 0; end; return SYSTEM.SYSCALL(44, fd, SYSTEM.PTR(s), LEN(s), 4000H, 0, 0); (* sendto, MSG_NOSIGNAL, no address *) end; (* send, but never waits: returns -11 (EAGAIN) where send would wait for room, and doesn't make reads on fd non-blocking too. *) proc sendNow*(fd: INT; s: []const U8): INT; begin if LEN(s) = 0 then return 0; end; return SYSTEM.SYSCALL(44, fd, SYSTEM.PTR(s), LEN(s), 4040H, 0, 0); (* sendto, MSG_NOSIGNAL | MSG_DONTWAIT, no address *) end; (* Waits up to ms milliseconds (ms < 0: as long as it takes) until one of fds may be read or written as each one's read and write say, and sets each one's ready. The number ready, 0 on a timeout, or minus an errno. It takes as many as it is given: the system's list is built on the stack for 64 or fewer, else in memory from mmap, given back before it returns (-12 if there is none). *) proc poll*(var fds: []Poll; ms: INT): INT; var small: [64]Pollfd; list: []Pollfd; big: ^Pollfd; n, i, r: INT; events: I16; begin n := LEN(fds); big := nil; if n <= LEN(small) then list := small[0..n]; else big := ^Pollfd(mmap(n * SIZE(Pollfd))); if big = nil then return -12; end; (* ENOMEM *) list := big[0..n]; end; for i := 0 to n - 1 do events := 0; if fds[i].read then events := 1; end; (* POLLIN *) if fds[i].write then events := events | 4; end; (* POLLOUT *) list[i] := {fd: I32(fds[i].fd), events: events}; end; r := SYSTEM.SYSCALL(7, SYSTEM.PTR(list), n, ms); (* poll *) for i := 0 to n - 1 do fds[i].ready := (r > 0) and (list[i].revents # 0); end; if big # nil then munmap(^U8(big), n * SIZE(Pollfd)); end; return r; end; (* The first of reads that has something to read within ms milliseconds, or of writes that has room to write, or that has reached its end or failed, so that a read or a write won't wait; -1 if none has. ms < 0 waits as long as it takes. At most 64 fds in all. *) proc readyFor*(reads, writes: []const INT; ms: INT): INT; var p: [64]Poll; ps: []Poll; n, i: INT; begin n := 0; for i := 0 to LEN(reads) - 1 do if n < LEN(p) then p[n] := {fd: reads[i], read: true}; INC(n); end; end; for i := 0 to LEN(writes) - 1 do if n < LEN(p) then p[n] := {fd: writes[i], write: true}; INC(n); end; end; ps := p[0..n]; if poll(ps, ms) <= 0 then return -1; end; for i := 0 to n - 1 do if p[i].ready then return p[i].fd; end; end; return -1; end; (* The first of fds that has something to read within ms milliseconds, or that has reached its end or failed, so that a read won't wait; -1 if none has. ms < 0 waits as long as it takes. At most 64 fds. *) proc readyOf*(fds: []const INT; ms: INT): INT; begin return readyFor(fds, [], ms); end; (* Reads and writes on fd made to wait, as they do at first; or, if not yes, to return -11 (EAGAIN) at once where they would wait. 0, or minus an errno. *) proc setBlocking*(fd: INT; yes: BOOL): INT; var flags: INT; begin flags := SYSTEM.SYSCALL(72, fd, 3, 0); (* fcntl F_GETFL *) if flags < 0 then return flags; end; if yes then flags := flags & ~INT(800H); else flags := flags | 800H; end; (* O_NONBLOCK *) return SYSTEM.SYSCALL(72, fd, 4, flags); (* F_SETFL *) end; (* Whether reads and writes on fd wait, as they do at first: 1 if they do, 0 if they return -11 (EAGAIN) at once, or minus an errno. *) proc blocking*(fd: INT): INT; var flags: INT; begin flags := SYSTEM.SYSCALL(72, fd, 3, 0); (* fcntl F_GETFL *) if flags < 0 then return flags; end; if flags & 800H # 0 then return 0; end; (* O_NONBLOCK *) return 1; end; (* A stream socket connected to port at addr, as connectTcp makes it, or -110 (ETIMEDOUT) if it isn't connected within ms milliseconds. It starts to connect without waiting, then waits for the socket to be writable, which it is once connected or refused, and asks which. *) proc connectTcpWithin*(addr: []const U8; port, ms: INT): INT; var a: Sockaddr; size, fd, r: INT; err, errSize: I32; begin size := inetAddr(addr, port, SYSTEM.ADR(a)); if size = 0 then return -22; end; fd := SYSTEM.SYSCALL(41, INT(a.family), 1 | 80800H, 0); (* socket: SOCK_STREAM, SOCK_CLOEXEC, SOCK_NONBLOCK *) if fd < 0 then return fd; end; r := SYSTEM.SYSCALL(42, fd, SYSTEM.ADR(a), size); (* connect *) if r = -115 then (* EINPROGRESS *) r := -110; if readyFor([], [fd], ms) = fd then errSize := 4; r := SYSTEM.SYSCALL(55, fd, 1, 4, SYSTEM.ADR(err), SYSTEM.ADR(errSize)); (* getsockopt: SOL_SOCKET, SO_ERROR *) if r = 0 then r := -INT(err); end; end; end; if r = 0 then r := setBlocking(fd, true); end; if r < 0 then close(fd); return r; end; return fd; end; (* The port the socket fd is bound to, or minus an errno: for a socket made on port 0, the one the system chose. *) proc localPort*(fd: INT): INT; var a: Sockaddr; size: I32; r: INT; begin size := I32(SIZE(Sockaddr)); r := SYSTEM.SYSCALL(51, fd, SYSTEM.ADR(a), SYSTEM.ADR(size)); (* getsockname *) if r < 0 then return r; end; return (INT(a.port[0]) shl 8) | INT(a.port[1]); end; (* The next datagram to the socket fd, waiting for one: its first LEN(buf) bytes in buf, the rest lost, and who sent it. The number is the bytes in buf, or minus an errno. *) proc receive*(fd: INT; buf: []U8): (INT, Peer); var p: Peer; size: I32; n: INT; begin size := I32(SIZE(Sockaddr)); n := SYSTEM.SYSCALL(45, fd, SYSTEM.PTR(buf), LEN(buf), 0, SYSTEM.ADR(p.a), SYSTEM.ADR(size)); (* recvfrom *) p.size := INT(size); return n, p; end; (* Sends s, as one datagram, from the socket fd to peer, as receive gave it: the bytes sent, or minus an errno. *) proc reply*(fd: INT; peer: Peer; s: []const U8): INT; begin return SYSTEM.SYSCALL(44, fd, SYSTEM.PTR(s), LEN(s), 4000H, SYSTEM.ADR(peer.a), peer.size); (* sendto, MSG_NOSIGNAL *) end; (* Sends s, at least one byte, to the Unix socket fd, as send does, and with it the files fds, at most 16, which the program that receives them then has open too: the bytes sent, or minus an errno. *) proc sendFds*(fd: INT; s: []const U8; fds: []const INT): INT; var m: Msghdr; v: Iovec; c: Rights; i: INT; begin if (LEN(s) = 0) or (LEN(fds) > LEN(c.fds)) then return -22; end; v := {base: SYSTEM.PTR(s), size: LEN(s)}; m := {iov: SYSTEM.ADR(v), iovLen: 1}; if LEN(fds) > 0 then c := {size: 16 + 4 * LEN(fds), level: 1, kind: 1}; (* SOL_SOCKET, SCM_RIGHTS *) for i := 0 to LEN(fds) - 1 do c.fds[i] := I32(fds[i]); end; m.control := ^U8(SYSTEM.ADR(c)); m.controlSize := (c.size + 7) & ~7; (* CMSG_SPACE: whole quadwords *) end; return SYSTEM.SYSCALL(46, fd, SYSTEM.ADR(m), 4000H); (* sendmsg, MSG_NOSIGNAL *) end; (* Reads into buf from the Unix socket fd, as read does, and puts the files sent with what it read in fds, as many as fit, closing the rest: the bytes read, or minus an errno, and the files put in fds. Each is closed in a program exec starts. *) proc receiveFds*(fd: INT; buf: []U8; fds: []INT): (INT, INT); var m: Msghdr; v: Iovec; c: Rights; n, k, i: INT; begin v := {base: SYSTEM.PTR(buf), size: LEN(buf)}; m := {iov: SYSTEM.ADR(v), iovLen: 1, control: ^U8(SYSTEM.ADR(c)), controlSize: SIZE(Rights)}; n := SYSTEM.SYSCALL(47, fd, SYSTEM.ADR(m), 40000000H); (* recvmsg, MSG_CMSG_CLOEXEC *) if n < 0 then return n, 0; end; k := 0; if (m.controlSize >= 16) and (c.level = 1) and (c.kind = 1) then for i := 0 to (c.size - 16) div 4 - 1 do if k < LEN(fds) then fds[k] := INT(c.fds[i]); INC(k); else close(INT(c.fds[i])); end; end; end; return n, k; end; const (* what each errno means, as glibc's strerror says it; 41 and 58 are none *) errorTexts: [134][]const U8 = [ "Success", (* 0 *) "Operation not permitted", (* 1, EPERM *) "No such file or directory", (* 2, ENOENT *) "No such process", (* 3, ESRCH *) "Interrupted system call", (* 4, EINTR *) "Input/output error", (* 5, EIO *) "No such device or address", (* 6, ENXIO *) "Argument list too long", (* 7, E2BIG *) "Exec format error", (* 8, ENOEXEC *) "Bad file descriptor", (* 9, EBADF *) "No child processes", (* 10, ECHILD *) "Resource temporarily unavailable", (* 11, EAGAIN *) "Cannot allocate memory", (* 12, ENOMEM *) "Permission denied", (* 13, EACCES *) "Bad address", (* 14, EFAULT *) "Block device required", (* 15, ENOTBLK *) "Device or resource busy", (* 16, EBUSY *) "File exists", (* 17, EEXIST *) "Invalid cross-device link", (* 18, EXDEV *) "No such device", (* 19, ENODEV *) "Not a directory", (* 20, ENOTDIR *) "Is a directory", (* 21, EISDIR *) "Invalid argument", (* 22, EINVAL *) "Too many open files in system", (* 23, ENFILE *) "Too many open files", (* 24, EMFILE *) "Inappropriate ioctl for device", (* 25, ENOTTY *) "Text file busy", (* 26, ETXTBSY *) "File too large", (* 27, EFBIG *) "No space left on device", (* 28, ENOSPC *) "Illegal seek", (* 29, ESPIPE *) "Read-only file system", (* 30, EROFS *) "Too many links", (* 31, EMLINK *) "Broken pipe", (* 32, EPIPE *) "Numerical argument out of domain", (* 33, EDOM *) "Numerical result out of range", (* 34, ERANGE *) "Resource deadlock avoided", (* 35, EDEADLOCK *) "File name too long", (* 36, ENAMETOOLONG *) "No locks available", (* 37, ENOLCK *) "Function not implemented", (* 38, ENOSYS *) "Directory not empty", (* 39, ENOTEMPTY *) "Too many levels of symbolic links", (* 40, ELOOP *) "unknown error", (* 41 *) "No message of desired type", (* 42, ENOMSG *) "Identifier removed", (* 43, EIDRM *) "Channel number out of range", (* 44, ECHRNG *) "Level 2 not synchronized", (* 45, EL2NSYNC *) "Level 3 halted", (* 46, EL3HLT *) "Level 3 reset", (* 47, EL3RST *) "Link number out of range", (* 48, ELNRNG *) "Protocol driver not attached", (* 49, EUNATCH *) "No CSI structure available", (* 50, ENOCSI *) "Level 2 halted", (* 51, EL2HLT *) "Invalid exchange", (* 52, EBADE *) "Invalid request descriptor", (* 53, EBADR *) "Exchange full", (* 54, EXFULL *) "No anode", (* 55, ENOANO *) "Invalid request code", (* 56, EBADRQC *) "Invalid slot", (* 57, EBADSLT *) "unknown error", (* 58 *) "Bad font file format", (* 59, EBFONT *) "Device not a stream", (* 60, ENOSTR *) "No data available", (* 61, ENODATA *) "Timer expired", (* 62, ETIME *) "Out of streams resources", (* 63, ENOSR *) "Machine is not on the network", (* 64, ENONET *) "Package not installed", (* 65, ENOPKG *) "Object is remote", (* 66, EREMOTE *) "Link has been severed", (* 67, ENOLINK *) "Advertise error", (* 68, EADV *) "Srmount error", (* 69, ESRMNT *) "Communication error on send", (* 70, ECOMM *) "Protocol error", (* 71, EPROTO *) "Multihop attempted", (* 72, EMULTIHOP *) "RFS specific error", (* 73, EDOTDOT *) "Bad message", (* 74, EBADMSG *) "Value too large for defined data type", (* 75, EOVERFLOW *) "Name not unique on network", (* 76, ENOTUNIQ *) "File descriptor in bad state", (* 77, EBADFD *) "Remote address changed", (* 78, EREMCHG *) "Can not access a needed shared library", (* 79, ELIBACC *) "Accessing a corrupted shared library", (* 80, ELIBBAD *) ".lib section in a.out corrupted", (* 81, ELIBSCN *) "Attempting to link in too many shared libraries", (* 82, ELIBMAX *) "Cannot exec a shared library directly", (* 83, ELIBEXEC *) "Invalid or incomplete multibyte or wide character", (* 84, EILSEQ *) "Interrupted system call should be restarted", (* 85, ERESTART *) "Streams pipe error", (* 86, ESTRPIPE *) "Too many users", (* 87, EUSERS *) "Socket operation on non-socket", (* 88, ENOTSOCK *) "Destination address required", (* 89, EDESTADDRREQ *) "Message too long", (* 90, EMSGSIZE *) "Protocol wrong type for socket", (* 91, EPROTOTYPE *) "Protocol not available", (* 92, ENOPROTOOPT *) "Protocol not supported", (* 93, EPROTONOSUPPORT *) "Socket type not supported", (* 94, ESOCKTNOSUPPORT *) "Operation not supported", (* 95, ENOTSUP *) "Protocol family not supported", (* 96, EPFNOSUPPORT *) "Address family not supported by protocol", (* 97, EAFNOSUPPORT *) "Address already in use", (* 98, EADDRINUSE *) "Cannot assign requested address", (* 99, EADDRNOTAVAIL *) "Network is down", (* 100, ENETDOWN *) "Network is unreachable", (* 101, ENETUNREACH *) "Network dropped connection on reset", (* 102, ENETRESET *) "Software caused connection abort", (* 103, ECONNABORTED *) "Connection reset by peer", (* 104, ECONNRESET *) "No buffer space available", (* 105, ENOBUFS *) "Transport endpoint is already connected", (* 106, EISCONN *) "Transport endpoint is not connected", (* 107, ENOTCONN *) "Cannot send after transport endpoint shutdown", (* 108, ESHUTDOWN *) "Too many references: cannot splice", (* 109, ETOOMANYREFS *) "Connection timed out", (* 110, ETIMEDOUT *) "Connection refused", (* 111, ECONNREFUSED *) "Host is down", (* 112, EHOSTDOWN *) "No route to host", (* 113, EHOSTUNREACH *) "Operation already in progress", (* 114, EALREADY *) "Operation now in progress", (* 115, EINPROGRESS *) "Stale file handle", (* 116, ESTALE *) "Structure needs cleaning", (* 117, EUCLEAN *) "Not a XENIX named type file", (* 118, ENOTNAM *) "No XENIX semaphores available", (* 119, ENAVAIL *) "Is a named type file", (* 120, EISNAM *) "Remote I/O error", (* 121, EREMOTEIO *) "Disk quota exceeded", (* 122, EDQUOT *) "No medium found", (* 123, ENOMEDIUM *) "Wrong medium type", (* 124, EMEDIUMTYPE *) "Operation canceled", (* 125, ECANCELED *) "Required key not available", (* 126, ENOKEY *) "Key has expired", (* 127, EKEYEXPIRED *) "Key has been revoked", (* 128, EKEYREVOKED *) "Key was rejected by service", (* 129, EKEYREJECTED *) "Owner died", (* 130, EOWNERDEAD *) "State not recoverable", (* 131, ENOTRECOVERABLE *) "Operation not possible due to RF-kill", (* 132, ERFKILL *) "Memory page has hardware error" (* 133, EHWPOISON *)]; (* What errno err, or minus it, means, as C's strerror says it; "unknown error" for a number that is no errno. *) proc errorText*(err: INT): []const U8; begin if (err < 0) and (err > -LEN(errorTexts)) then err := -err; end; if (err < 0) or (err >= LEN(errorTexts)) then return "unknown error"; end; return errorTexts[err]; end; (* The environment, its NAME=values as C strings and a nil: the one the program started with, after the arguments and their nil, until setEnv makes one of its own. *) proc environment: ^^U8; begin if envp # nil then return envp; end; return SYSTEM.ARGV() + (ARGC() + 1); end; (* Whether the NAME=value s, a C string, is name's. *) proc named(s: ^U8; name: []const U8): BOOL; var n: INT; begin n := 0; while (n < LEN(name)) and (s[n] = name[n]) do INC(n); end; return (n = LEN(name)) and (s[n] = '='); end; (* The value of the environment variable name and true, or "" and false if it isn't set: "" and true if it is set to nothing. Every program calls env, from Rt, so this reads the environment itself rather than through environment and named, which would add their code to every executable. *) proc findEnv*(name: []const U8): ([]const U8, BOOL); var e: ^^U8; s: ^U8; i, n, m: INT; begin e := envp; if e = nil then e := SYSTEM.ARGV() + (ARGC() + 1); end; i := 0; while e[i] # nil do s := e[i]; n := 0; while (n < LEN(name)) and (s[n] = name[n]) do INC(n); end; if (n = LEN(name)) and (s[n] = '=') then m := n + 1; while s[m] # 0 do INC(m); end; return s[n + 1..m], true; end; INC(i); end; return "", false; end; (* The value of the environment variable name; "" if it isn't set. *) proc env*(name: []const U8): []const U8; var v: []const U8; begin v, _ := findEnv(name); return v; end; (* The environment's ith NAME=value, from 0, and true; "" and false past the last. *) proc envAt*(i: INT): ([]const U8, BOOL); var e: ^^U8; s: ^U8; j, n: INT; begin if i < 0 then return "", false; end; e := environment(); for j := 0 to i do if e[j] = nil then return "", false; end; end; s := e[i]; n := 0; while s[n] # 0 do INC(n); end; return s[0..n], true; end; (* The working directory, good until the next call; and 0, or minus an errno. *) proc workDir*: ([]const U8, INT); var r: INT; begin r := SYSTEM.SYSCALL(79, SYSTEM.ADR(cwd), LEN(cwd)); (* getcwd: its length with its zero *) if r < 0 then return "", r; end; return cwd[0..r - 1], 0; end; (* Makes path the working directory. *) proc setWorkDir*(path: []const U8): INT; var a: [4096]U8; begin if not cstr(path, a) then return -36; end; return SYSTEM.SYSCALL(80, SYSTEM.ADR(a)); (* chdir *) end; (* A pseudo-terminal: the file descriptor of its controlling side, or minus an errno. Its other side, the terminal its programs run on, is unlocked, for spawn to open. *) proc openPty*: INT; var a: [4096]U8; fd, unlock: INT; begin _ := cstr("/dev/ptmx", a); fd := SYSTEM.SYSCALL(2, SYSTEM.ADR(a), 80102H); (* open: O_RDWR, O_NOCTTY, O_CLOEXEC *) if fd < 0 then return fd; end; unlock := 0; if SYSTEM.SYSCALL(16, fd, 40045431H, SYSTEM.ADR(unlock)) # 0 then (* TIOCSPTLCK *) close(fd); return -5; (* EIO *) end; return fd; end; (* Tells the terminal of the pseudo-terminal fd that it has cols columns and rows rows: 0, or minus an errno. *) proc setTermSize*(fd, cols, rows: INT): INT; var w: Winsize; begin w := {rows: U16(rows), cols: U16(cols)}; return SYSTEM.SYSCALL(16, fd, 5414H, SYSTEM.ADR(w)); (* TIOCSWINSZ *) end; (* Copies s and a zero to at: the byte after them. *) proc put(s: []const U8; at: ^U8): ^U8; begin COPY(at[0..LEN(s)], s); at[LEN(s)] := 0; return at + (LEN(s) + 1); end; (* Whether the NAME=value s, a C string, names a variable that one of env gives. *) proc replaced(s: ^U8; env: [][]const U8): BOOL; var i, n: INT; begin for i := 0 to LEN(env) - 1 do n := 0; while (n < LEN(env[i])) and (s[n] = env[i][n]) and (s[n] # '=') do INC(n); end; if (n < LEN(env[i])) and (env[i][n] = '=') and (s[n] = '=') then return true; end; end; return false; end; (* What execve takes, in fresh memory of the size returned: args as C strings and a nil, then the environment old with each NAME=value of env in place of its variable or added, and a nil; or nil. The environment follows the arguments. *) proc argsAndEnv(args, env: [][]const U8; old: ^^U8): (^^U8, INT); var p: ^^U8; s: ^U8; size, n, i, k: INT; begin n := 0; while old[n] # nil do INC(n); end; size := (LEN(args) + n + LEN(env) + 2) * SIZE(^U8); for i := 0 to LEN(args) - 1 do INC(size, LEN(args[i]) + 1); end; for i := 0 to LEN(env) - 1 do INC(size, LEN(env[i]) + 1); end; p := ^^U8(mmap(size)); if p = nil then return nil, 0; end; s := ^U8(p + (LEN(args) + n + LEN(env) + 2)); k := 0; for i := 0 to LEN(args) - 1 do p[k] := s; s := put(args[i], s); INC(k); end; p[k] := nil; INC(k); for i := 0 to n - 1 do if not replaced(old[i], env) then p[k] := old[i]; INC(k); end; end; for i := 0 to LEN(env) - 1 do p[k] := s; s := put(env[i], s); INC(k); end; p[k] := nil; return p, size; end; (* Sets the environment variable name to value, for env and for the programs this one starts; 0, or minus an errno: -22 if name is empty or holds an = or a 0, or value a 0, and -12 if there is no memory. As C's setenv does, it makes the environment the program's own the first time it adds a variable: an array of pointers that doubles when it is full, the old one given back. A variable set again keeps its place. A NAME=value is never given back, so that what env gave stays good for the rest of the run; they are taken in turn from blocks of 64 KB. It isn't safe while another thread reads the environment or starts a program, as C's setenv isn't. *) proc setEnv*(name, value: []const U8): INT; var e, p: ^^U8; s: ^U8; size, cap, n, i: INT; begin if LEN(name) = 0 then return -22; end; (* EINVAL *) for i := 0 to LEN(name) - 1 do if (name[i] = '=') or (name[i] = 0) then return -22; end; end; for i := 0 to LEN(value) - 1 do if value[i] = 0 then return -22; end; end; (* NAME=value, written where the next one goes, and taken only once the array has room for it *) size := LEN(name) + LEN(value) + 2; if size > envLeft then n := 10000H; if size > n then n := size; end; s := mmap(n); if s = nil then return -12; end; (* ENOMEM *) envText := s; envLeft := n; end; s := envText; COPY(s[0..LEN(name)], name); s[LEN(name)] := '='; COPY(s[LEN(name) + 1..size - 1], value); s[size - 1] := 0; e := environment(); if envp = nil then envLen := 0; while e[envLen] # nil do INC(envLen); end; end; i := 0; while (i < envLen) and not named(e[i], name) do INC(i); end; if i = envLen then (* a new variable: the array grows if it is the first, or full *) if (envp = nil) or (envLen + 1 = envCap) then cap := 2 * (envLen + 1); if cap < 32 then cap := 32; end; p := ^^U8(mmap(cap * SIZE(^U8))); if p = nil then return -12; end; if envLen > 0 then COPY(p[0..envLen], e[0..envLen]); end; if envp # nil then munmap(^U8(envp), envCap * SIZE(^U8)); end; envp := p; envCap := cap; e := p; end; INC(envLen); e[envLen] := nil; end; e[i] := s; envText := envText + size; envLeft := envLeft - size; return 0; end; (* A pipe: the fd to read and the fd to write, both closed in a program exec starts; or minus an errno and -1. *) proc pipe*: (INT, INT); var fds: [2]I32; r: INT; begin r := SYSTEM.SYSCALL(293, SYSTEM.ADR(fds), 80000H); (* pipe2, O_CLOEXEC *) if r < 0 then return r, -1; end; return INT(fds[0]), INT(fds[1]); end; (* This program's process id. *) proc pid*: INT; begin return SYSTEM.SYSCALL(39); (* getpid *) end; (* The user this program runs as: its real id. *) proc uid*: INT; begin return SYSTEM.SYSCALL(102); (* getuid *) end; (* The user whose rights this program has, its effective id: 0 is root. *) proc euid*: INT; begin return SYSTEM.SYSCALL(107); (* geteuid *) end; (* The name of this machine, good until the next call; and 0, or minus an errno. *) proc hostName*: ([]const U8, INT); var r, n: INT; begin r := SYSTEM.SYSCALL(63, SYSTEM.ADR(uts)); (* uname *) if r < 0 then return "", r; end; n := 0; while (n < 64) and (uts[65 + n] # 0) do INC(n); end; (* the nodename, at 65 *) return uts[65..65 + n], 0; end; (* The number of processors this program may run on, at least 1. *) proc processors*: INT; var mask: [1024]U8; n, i, b, count: INT; begin n := SYSTEM.SYSCALL(204, 0, LEN(mask), SYSTEM.ADR(mask)); (* sched_getaffinity: this thread, the bytes it filled in *) count := 0; for i := 0 to n - 1 do for b := 0 to 7 do if (INT(mask[i]) shr b) & 1 = 1 then INC(count); end; end; end; if count < 1 then return 1; end; (* n < 0: it failed *) return count; end; (* The time on the processor, in ns, that this program has used, or, if children, the programs it started and waited for: in the program itself, and in the system for it. *) proc cpuTime*(children: BOOL): (I64, I64); var ru: [18]I64; (* struct rusage: two struct timeval first *) begin if children then _ := SYSTEM.SYSCALL(98, -1, SYSTEM.ADR(ru)); (* getrusage: RUSAGE_CHILDREN *) else _ := SYSTEM.SYSCALL(98, 0, SYSTEM.ADR(ru)); (* RUSAGE_SELF *) end; return ru[0] * 1000000000 + ru[1] * 1000, ru[2] * 1000000000 + ru[3] * 1000; end; (* The limit which, one of the limit constants: the soft one, which this program may raise up to the hard one; -1 for none; and 0, or minus an errno. *) proc limit*(which: INT): (I64, I64, INT); var r: [2]I64; err: INT; begin err := SYSTEM.SYSCALL(97, which, SYSTEM.ADR(r)); (* getrlimit; RLIM_INFINITY is -1 *) return r[0], r[1], err; end; (* Sets the limit which to soft and hard, -1 for none: 0, or minus an errno. *) proc setLimit*(which: INT; soft, hard: I64): INT; var r: [2]I64; begin r := [soft, hard]; return SYSTEM.SYSCALL(160, which, SYSTEM.ADR(r)); (* setrlimit *) end; (* Moves the program pid, or this one if pid is 0, to the process group group, or to a new one it leads if group is 0. *) proc setGroup*(pid, group: INT): INT; begin return SYSTEM.SYSCALL(109, pid, group); (* setpgid *) end; (* The process group this program is in. *) proc group*: INT; begin return SYSTEM.SYSCALL(111); (* getpgrp *) end; (* Gives the keys of the terminal on fd, and its signals, to the process group group. *) proc foreground*(fd, group: INT): INT; var g: I32; begin g := I32(group); return SYSTEM.SYSCALL(16, fd, 5410H, SYSTEM.ADR(g)); (* TIOCSPGRP *) end; (* The process group the terminal on fd gives its keys to, or minus an errno. *) proc foregroundOf*(fd: INT): INT; var g: I32; r: INT; begin r := SYSTEM.SYSCALL(16, fd, 540FH, SYSTEM.ADR(g)); (* TIOCGPGRP *) if r < 0 then return r; end; return INT(g); end; (* Where spawn looks for a program named without a /, if PATH is unset or empty: glibc's execvp looks in these. *) const defaultPath = "/bin:/usr/bin"; (* The ith directory of search, a list of them with : between, as PATH is: dir, "." if it is empty, and where the next starts; -1 past the last. *) proc pathDir(search: []const U8; i: INT): ([]const U8, INT); var j: INT; begin if i > LEN(search) then return "", -1; end; j := i; while (j < LEN(search)) and (search[j] # ':') do INC(j); end; if j = i then return ".", j + 1; end; return search[i..j], j + 1; end; (* dir, a /, and name, a C string in buf; false if it doesn't fit. *) proc joinPath(dir, name: []const U8; buf: []U8): BOOL; var n: INT; begin n := LEN(dir) + 1 + LEN(name); if n >= LEN(buf) then return false; end; COPY(buf, dir); buf[LEN(dir)] := '/'; COPY(buf[LEN(dir) + 1..n], name); buf[n] := 0; return true; end; (* Whether name holds a /, and so is a path, not a name to look for. *) proc isPath(name: []const U8): BOOL; var i: INT; begin for i := 0 to LEN(name) - 1 do if name[i] = '/' then return true; end; end; return false; end; (* Runs the program at name, as execve does; or, for a name without a /, the first program of that name in the directories of search, as execvp does: each in turn, an empty one being the working directory. It returns only if none could be run. It runs in spawn's child, after the fork, so it takes no memory: each path is made in buf. *) proc run(name, search: []const U8; buf: []U8; argv, envp: ^^U8); var dir: []const U8; i: INT; begin if isPath(name) or (LEN(name) = 0) then if cstr(name, buf) then _ := SYSTEM.SYSCALL(59, SYSTEM.ADR(buf[0]), argv, envp); end; (* execve *) return; end; dir, i := pathDir(search, 0); while i >= 0 do if joinPath(dir, name, buf) then _ := SYSTEM.SYSCALL(59, SYSTEM.ADR(buf[0]), argv, envp); end; (* execve *) dir, i := pathDir(search, i); end; end; (* The program exec runs for name, as a C string in buf: name itself if it has a /, or else the first file of that name in the directories of search that is no directory and that this user may run. 0; or -2 (ENOENT) if there is none, or -13 (EACCES) if one is there and can't be run. *) proc find(name, search: []const U8; buf: []U8): INT; var dir: []const U8; i, err, r: INT; f: Info; begin if isPath(name) then if not cstr(name, buf) then return -36; end; return 0; end; r := -2; (* ENOENT *) dir, i := pathDir(search, 0); while (LEN(name) > 0) and (i >= 0) do if joinPath(dir, name, buf) then f, err := info(buf[0..LEN(dir) + 1 + LEN(name)]); if (err = 0) and not f.dir then if SYSTEM.SYSCALL(21, SYSTEM.ADR(buf[0]), 1) = 0 then return 0; end; (* access, X_OK *) r := -13; (* EACCES *) end; end; dir, i := pathDir(search, i); end; return r; end; (* The name of the terminal of the pseudo-terminal fd, as a C string in name: /dev/pts/ and the number TIOCGPTN gives. 0, or -25 (ENOTTY). *) proc ptyName(fd: INT; name: []U8): INT; var n, i, size: INT; begin n := 0; if SYSTEM.SYSCALL(16, fd, 80045430H, SYSTEM.ADR(n)) # 0 then return -25; end; (* TIOCGPTN; ENOTTY *) i := put("/dev/pts/", SYSTEM.ADR(name[0])) - SYSTEM.ADR(name[0]) - 1; (* at its zero *) size := n; repeat INC(i); size := size div 10; until size = 0; name[i] := 0; repeat DEC(i); name[i] := U8(48 + n mod 10); n := n div 10; until n = 0; return 0; end; (* Closes every fd from 3 on but those of keep, which stay open in the program exec starts. It runs in spawn's child, after the fork, so it takes no memory: it closes the runs between the fds kept, the lowest first, each with one close_range. *) proc closeAllBut(keep: []const INT); var lo, next, i: INT; begin lo := 3; repeat next := -1; for i := 0 to LEN(keep) - 1 do if (keep[i] >= lo) and ((next < 0) or (keep[i] < next)) then next := keep[i]; end; end; if next < 0 then _ := SYSTEM.SYSCALL(436, lo, 0FFFFFFFFH, 0); (* close_range: the rest *) else if next > lo then _ := SYSTEM.SYSCALL(436, lo, next - 1, 0); end; _ := SYSTEM.SYSCALL(72, next, 2, 0); (* fcntl: F_SETFD, kept on exec *) lo := next + 1; end; until next < 0; end; (* What p asks of the program before it runs, done to this one: a session on the terminal name, if p.tty, or else its group, its terminal's foreground; then its standard input, output and error, each p.fds names over the terminal's; then its working directory, the C string dir. 0, or minus an errno. *) proc takeOn(p: Program; name, dir: []const U8): INT; var fd, i, r: INT; begin if p.tty # 0 then _ := SYSTEM.SYSCALL(112); (* setsid *) fd := SYSTEM.SYSCALL(2, SYSTEM.PTR(name), 2); (* open, O_RDWR *) if fd < 0 then return fd; end; r := SYSTEM.SYSCALL(16, fd, 540EH, 0); (* TIOCSCTTY *) if r # 0 then return r; end; for i := 0 to 2 do _ := SYSTEM.SYSCALL(33, fd, i); end; (* dup2 *) else if p.group = -1 then _ := SYSTEM.SYSCALL(109, 0, 0); (* setpgid *) elsif p.group # 0 then _ := SYSTEM.SYSCALL(109, 0, p.group); end; if p.foreground then _ := foreground(0, SYSTEM.SYSCALL(111)); end; (* getpgrp *) end; for i := 0 to 2 do if p.fds[i] = i then _ := keepOnExec(i, true); (* dup2 of a file onto itself would leave it closed on exec *) elsif p.fds[i] # 0 then _ := SYSTEM.SYSCALL(33, p.fds[i], i); (* dup2 *) end; end; if LEN(p.dir) > 0 then return SYSTEM.SYSCALL(80, SYSTEM.PTR(dir)); end; (* chdir *) return 0; end; (* Whether the signal sig does nothing now, as ignore(sig, true) or the program that started this one left it: its handler is SIG_IGN, 1. *) proc ignored*(sig: INT): BOOL; var act: [4]U64; (* struct sigaction *) begin _ := SYSTEM.SYSCALL(13, sig, 0, SYSTEM.ADR(act), 8); (* rt_sigaction *) return act[0] = 1; end; (* Starts the program p describes, found as run says: its process id, or minus an errno: -2 (ENOENT) or -13 (EACCES) as exec says, before the fork, if there is no program to run. A program found that execve then refuses ends with status 127. Every signal is blocked from the fork until the program has its own: its group, its terminal's foreground, and signals as they are at first. *) proc spawn*(p: Program): INT; var a, dir: [4096]U8; name: [32]U8; dfl: [4]U64; (* struct sigaction: SIG_DFL *) argv: ^^U8; none: ^U8; all, old, empty: U64; size, pid, i, g, r: INT; search: []const U8; begin if not cstr(p.path, a) or not cstr(p.dir, dir) then return -36; end; (* ENAMETOOLONG *) if (p.tty # 0) and (ptyName(p.tty, name) # 0) then return -25; end; (* ENOTTY *) none := nil; if p.onlyEnv then argv, size := argsAndEnv(p.args, p.env, SYSTEM.ADR(none)); else argv, size := argsAndEnv(p.args, p.env, environment()); end; if argv = nil then return -12; end; (* ENOMEM *) search := env("PATH"); (* read here, before the fork *) if LEN(search) = 0 then search := defaultPath; end; r := find(p.path, search, a); if r < 0 then munmap(^U8(argv), size); return r; end; all := 0FFFFFFFFFFFFFFFFH; _ := SYSTEM.SYSCALL(14, 2, SYSTEM.ADR(all), SYSTEM.ADR(old), 8); (* rt_sigprocmask: SIG_SETMASK *) pid := SYSTEM.SYSCALL(57); (* fork *) if pid = 0 then if takeOn(p, name, dir) # 0 then _ := SYSTEM.SYSCALL(231, 127); end; (* exit *) closeAllBut(p.more); for i := 1 to 64 do if not (p.keepIgnored and ignored(i)) then _ := SYSTEM.SYSCALL(13, i, SYSTEM.ADR(dfl), 0, 8); end; (* rt_sigaction *) end; _ := SYSTEM.SYSCALL(14, 2, SYSTEM.ADR(empty), 0, 8); (* no signal blocked *) run(p.path, search, a, argv, argv + (LEN(p.args) + 1)); _ := SYSTEM.SYSCALL(231, 127); (* exit *) end; if (pid > 0) and (p.tty = 0) then (* as the program does, for whichever of the two runs first *) g := p.group; if g = -1 then g := pid; elsif g = 0 then g := SYSTEM.SYSCALL(111); end; if p.group # 0 then _ := SYSTEM.SYSCALL(109, pid, g); end; if p.foreground then _ := foreground(0, g); end; end; _ := SYSTEM.SYSCALL(14, 2, SYSTEM.ADR(old), 0, 8); munmap(^U8(argv), size); return pid; end; (* Runs the program p describes in this one's place, as spawn would start it, but keeping this program's other fds as they are, open unless closed on exec (as open and pipe give) and not kept by keepOnExec; the fds of p.more are kept. It returns only if it can't: -2 (ENOENT) or -13 (EACCES) if there is no program to run, before anything is done; or, once the program's terminal, group, fds and working directory are as p asks, which stay so, minus the errno that stopped it, with this program's signals given back as they were. *) proc exec*(p: Program): INT; var a, dir: [4096]U8; name: [32]U8; dfl: [4]U64; acts: [65][4]U64; (* struct sigaction *) argv: ^^U8; none: ^U8; all, old, empty: U64; size, r, i: INT; search: []const U8; begin if not cstr(p.dir, dir) then return -36; end; (* ENAMETOOLONG *) if (p.tty # 0) and (ptyName(p.tty, name) # 0) then return -25; end; (* ENOTTY *) search := env("PATH"); if LEN(search) = 0 then search := defaultPath; end; r := find(p.path, search, a); if r < 0 then return r; end; none := nil; if p.onlyEnv then argv, size := argsAndEnv(p.args, p.env, SYSTEM.ADR(none)); else argv, size := argsAndEnv(p.args, p.env, environment()); end; if argv = nil then return -12; end; (* ENOMEM *) r := takeOn(p, name, dir); if r = 0 then for i := 0 to LEN(p.more) - 1 do if p.more[i] > 2 then _ := keepOnExec(p.more[i], true); end; end; (* every signal as it is at first and none blocked, as spawn gives them, each kept to give back if execve fails *) all := 0FFFFFFFFFFFFFFFFH; _ := SYSTEM.SYSCALL(14, 2, SYSTEM.ADR(all), SYSTEM.ADR(old), 8); (* rt_sigprocmask: SIG_SETMASK *) for i := 1 to 64 do _ := SYSTEM.SYSCALL(13, i, 0, SYSTEM.ADR(acts[i]), 8); (* rt_sigaction: as it is *) if not (p.keepIgnored and (acts[i][0] = 1)) then _ := SYSTEM.SYSCALL(13, i, SYSTEM.ADR(dfl), 0, 8); end; end; _ := SYSTEM.SYSCALL(14, 2, SYSTEM.ADR(empty), 0, 8); r := SYSTEM.SYSCALL(59, SYSTEM.ADR(a), argv, argv + (LEN(p.args) + 1)); (* execve *) _ := SYSTEM.SYSCALL(14, 2, SYSTEM.ADR(all), 0, 8); for i := 1 to 64 do _ := SYSTEM.SYSCALL(13, i, SYSTEM.ADR(acts[i]), 0, 8); end; _ := SYSTEM.SYSCALL(14, 2, SYSTEM.ADR(old), 0, 8); end; munmap(^U8(argv), size); return r; end; (* Runs the program at path in this one's place, with args, the first its name, and env, NAME=value, its whole environment, as the kernel's execve does and a shell wants: no search, and every fd and signal as it is, but that a handled signal does what it does at first. It returns only if it can't: minus an errno. *) proc execve*(path: []const U8; args, env: [][]const U8): INT; var a: [4096]U8; argv: ^^U8; none: ^U8; size, r: INT; begin if not cstr(path, a) then return -36; end; (* ENAMETOOLONG *) none := nil; argv, size := argsAndEnv(args, env, SYSTEM.ADR(none)); if argv = nil then return -12; end; (* ENOMEM *) r := SYSTEM.SYSCALL(59, SYSTEM.ADR(a), argv, argv + (LEN(args) + 1)); (* execve *) munmap(^U8(argv), size); return r; end; (* wait4 with options, its status read as C's macros read it. *) proc waitFor(pid, options: INT): (INT, Status, INT); var status: I32; r: INT; begin r := SYSTEM.SYSCALL(61, pid, SYSTEM.ADR(status), options, 0); (* wait4 *) if r <= 0 then return r, running, 0; end; if status & 7FH = 0 then return r, exited, INT(status) shr 8 & 0FFH; end; if status & 0FFH = 7FH then return r, stopped, INT(status) shr 8 & 0FFH; end; return r, killed, INT(status) & 7FH; end; (* Waits for the program pid, any of this program's if pid is -1, or any of the group g if pid is -g, to change, if block, and says which one changed and how: exited, with its exit status; killed or stopped, with the signal's number. Without block it doesn't wait: 0 and running if none has changed. Minus an errno, and running, if there is none to wait for. *) proc wait*(pid: INT; block: BOOL): (INT, Status, INT); var options: INT; begin options := 3; (* WNOHANG, WUNTRACED *) if block then options := 2; end; return waitFor(pid, options); end; (* Waits for the program pid as wait does, but only for one to end: a stopped program is not waited for, so the status is exited or killed, or running if there is none to wait for. *) proc waitExit*(pid: INT): (INT, Status, INT); begin return waitFor(pid, 0); end; (* Sends the program pid, or the group -pid, the signal: 0, or minus an errno. *) proc kill*(pid, signal: INT): INT; begin return SYSTEM.SYSCALL(62, pid, signal); end; (* Catches the signals sigs: blocks them, so that they don't do what they would, and gives them on an fd, which a later catch adds to and gives again; or minus an errno. Only the thread that catches them blocks them, and threads it starts later. ignore gives a signal up. *) proc catch*(sigs: []const INT): INT; var m: U64; i, fd: INT; begin m := caughtSigs; for i := 0 to LEN(sigs) - 1 do if (sigs[i] < 1) or (sigs[i] > 64) or (sigs[i] = sigKill) or (sigs[i] = sigStop) or (sigs[i] = 8) or (sigs[i] = 11) then (* SIGFPE and SIGSEGV, Rt's *) return -22; (* EINVAL *) end; m := m | U64(1) shl (sigs[i] - 1); end; fd := -1; if caughtSigs # 0 then fd := sigFd; end; _ := SYSTEM.SYSCALL(14, 0, SYSTEM.ADR(m), 0, 8); (* rt_sigprocmask: SIG_BLOCK *) fd := SYSTEM.SYSCALL(289, fd, SYSTEM.ADR(m), 8, 80800H); (* signalfd4: SFD_NONBLOCK, SFD_CLOEXEC *) if fd < 0 then return fd; end; caughtSigs := m; sigFd := fd; return fd; end; (* The next signal catch's fd has, or 0 if none is waiting. *) proc caught*(fd: INT): INT; var info: [128]U8; (* struct signalfd_siginfo: the number first, little-endian, below 65 *) begin if read(fd, info) # 128 then return 0; end; return INT(info[0]); end; (* Makes the signal sig do nothing, or, if not yes, what it does at first: 0, or minus an errno. A signal catch took is given up: it is unblocked in this thread, and catch's fd no longer gives it. *) proc ignore*(sig: INT; yes: BOOL): INT; var act: [4]U64; bit, m: U64; (* struct sigaction: its handler, SIG_IGN or SIG_DFL, first *) begin if yes then act[0] := 1; end; if (sig >= 1) and (sig <= 64) then bit := U64(1) shl (sig - 1); if caughtSigs & bit # 0 then caughtSigs := caughtSigs & ~bit; m := caughtSigs; _ := SYSTEM.SYSCALL(289, sigFd, SYSTEM.ADR(m), 8, 80800H); (* signalfd4: the signals still caught *) _ := SYSTEM.SYSCALL(14, 1, SYSTEM.ADR(bit), 0, 8); (* rt_sigprocmask: SIG_UNBLOCK *) end; end; return SYSTEM.SYSCALL(13, sig, SYSTEM.ADR(act), 0, 8); (* rt_sigaction *) end; (* Returns from a signal handler, as the kernel asks: rt_sigreturn, which sa_restorer names. *) proc sigReturn; code mov eax, 15; syscall; end sigReturn; (* The handler of the signals handle takes: it notes that sig came, and does nothing else, since it runs between any two instructions of the program, perhaps while Out or Heap holds its lock. *) proc onNoted(sig: INT); begin _ := XCHG(noted[sig], 1); end; (* Takes the signal sig away from what it would do: it is noted, for came to see, and a system call it comes during fails with -4 (EINTR) rather than going on, so that a program waiting for another, or for a key, sees Ctrl-C at once. 0, or minus an errno. ignore(sig, false) gives it back what it does at first. *) proc handle*(sig: INT): INT; var act: Action; begin if (sig < 1) or (sig > 64) or (sig = sigKill) or (sig = sigStop) or (sig = 8) or (sig = 11) then (* SIGFPE and SIGSEGV, Rt's *) return -22; (* EINVAL *) end; act := {handler: onNoted, flags: 4000000H, restorer: sigReturn}; (* SA_RESTORER, and no SA_RESTART *) return SYSTEM.SYSCALL(13, sig, SYSTEM.ADR(act), 0, 8); (* rt_sigaction *) end; (* Whether the signal sig, which handle took, came since the last time it was asked. *) proc came*(sig: INT): BOOL; begin if (sig < 1) or (sig > 64) then return false; end; return XCHG(noted[sig], 0) = 1; end; (* A copy of this program, which goes on from here: 0 in the copy, its process id in this one, or minus an errno. Only the thread that calls it is copied, so a program with threads mustn't; and what Out keeps is copied too, to be written twice, so the program flushes it first. *) proc fork*: INT; begin return SYSTEM.SYSCALL(57); (* fork *) end; (* A new session and process group, led by this program, with no controlling terminal: its process id, or minus an errno (-1, EPERM, if it leads a process group already, as a program just forked doesn't). *) proc setsid*: INT; begin return SYSTEM.SYSCALL(112); (* setsid *) end; (* Gives the processor to another thread. *) proc yield*; begin _ := SYSTEM.SYSCALL(24); end; (* Ends the program, at once, with status. *) proc exit*(status: INT); begin _ := SYSTEM.SYSCALL(231, status); end; (* The test of programs: one on a pseudo-terminal of 100 by 30 prints its arguments, a variable put in place and its size, and leads the terminal's foreground until it ends with status 3; one in a directory and an environment of its own writes to a pipe; one in a group of its own is stopped and killed through it; one that isn't there is no child, and one found that execve refuses ends with 127; ignored signals stay so only with keepIgnored; fds replace a terminal's files. Then signals: caught as a program ends and as one is sent; and a program starts with them neither caught nor ignored. *) proc testPrograms; var pty, child, n, m, r, w, sigs, c: INT; st: Status; buf: [64]U8; begin pty := openPty(); if (pty < 0) or (setTermSize(pty, 100, 30) # 0) then exit(2); end; child := spawn({path: "/bin/sh", args: ["sh", "-c", "echo $0 $1 $HOME; stty size; read x; exit 3", "a", "b"], env: ["HOME=/h"], tty: pty}); if child <= 0 then exit(2); end; n := 0; while n < 16 do if not ready(pty, 5000) then exit(2); end; m := read(pty, buf[n..LEN(buf)]); if m <= 0 then exit(2); end; INC(n, m); end; if (buf[0..n] # "a b /h\r\n30 100\r\n") or (foregroundOf(pty) # child) then exit(2); end; if write(pty, "\n") # 1 then exit(2); end; repeat if not ready(pty, 5000) then exit(2); end; until read(pty, buf) <= 0; (* -5, EIO, once the terminal has no program *) close(pty); r, st, c := wait(child, true); if (r # child) or (st # exited) or (c # 3) then exit(2); end; r, w := pipe(); if w < 0 then exit(2); end; child := spawn({path: "/bin/sh", args: ["sh", "-c", "echo $X $HOME; pwd"], env: ["X=x"], onlyEnv: true, dir: "/tmp", fds: [0, w, 0]}); close(w); n := 0; repeat m := read(r, buf[n..LEN(buf)]); if m > 0 then INC(n, m); end; until m <= 0; close(r); if buf[0..n] # "x\n/tmp\n" then exit(2); end; r, st, c := wait(child, true); if (r # child) or (st # exited) or (c # 0) then exit(2); end; (* a pipe filled without waiting, then emptied: room to write again *) r, w := pipe(); if (w < 0) or (setBlocking(w, false) # 0) or (setBlocking(r, false) # 0) then exit(2); end; repeat n := write(w, buf); until n < 0; if (n # -11) or (readyFor([], [w], 0) # -1) or (readyFor([r], [w], 0) # r) then exit(2); end; repeat n := read(r, buf); until n < 0; if (n # -11) or (readyFor([r], [w], 0) # w) or (setBlocking(w, true) # 0) then exit(2); end; close(r); close(w); (* blocking: a fresh pipe waits, a non-blocking one doesn't, a closed fd is -9 *) r, w := pipe(); if (blocking(r) # 1) or (setBlocking(r, false) # 0) or (blocking(r) # 0) then exit(2); end; if (setBlocking(r, true) # 0) or (blocking(r) # 1) then exit(2); end; close(r); close(w); if blocking(r) # -9 then exit(2); end; (* setsid: a forked child leads a session of its own, once; a group leader can't *) child := fork(); if child = 0 then if (setsid() # pid()) or (setsid() # -1) then exit(2); end; exit(0); end; r, st, c := wait(child, true); if (r # child) or (st # exited) or (c # 0) then exit(2); end; child := fork(); if child = 0 then if (setGroup(0, 0) # 0) or (setsid() # -1) then exit(2); end; exit(0); end; r, st, c := wait(child, true); if (r # child) or (st # exited) or (c # 0) then exit(2); end; child := spawn({path: "/bin/sleep", args: ["sleep", "10"], group: -1}); r, st, c := wait(child, false); if (r # 0) or (st # running) or (kill(-child, sigStop) # 0) then exit(2); end; r, st, c := wait(child, true); if (r # child) or (st # stopped) or (c # sigStop) or (kill(-child, sigKill) # 0) then exit(2); end; r, st, c := wait(-1, true); if (r # child) or (st # killed) or (c # sigKill) then exit(2); end; r, st, c := wait(-1, true); if r # -10 then exit(2); end; (* ECHILD: none left *) child := spawn({path: "/no/such/program", args: ["x"]}); r, st, c := wait(child, true); if (r # child) or (st # exited) or (c # 127) then exit(2); end; (* a name without a / is looked for along PATH *) child := spawn({path: "sh", args: ["sh", "-c", "exit 4"]}); r, st, c := wait(child, true); if (r # child) or (st # exited) or (c # 4) then exit(2); end; (* one not on PATH is no child at all *) if spawn({path: "no-such-program-on-path", args: ["x"]}) # -2 then exit(2); end; r, st, c := wait(-1, false); if r # -10 then exit(2); end; (* ECHILD: none was made *) (* an ignored signal stays so only with keepIgnored *) if ignore(sigInt, true) # 0 then exit(2); end; child := spawn({path: "sh", args: ["sh", "-c", "kill -INT $$; exit 6"], keepIgnored: true}); r, st, c := waitExit(child); if (r # child) or (st # exited) or (c # 6) then exit(2); end; child := spawn({path: "sh", args: ["sh", "-c", "kill -INT $$; exit 6"]}); r, st, c := waitExit(child); if (r # child) or (st # killed) or (c # sigInt) then exit(2); end; if ignore(sigInt, false) # 0 then exit(2); end; (* fds replace the terminal's files, with tty *) pty := openPty(); r, w := pipe(); child := spawn({path: "sh", args: ["sh", "-c", "echo out; echo err >&2"], tty: pty, fds: [0, w, 0]}); close(w); n := 0; repeat m := read(r, buf[n..LEN(buf)]); if m > 0 then INC(n, m); end; until m <= 0; close(r); r, st, c := waitExit(child); close(pty); if (buf[0..n] # "out\n") or (r # child) or (st # exited) or (c # 0) then exit(2); end; sigs := catch([sigChld, sigHup]); if (sigs < 0) or (catch([sigWinch]) # sigs) or (catch([11]) # -22) or (catch([sigKill]) # -22) then exit(2); end; if (caught(sigs) # 0) or (ignore(sigInt, true) # 0) then exit(2); end; child := spawn({path: "/bin/sh", args: ["sh", "-c", "kill -INT $$; exit 0"]}); if not ready(sigs, 5000) or (caught(sigs) # sigChld) then exit(2); end; r, st, c := wait(child, true); if (st # killed) or (c # sigInt) then exit(2); end; child := spawn({path: "/bin/sh", args: ["sh", "-c", "kill -HUP $$; exit 0"]}); r, st, c := wait(child, true); if (st # killed) or (c # sigHup) then exit(2); end; while caught(sigs) # 0 do end; if (kill(pid(), sigHup) # 0) or not ready(sigs, 1000) or (caught(sigs) # sigHup) then exit(2); end; if ignore(sigInt, false) # 0 then exit(2); end; end; (* The test of what a shell needs: fds copied, moved and kept on exec; a program given an fd at its own number, and one not; access, the umask and the environment by number; a terminal's modes; time used; limits; who and where; and exec, with nothing to run, and with a program that can't be run, after which the signals caught are caught still. *) proc testShell; var r, w, fd, n, k, child, c, err, pty, sigs, mask, parent: INT; t: I64; st: Status; buf: [64]U8; m, raw: Mode; soft, hard, s2, h2, user, system: I64; e: []const U8; ok, path: BOOL; begin r, w := pipe(); if w < 0 then exit(2); end; fd := dup(w); if (fd < 0) or (write(fd, "ab") # 2) or (read(r, buf) # 2) then exit(2); end; close(fd); if (dupTo(w, 9) # 9) or (write(9, "c") # 1) or (read(r, buf) # 1) or (buf[0] # 'c') then exit(2); end; if (keepOnExec(9, false) # 0) or (keepOnExec(9, true) # 0) or (keepOnExec(-1, true) # -9) then exit(2); end; child := spawn({path: "/bin/sh", args: ["sh", "-c", "echo more >&9"], more: [9]}); close(9); close(w); n := 0; repeat k := read(r, buf[n..LEN(buf)]); if k > 0 then INC(n, k); end; until k <= 0; close(r); if buf[0..n] # "more\n" then exit(2); end; k, st, c := wait(child, true); if (st # exited) or (c # 0) then exit(2); end; r, w := pipe(); if (w < 0) or (dupTo(w, 9) # 9) then exit(2); end; child := spawn({path: "/bin/sh", args: ["sh", "-c", "{ echo none >&9; } 2>/dev/null"]}); (* 9 is closed in it *) close(9); close(w); if read(r, buf) # 0 then exit(2); end; close(r); k, st, c := wait(child, true); if (st # exited) or (c = 0) then exit(2); end; if (access("/bin/sh", {executing}) # 0) or (access("/", {reading}) # 0) or (access("/no/such/file", {}) # -2) or (open("/bin/sh", {executing}) # -22) then exit(2); end; mask := umask(3FH); (* 077 *) if umask(mask) # 3FH then exit(2); end; path := false; n := 0; repeat e, ok := envAt(n); if ok and (LEN(e) > 5) and (e[0..5] = "PATH=") then path := true; end; INC(n); until not ok; e, ok := envAt(-1); if not path or ok or (LEN(e) # 0) then exit(2); end; (* a terminal's modes, kept and given back: a new one has lines *) pty := openPty(); m, err := getMode(pty); if (err # 0) or (m.t.lflag & 2 = 0) or not rawMode(pty) then exit(2); end; (* ICANON *) raw, err := getMode(pty); if (err # 0) or (raw.t.lflag & 2 # 0) or (setMode(pty, m) # 0) then exit(2); end; raw, err := getMode(pty); if (err # 0) or (raw.t.lflag & 2 = 0) then exit(2); end; m, err := getMode(-1); if err # -9 then exit(2); end; (* EBADF *) r, w := pipe(); m, err := getMode(r); if err # -25 then exit(2); end; (* ENOTTY *) close(r); close(w); close(pty); user, system := cpuTime(false); if (user < 0) or (system < 0) or (user + system = 0) then exit(2); end; user, system := cpuTime(true); if (user < 0) or (system < 0) then exit(2); end; soft, hard, err := limit(limitFiles); if (err # 0) or (soft < 16) or (setLimit(limitFiles, soft - 1, hard) # 0) then exit(2); end; s2, h2, err := limit(limitFiles); if (err # 0) or (s2 # soft - 1) or (h2 # hard) or (setLimit(limitFiles, soft, hard) # 0) then exit(2); end; soft, hard, err := limit(10000); if err # -22 then exit(2); end; (* EINVAL *) e, err := hostName(); if (err # 0) or (LEN(e) = 0) or (uid() < 0) or (euid() < 0) then exit(2); end; (* a copy of an fd out of the way; this program's group; a copy of this program, waited for by the group; a signal noted, and a wait it breaks into *) r, w := pipe(); fd := dupAbove(w, 10); if (fd < 10) or (write(fd, "d") # 1) or (read(r, buf) # 1) or (dupAbove(-1, 10) # -9) then exit(2); end; close(fd); if group() <= 0 then exit(2); end; child := fork(); if child = 0 then exit(7); end; k, st, c := wait(-group(), true); if (k # child) or (st # exited) or (c # 7) then exit(2); end; if (handle(sigUsr2) # 0) or came(sigUsr2) or (handle(sigKill) # -22) then exit(2); end; if (kill(pid(), sigUsr2) # 0) or not came(sigUsr2) or came(sigUsr2) then exit(2); end; parent := pid(); child := fork(); if child = 0 then sleep(100); _ := kill(parent, sigUsr2); exit(0); end; t := clock(); if ready(r, 5000) or not came(sigUsr2) or (clock() - t > 4000000000) then exit(2); end; k, st, c := wait(child, true); if (k # child) or (ignore(sigUsr2, false) # 0) then exit(2); end; close(r); close(w); sigs := catch([sigUsr1]); while caught(sigs) # 0 do end; (* the sigChld of the programs above *) if (sigs < 0) or (exec({path: "no-such-program-on-path", args: ["x"]}) # -2) then exit(2); end; if exec({path: "/etc/passwd", args: ["x"]}) # -13 then exit(2); end; (* not executable *) if (kill(pid(), sigUsr1) # 0) or not ready(sigs, 1000) or (caught(sigs) # sigUsr1) then exit(2); end; end; (* The test of time, random bytes and the network: a sleep the clock sees; addresses read and refused; a TCP connection on the loopback; a datagram to a port where no one listens, refused; servers on ports the system chooses, of streams and of datagrams. *) proc testNet; var t: I64; l, c, a, u, port, n: INT; x, y: [16]U8; s, s6: Sockaddr; peer: Peer; begin t := clock(); sleep(20); t := clock() - t; if (t < 20000000) or (t > 2000000000) or (now() < 1700000000 * 1000000000) then exit(2); end; random(x); random(y); if x[0..16] = y[0..16] then exit(2); end; if (inetAddr("10.0.0.255", 80, SYSTEM.ADR(s)) # 16) or (s.port[0] # 0) or (s.port[1] # 80) or (s.data[0] # 10) or (s.data[2] # 0) or (s.data[3] # 255) then exit(2); end; if (inetAddr("1:aBcd::ff", 258, SYSTEM.ADR(s6)) # 28) or (s6.port[0] # 1) or (s6.port[1] # 2) or (s6.data[0] # 0) or (s6.data[5] # 1) or (s6.data[6] # 0ABH) or (s6.data[7] # 0CDH) or (s6.data[18] # 0) or (s6.data[19] # 0FFH) then exit(2); end; if (inetAddr("::", 0, SYSTEM.ADR(s6)) # 28) or (inetAddr("1:2:3:4:5:6:7:8", 0, SYSTEM.ADR(s6)) # 28) then exit(2); end; if (connectTcp("1.2.3", 80) # -22) or (connectTcp("1.2.3.256", 80) # -22) or (connectTcp("1::2::3", 80) # -22) or (connectTcp("1:2:3:4:5:6:7:8:9", 80) # -22) or (connectTcp("1:", 80) # -22) or (connectTcp("12345::", 80) # -22) or (connectTcp("::1", 65536) # -22) then exit(2); end; l := listenTcp("127.0.0.1", 47391); c := connectTcp("127.0.0.1", 47391); if (l < 0) or (c < 0) then exit(2); end; a := accept(l); if (a < 0) or (send(c, "hi") # 2) or (read(a, x) # 2) or (x[0..2] # "hi") then exit(2); end; close(a); close(c); close(l); u := connectUdp("127.0.0.1", 47391); if (u < 0) or (send(u, "x") # 1) or not ready(u, 1000) or (read(u, x) # -111) then exit(2); end; (* ECONNREFUSED *) close(u); (* a server on a port the system chooses, and a connection to it within a time; then none, where no one listens *) l := listenTcp("127.0.0.1", 0); port := localPort(l); if (l < 0) or (port <= 0) then exit(2); end; c := connectTcpWithin("127.0.0.1", port, 1000); a := accept(l); if (c < 0) or (a < 0) or (send(c, "hi") # 2) or (read(a, x) # 2) then exit(2); end; close(a); close(c); close(l); if connectTcpWithin("127.0.0.1", port, 1000) # -111 then exit(2); end; (* a datagram to a server, and its answer *) l := listenUdp("127.0.0.1", 0); port := localPort(l); u := connectUdp("127.0.0.1", port); if (l < 0) or (port <= 0) or (u < 0) or (send(u, "ping") # 4) then exit(2); end; n, peer := receive(l, x[0..2]); if (n # 2) or (x[0..2] # "pi") or (reply(l, peer, "pong") # 4) then exit(2); end; if (read(u, x) # 4) or (x[0..4] # "pong") then exit(2); end; close(u); close(l); end; (* Runs a copy of this program that catches sigUsr1 and sigUsr2, gives up sigUsr1 by ignore(sigUsr1, yes) and sends itself send. The copy exits 0 if sigUsr1 then does nothing, or sigUsr2 still comes on catch's fd, and 1 if not; this says how it ended. *) proc giveUpChild(yes: BOOL; send: INT): (Status, INT); var child, c, fd: INT; st: Status; begin child := fork(); if child = 0 then fd := catch([sigUsr1, sigUsr2]); if fd < 0 then exit(3); end; while caught(fd) # 0 do end; (* what the parent had left there *) if (ignore(sigUsr1, yes) # 0) or (kill(pid(), send) # 0) then exit(3); end; if send = sigUsr1 then if ready(fd, 100) then exit(1); end; (* it ought to have ended, or be ignored *) exit(0); end; if not ready(fd, 1000) or (caught(fd) # sigUsr2) then exit(1); end; exit(0); end; _, st, c := wait(child, true); return st, c; end; (* The test of giving a caught signal up: with the default back it ends the program; ignored it does nothing; and the signals still caught still come on catch's fd. *) proc testGiveUp; var st: Status; c: INT; begin st, c := giveUpChild(false, sigUsr1); if (st # killed) or (c # sigUsr1) then exit(2); end; st, c := giveUpChild(true, sigUsr1); if (st # exited) or (c # 0) then exit(2); end; st, c := giveUpChild(false, sigUsr2); if (st # exited) or (c # 0) then exit(2); end; end; (* The test of what a program asks of itself: a signal ignored or not, an environment variable unset or empty, and the processors. *) proc testProcess; var v: []const U8; found: BOOL; begin if (ignore(sigUsr1, true) # 0) or not ignored(sigUsr1) then exit(2); end; if (ignore(sigUsr1, false) # 0) or ignored(sigUsr1) then exit(2); end; v, found := findEnv("RAZ_NO_SUCH_VARIABLE"); if found or (LEN(v) # 0) then exit(2); end; if setEnv("RAZ_SYS_TEST_EMPTY", "") # 0 then exit(2); end; v, found := findEnv("RAZ_SYS_TEST_EMPTY"); if not found or (LEN(v) # 0) then exit(2); end; v, found := findEnv("PATH"); if not found or (LEN(v) = 0) then exit(2); end; if processors() < 1 then exit(2); end; end; (* The test of what a server needs: a pair of sockets, one end told it has no more to read, who is at the other end of a Unix socket and of a TCP one, a send that doesn't wait, and a fifo opened without waiting. *) proc testServer; var a, b, l, c, s, port, n, r: INT; buf: [8]U8; full: [4096]U8; w: Remote; j: Info; begin a, b, r := socketPair(); if (r # 0) or (send(a, "hi") # 2) or (read(b, buf) # 2) or (buf[0..2] # "hi") then exit(2); end; if (closeWrite(a) # 0) or (read(b, buf) # 0) then exit(2); end; (* b reads an end, *) if (send(b, "yo") # 2) or (read(a, buf) # 2) or (buf[0..2] # "yo") then exit(2); end; (* and can still answer *) w, r := peer(a); if (r # 0) or not w.unix or (w.pid # pid()) or (w.uid # uid()) or (w.port # 0) or (w.addr[0] # 0) then exit(2); end; close(a); close(b); a, b, r := socketPair(); (* sendNow gives -11 once the socket is full, *) if r # 0 then exit(2); end; n := 0; while sendNow(a, full) = LEN(full) do INC(n); end; if (n = 0) or (sendNow(a, full) # errAgain) then exit(2); end; (* where send would wait *) close(a); close(b); _, r := peer(-1); if r # errBadFd then exit(2); end; l := listenTcp("127.0.0.1", 0); port := localPort(l); c := connectTcp("127.0.0.1", port); s := accept(l); if (l < 0) or (c < 0) or (s < 0) then exit(2); end; w, r := peer(c); if (r # 0) or w.unix or w.ipv6 or (w.port # port) or (w.addr[0..4] # "\x7f\x00\x00\x01") then exit(2); end; w, r := peer(s); if (r # 0) or (w.port = port) or (w.addr[3] # 1) or (w.addr[4] # 0) then exit(2); end; close(s); close(c); close(l); _ := remove("/tmp/raz-sys-fifo"); if makeFifo("/tmp/raz-sys-fifo", 1A4H) # 0 then exit(2); end; j, r := info("/tmp/raz-sys-fifo"); if (r # 0) or j.file or j.dir then exit(2); end; (* a fifo is neither *) if j.uid # uid() then exit(2); end; (* made by this user *) if (chown("/tmp/raz-sys-fifo", j.uid, j.gid) # 0) or (chown("/tmp/raz-sys-fifo", -1, -1) # 0) then exit(2); end; if chown("/no/such/file", -1, -1) # -2 then exit(2); end; if open("/tmp/raz-sys-fifo", {writing, nonblocking}) # -6 then exit(2); end; (* ENXIO: no reader, and it didn't wait *) a := open("/tmp/raz-sys-fifo", {reading, nonblocking}); b := open("/tmp/raz-sys-fifo", {writing, nonblocking}); if (a < 0) or (b < 0) or (read(a, buf) # errAgain) then exit(2); end; (* nothing to read, and it didn't wait *) close(a); close(b); _ := remove("/tmp/raz-sys-fifo"); end; (* The test of memory and files mapped: a file open only to read, mapped to be read, and not to be written; and pages that change what may be done with them. *) proc testMaps; var fd: INT; p, q: ^U8; begin fd := create("/tmp/raz-sys-map"); if (fd < 0) or (write(fd, "hello") # 5) then exit(2); end; close(fd); fd := openRead("/tmp/raz-sys-map"); if (fd < 0) or (mapFile(fd, 5) # nil) then exit(2); end; (* shared and writable: not for a file open to read *) p := mapRead(fd, 5); if (p = nil) or (p[0..5] # "hello") then exit(2); end; munmap(p, 5); close(fd); _ := remove("/tmp/raz-sys-map"); p := mmap(8192); if p = nil then exit(2); end; p[0] := 1; q := p + 4096; if (protect(q, 4096, true, false) # 0) or (q[0] # 0) then exit(2); end; if protect(q, 4096, true, true) # 0 then exit(2); end; q[0] := 2; if (protect(p, 4096, false, false) # 0) or (protect(p, 4096, true, true) # 0) or (p[0] # 1) then exit(2); end; (* its bytes stay *) munmap(p, 8192); end; (* poll over 100 socket pairs with a byte sent on three, so that all three are reported in one call, at their places; a timeout, 0; a closed descriptor, ready, and -9 from a read; and an abstract Unix socket, whose name starts with a zero byte. *) proc testPoll; var a: [100]Poll; ends: [100]INT; ps: []Poll; nm: [18]U8; buf: [4]U8; x, y, r, i, l, c, s: INT; begin for i := 0 to 99 do x, y, r := socketPair(); if r # 0 then exit(2); end; a[i] := {fd: x, read: true}; ends[i] := y; end; ps := a[0..100]; if poll(ps, 0) # 0 then exit(2); end; (* a timeout *) for i := 3 to 77 by 37 do (* 3, 40, 77 *) if send(ends[i], "x") # 1 then exit(2); end; end; if poll(ps, 1000) # 3 then exit(2); end; for i := 0 to 99 do if a[i].ready # ((i = 3) or (i = 40) or (i = 77)) then exit(2); end; end; for i := 3 to 77 by 37 do if read(a[i].fd, buf) # 1 then exit(2); end; end; if poll(ps, 0) # 0 then exit(2); end; close(a[5].fd); (* not open: ready, and a read says why *) if (poll(ps, 0) # 1) or not a[5].ready or (read(a[5].fd, buf) # -9) then exit(2); end; for i := 0 to 99 do close(ends[i]); if i # 5 then close(a[i].fd); end; end; nm[0] := 0; (* an abstract name: a zero byte, then 17 *) COPY(nm[1..18], "raz-abstract-test"); l := listen(nm); c := connect(nm); if (l < 0) or (c < 0) or (readyOf([c, l], 1000) # l) then exit(2); end; s := accept(l); if (s < 0) or (send(s, "x") # 1) or (readyOf([l, c], 1000) # c) then exit(2); end; close(s); close(c); close(l); end; (* The module's test: a file written, read back and closed; a directory made, listed and emptied; no terminal; a socket, sent to after its end; programs; time and the network. *) proc main*; var free, total: I64; fd, n, err, w, h, l, c, a, m, k, o: INT; got: [1]INT; buf: [16]U8; p, q: ^U8; i, j: Info; d: Dir; name: []const U8; ok: BOOL; begin testPoll(); fd := create("/tmp/raz-sys-test"); if fd < 0 then exit(2); end; if write(fd, "hello") # 5 then exit(2); end; close(fd); fd := openRead("/tmp/raz-sys-test"); if fd < 0 then exit(2); end; n := read(fd, buf); if (n # 5) or (buf[0..5] # "hello") or (read(fd, buf) # 0) then exit(2); end; close(fd); if openRead("/no/such/file") >= 0 then exit(2); end; if (errorText(-2) # "No such file or directory") or (errorText(13) # "Permission denied") or (errorText(41) # "unknown error") or (errorText(134) # "unknown error") then exit(2); end; if isTerminal(-1) then exit(2); end; p := mmap(100); if (p = nil) or (p[99] # 0) then exit(2); end; munmap(p, 100); (* files and directories *) _ := remove("/tmp/raz-sys-dir/f"); _ := remove("/tmp/raz-sys-dir/g"); _ := makeDir("/tmp/raz-sys-dir"); fd := create("/tmp/raz-sys-dir/f"); if (fd < 0) or (write(fd, "abc") # 3) then exit(2); end; close(fd); if rename("/tmp/raz-sys-dir/f", "/tmp/raz-sys-dir/g") # 0 then exit(2); end; i, err := info("/tmp/raz-sys-dir/g"); if (err # 0) or (i.size # 3) or i.dir or not i.file or i.symlink then exit(2); end; i, err := info("/tmp/raz-sys-dir"); if (err # 0) or not i.dir or i.file then exit(2); end; i, err := info("/dev/null"); if (err # 0) or i.dir or i.file then exit(2); end; free, total, err := space("/tmp"); if (err # 0) or (total <= 0) or (free < 0) or (free > total) then exit(2); end; free, total, err := space("/no/such/dir"); if err # -2 then exit(2); end; _ := remove("/tmp/raz-sys-link"); if symlink("/tmp/raz-sys-dir", "/tmp/raz-sys-link") # 0 then exit(2); end; i, err := info("/tmp/raz-sys-link"); if (err # 0) or not i.dir or not i.symlink then exit(2); end; i, err := linkInfo("/tmp/raz-sys-link"); if (err # 0) or i.dir or i.file or not i.symlink or (i.size # 16) then exit(2); end; i, err := linkInfo("/tmp/raz-sys-dir"); if (err # 0) or not i.dir or i.symlink or (i.ino = 0) then exit(2); end; name, err := readLink("/tmp/raz-sys-link"); if (err # 0) or (name # "/tmp/raz-sys-dir") then exit(2); end; name, err := readLink("/tmp/raz-sys-dir"); if err # -22 then exit(2); end; (* EINVAL: not a link *) _ := remove("/tmp/raz-sys-link"); if symlink("/no/such/file", "/tmp/raz-sys-link") # 0 then exit(2); end; (* dangling *) i, err := linkInfo("/tmp/raz-sys-link"); if (err # 0) or not i.symlink or (i.size # 13) then exit(2); end; _ := remove("/tmp/raz-sys-link"); (* open as asked, seek, the mode and the time *) _ := remove("/tmp/raz-sys-dir/h"); fd := open("/tmp/raz-sys-dir/h", {writing, creating, exclusive}); if (fd < 0) or (write(fd, "abc") # 3) then exit(2); end; close(fd); if open("/tmp/raz-sys-dir/h", {writing, creating, exclusive}) # -17 then exit(2); end; fd := open("/tmp/raz-sys-dir/h", {writing, appending}); if (fd < 0) or (seek(fd, 0, false) # 0) or (write(fd, "de") # 2) then exit(2); end; close(fd); fd := open("/tmp/raz-sys-dir/h", {reading, writing}); if (seek(fd, -2, true) # 3) or (read(fd, buf) # 2) or (buf[0..2] # "de") then exit(2); end; if (seek(fd, 1, false) # 1) or (write(fd, "B") # 1) or (seek(fd, 0, false) # 0) then exit(2); end; if (read(fd, buf) # 5) or (buf[0..5] # "aBcde") then exit(2); end; (* where it is, its size open, cut short, on the disk *) if (position(fd) # 5) or (seek(fd, 2, false) # 2) or (position(fd) # 2) then exit(2); end; if (truncate(fd, 4) # 0) or (position(fd) # 2) or (sync(fd) # 0) then exit(2); end; i, err := infoOf(fd); if (err # 0) or (i.size # 4) or not i.file or i.symlink then exit(2); end; m := INT(i.ino); i, err := info("/tmp/raz-sys-dir/h"); if (err # 0) or (INT(i.ino) # m) or (syncAll(fd) # 0) then exit(2); end; if syncAll(-1) # -9 then exit(2); end; (* EBADF *) (* the lock: one open file holds it, another can't take it until the first is closed *) k := openRead("/tmp/raz-sys-dir/h"); if (lock(fd, false) # 0) or (lock(k, false) # -11) then exit(2); end; close(fd); if lock(k, true) # 0 then exit(2); end; close(k); (* the shared lock: two open files hold it at once, lock is refused until both have gone, and a shared one while lock holds it *) fd := openRead("/tmp/raz-sys-dir/h"); k := openRead("/tmp/raz-sys-dir/h"); if (lockShared(fd, false) # 0) or (lockShared(k, true) # 0) then exit(2); end; o := openRead("/tmp/raz-sys-dir/h"); if lock(o, false) # -11 then exit(2); end; close(fd); close(k); if lock(o, false) # 0 then exit(2); end; fd := openRead("/tmp/raz-sys-dir/h"); if lockShared(fd, false) # -11 then exit(2); end; close(fd); close(o); if (position(fd) # -9) or (truncate(fd, 0) # -9) or (sync(fd) # -9) then exit(2); end; (* EBADF *) k := openRead("/tmp/raz-sys-dir/h"); if (closeChecked(k) # 0) or (closeChecked(k) # -9) then exit(2); end; i, err := infoOf(fd); if err # -9 then exit(2); end; i, err := info("/tmp/raz-sys-dir/h"); if (err # 0) or (i.mode & 1C0H # 180H) or (i.mtime < 1700000000 * 1000000000) then exit(2); end; if chmod("/tmp/raz-sys-dir/h", 1EDH) # 0 then exit(2); end; i, err := info("/tmp/raz-sys-dir/h"); if i.mode # 1EDH then exit(2); end; (* setTime, after 1970 and before it, to the nanosecond *) if setTime("/tmp/raz-sys-dir/h", 1234567890, 123456789) # 0 then exit(2); end; i, err := info("/tmp/raz-sys-dir/h"); if (i.mtime # 1234567890123456789) or (i.seconds # 1234567890) then exit(2); end; if setTime("/tmp/raz-sys-dir/h", -2, 500000000) # 0 then exit(2); end; i, err := info("/tmp/raz-sys-dir/h"); if (i.mtime # -1500000000) or (i.seconds # -2) then exit(2); end; if setTime("/tmp/raz-sys-dir/h", 10413792000, 0) # 0 then exit(2); end; (* 2300, past mtime's reach *) i, err := info("/tmp/raz-sys-dir/h"); if i.seconds # 10413792000 then exit(2); end; if setTime("/tmp/raz-sys-dir/h", 0, 1000000000) # -22 then exit(2); end; if setTime("/no/such/file", 0, 0) # -2 then exit(2); end; (* the special bits: set-user-id by chmod, and sticky by makeDirMode *) if chmod("/tmp/raz-sys-dir/h", 9EDH) # 0 then exit(2); end; i, err := info("/tmp/raz-sys-dir/h"); if (i.mode # 1EDH) or (i.special # 800H) then exit(2); end; if makeDirMode("/tmp/raz-sys-dir/m", 3C0H) # 0 then exit(2); end; i, err := info("/tmp/raz-sys-dir/m"); if (err # 0) or not i.dir or (i.mode # 1C0H) or (i.special # 200H) then exit(2); end; if removeDir("/tmp/raz-sys-dir/m") # 0 then exit(2); end; _ := remove("/tmp/raz-sys-dir/h"); fd := openMode("/tmp/raz-sys-dir/h", {writing, creating}, 1C0H); (* rwx------ *) close(fd); i, err := info("/tmp/raz-sys-dir/h"); if (fd < 0) or (err # 0) or (i.mode # 1C0H) then exit(2); end; _ := remove("/tmp/raz-sys-dir/h"); i, err := info("/no/such/file"); if err >= 0 then exit(2); end; if openDir(d, "/tmp/raz-sys-dir") # 0 then exit(2); end; name, ok := nextEntry(d); if not ok or (name # "g") then exit(2); end; if (entryKind(d) # isFile) and (entryKind(d) # unknown) then exit(2); end; i, err := info("/tmp/raz-sys-dir/g"); j, err := info("/tmp/raz-sys-dir"); if (err # 0) or (i.dev # j.dev) or (i.ino = j.ino) or (i.links # 1) then exit(2); end; name, ok := nextEntry(d); if ok then exit(2); end; closeDir(d); if (remove("/tmp/raz-sys-dir/g") # 0) or (remove("/tmp/raz-sys-dir/g") >= 0) then exit(2); end; if openDir(d, "/no/such/dir") >= 0 then exit(2); end; (* the terminal: none here, fd -1 *) if rawMode(-1) or ready(-1, 0) then exit(2); end; w, h := termSize(-1); if (w # 80) or (h # 24) then exit(2); end; (* the environment *) if (LEN(env("PATH")) = 0) or (LEN(env("RAZ_NO_SUCH_VARIABLE")) # 0) then exit(2); end; (* the environment set: refused, added, set again, grown past its first array *) if (setEnv("", "x") # -22) or (setEnv("A=B", "x") # -22) or (setEnv("A", "\x00") # -22) then exit(2); end; if (setEnv("RAZ_SYS_TEST", "one") # 0) or (env("RAZ_SYS_TEST") # "one") then exit(2); end; name := env("RAZ_SYS_TEST"); if (setEnv("RAZ_SYS_TEST", "") # 0) or (env("RAZ_SYS_TEST") # "") or (name # "one") then exit(2); end; buf := "RAZ_SYS_TEST_.."; for k := 0 to 99 do buf[13] := U8('0' + k div 10); buf[14] := U8('0' + k mod 10); if setEnv(buf[0..15], buf[13..15]) # 0 then exit(2); end; end; if (env("RAZ_SYS_TEST_42") # "42") or (env("RAZ_SYS_TEST") # "") or (LEN(env("PATH")) = 0) then exit(2); end; n := 0; k := 0; repeat name, ok := envAt(k); if (LEN(name) > 12) and (name[0..12] = "RAZ_SYS_TEST") then INC(n); end; INC(k); until not ok; if n # 101 then exit(2); end; name, err := workDir(); if (err # 0) or (LEN(name) = 0) or (name[0] # '/') then exit(2); end; if (setWorkDir("/tmp/raz-sys-dir") # 0) or (removeDir("/tmp/raz-sys-dir") # 0) then exit(2); end; if (setWorkDir("/") # 0) or (removeDir("/tmp/raz-sys-dir") # -2) then exit(2); end; (* a socket: nothing at a path, then a listener that a connection makes ready, and a byte from it to the connection *) if connect("/tmp/raz-no-such-socket") # -2 then exit(2); end; (* ENOENT *) _ := remove("/tmp/raz-sys-socket"); l := listen("/tmp/raz-sys-socket"); if (l < 0) or (listen("/tmp/raz-sys-socket") # -98) then exit(2); end; (* EADDRINUSE: there already *) c := connect("/tmp/raz-sys-socket"); if c < 0 then exit(2); end; if readyOf([c], 0) # -1 then exit(2); end; if readyOf([c, l], 1000) # l then exit(2); end; a := accept(l); if (a < 0) or (send(a, "x") # 1) or (readyOf([l, c], 1000) # c) then exit(2); end; if (read(c, buf) # 1) or (buf[0] # 'x') then exit(2); end; close(a); if (readyOf([c], 1000) # c) or (read(c, buf) # 0) then exit(2); end; (* its end *) if send(c, "x") # -32 then exit(2); end; (* EPIPE, and no SIGPIPE *) close(c); close(l); _ := remove("/tmp/raz-sys-socket"); (* a file in memory, mapped, and passed with a byte down a socket twice, with room for one: what the other side maps is the same *) m := memFile(8192); p := mapFile(m, 8192); if (m < 0) or (p = nil) or (p[8191] # 0) then exit(2); end; p[100] := 42; l := listen("/tmp/raz-sys-socket"); c := connect("/tmp/raz-sys-socket"); a := accept(l); if (l < 0) or (c < 0) or (a < 0) or (sendFds(c, "", [m]) # -22) or (sendFds(c, "f", [m, m]) # 1) then exit(2); end; n, k := receiveFds(a, buf, got); if (n # 1) or (k # 1) or (buf[0] # 'f') then exit(2); end; q := mapFile(got[0], 8192); if (q = nil) or (q[100] # 42) then exit(2); end; q[200] := 7; if p[200] # 7 then exit(2); end; munmap(p, 8192); munmap(q, 8192); close(got[0]); close(m); close(a); close(c); close(l); _ := remove("/tmp/raz-sys-socket"); testPrograms; testShell; testNet; testProcess; testGiveUp; testServer; testMaps; end; end Sys.