raz / lib / Sys.raz

2942 lines · 112.7 KiB · raw · history · last change 89524972

1(* System calls through the C library: Sys for the targets that have no
2 file of their own, with the same exports. A program that imports it
3 uses C.
4
5 It keeps to POSIX's names, and raw mode is cfmakeraw's. What the C
6 library fixes for its target, the numbers of flags, requests,
7 signals, limits and errnos, where a field lies in a struct, and the
8 two procedures whose names differ, it takes from CAbi, one file per
9 target, which tools/cabi.c writes; so a struct the C library fills
10 in or reads is bytes here, its fields read and written at CAbi's
11 offsets by field and setField. So do the calls that Linux's C
12 library has and another system's lacks (pipe2, accept4, getrandom,
13 memfd_create, clock_nanosleep, sched_getaffinity, SO_PEERCRED), which
14 CAbi makes there of what it has. A flag CAbi gives as 0, that system
15 lacking it, is done after: a socket closed on exec by keepOnExec. A failure is minus Linux's errno, on
16 every target: linux maps the C library's, and errorText maps back.
17 A terminal's modes, Mode, are its struct termios whole, which cabi
18 checks fits in 256 bytes. Still Linux's: what a wait status holds,
19 which every Unix encodes alike. *)
20module Sys;
21import C, CAbi;
22import SYSTEM;
23
24const
25 stdin* = 0; (* standard input's file descriptor *)
26 stdout* = 1; (* standard output's *)
27 stderr* = 2; (* standard error's *)
28 (* the bytes Out keeps before it writes them; a target with little
29 memory keeps fewer *)
30 outSize* = 4096;
31 (* signals, by the target's numbers *)
32 sigHup* = CAbi.sigHup; sigInt* = CAbi.sigInt; sigQuit* = CAbi.sigQuit;
33 sigKill* = CAbi.sigKill; sigPipe* = CAbi.sigPipe; sigTerm* = CAbi.sigTerm;
34 sigChld* = CAbi.sigChld; sigCont* = CAbi.sigCont; sigStop* = CAbi.sigStop;
35 sigTstp* = CAbi.sigTstp; sigTtin* = CAbi.sigTtin; sigTtou* = CAbi.sigTtou;
36 sigWinch* = CAbi.sigWinch; sigUsr1* = CAbi.sigUsr1; sigUsr2* = CAbi.sigUsr2;
37 sigAlrm* = CAbi.sigAlrm;
38 (* the limits limit and setLimit take, by the target's numbers *)
39 limitCpu* = CAbi.rlimitCpu; (* seconds of the processor *)
40 limitFileSize* = CAbi.rlimitFsize; (* bytes in a file it writes *)
41 limitData* = CAbi.rlimitData; (* bytes of its data *)
42 limitStack* = CAbi.rlimitStack; (* bytes of its stack *)
43 limitCore* = CAbi.rlimitCore; (* bytes of a core dump *)
44 limitProcs* = CAbi.rlimitNproc; (* processes of its user *)
45 limitFiles* = CAbi.rlimitNofile; (* one more than its highest fd *)
46 limitMemory* = CAbi.rlimitAs; (* bytes of its address space *)
47 (* errors, minus Linux's errnos, as on every target *)
48 errPerm* = -1; errNoEntry* = -2; errNoProcess* = -3; errIntr* = -4;
49 errIo* = -5; errBadFd* = -9; errChild* = -10; errAgain* = -11;
50 errNoMemory* = -12; errDenied* = -13; errExists* = -17;
51 errNotDir* = -20; errIsDir* = -21; errInvalid* = -22;
52 errNotTerminal* = -25; errNoSpace* = -28; errReadOnly* = -30; errPipe* = -32;
53 errNameTooLong* = -36; errNotEmpty* = -39; errLoop* = -40;
54 errAddrInUse* = -98; errNetUnreach* = -101; errConnAborted* = -103; errConnReset* = -104;
55 errTimedOut* = -110; errRefused* = -111; errHostUnreach* = -113;
56 errInProgress* = -115;
57
58type
59 (* One descriptor poll waits on: whether to wait to read from it, to
60 write to it, or both, and, when poll returns, whether it may be.
61 One that has reached its end, has failed or isn't open is ready
62 too, so that a read or a write finds out. *)
63 Poll* = record
64 fd*: INT; (* the file descriptor; a negative one is never ready *)
65 read*: BOOL; (* wait until it has something to read *)
66 write*: BOOL; (* wait until it has room to write *)
67 ready*: BOOL; (* set by poll: a read or a write on it won't wait *)
68 end;
69
70 (* What open is asked for: reading, writing or both, and what else
71 it does to the file; nonblocking, that open doesn't wait (for a
72 fifo's other end) and reads and writes on the file don't either. *)
73 Access* = (reading, writing, creating, exclusive, truncating,
74 appending, executing, nonblocking);
75 Accesses* = set of Access; (* what open is given *)
76
77 (* What info says of a file. *)
78 Info* = record
79 size*: I64; (* in bytes *)
80 mtime*: I64; (* its contents' last change, in ns since 1970 *)
81 seconds*: I64; (* mtime in whole seconds, rounded down: exact past 2262 and before 1677, where mtime wraps *)
82 mode*: INT; (* its permission bits, rwxrwxrwx *)
83 dir*: BOOL; (* a directory *)
84 file*: BOOL; (* not a directory, device, pipe or socket *)
85 symlink*: BOOL; (* the path itself is a symbolic link *)
86 ino*: U64; (* its inode, which a rename keeps and a new file doesn't *)
87 dev*: U64; (* the file system it is on; with ino, it names the file *)
88 links*: U64; (* how many names it has: 1 for a file no hard link shares *)
89 special*: INT; (* its set-user-id, set-group-id and sticky bits, as chmod takes them: 800H, 400H, 200H *)
90 uid*: INT; (* its owner's user number *)
91 gid*: INT; (* its group's number *)
92 end;
93
94 (* What a directory says a name in it is, without asking the file:
95 a regular file, a directory, a symbolic link, or something else
96 (a device, pipe or socket); unknown where the file system
97 doesn't say, and linkInfo must be asked. *)
98 Kind* = (unknown, isFile, isDir, isLink, isOther);
99
100 (* An open directory: C's DIR. *)
101 Dir* = record
102 d: ^U8;
103 kind: Kind; (* of the name nextEntry gave last *)
104 end;
105
106 (* A program for spawn to start. *)
107 Program* = record
108 path*: []const U8;
109 args*: [][]const U8; (* the first is its name *)
110 env*: [][]const U8; (* NAME=value, each added to this environment *)
111 onlyEnv*: BOOL; (* env is its whole environment *)
112 dir*: []const U8; (* its working directory; "" for this program's *)
113 fds*: [3]INT; (* stdin, stdout, stderr; 0 for this program's *)
114 group*: INT; (* its group: 0 for this program's, -1 a new one *)
115 foreground*: BOOL; (* its group gets the terminal on standard input *)
116 tty*: INT; (* a pseudo-terminal to start a session on, or 0 *)
117 more*: []INT; (* fds above 2 passed on to it at the same numbers *)
118 keepIgnored*: BOOL; (* signals this program ignores stay ignored in it *)
119 end;
120 (* How a program that wait waited for changed. *)
121 Status* = (running, exited, killed, stopped);
122
123 (* a signal's handler; nil is SIG_DFL, 1 SIG_IGN *)
124 Handler = proc(sig: I32);
125 (* the C library's struct sigaction and sigset_t, as bytes, kept
126 aligned for the pointers in them *)
127 Sigaction = record b: [(CAbi.sigactionLen + 7) div 8]U64; end;
128 Sigset = [(CAbi.sigsetLen + 7) div 8]U64;
129
130 (* A terminal's modes, as getMode reads them and setMode sets them:
131 a struct termios, of the C library's size, 256 bytes at most. *)
132 Mode* = record
133 t: [256]U8;
134 end;
135
136 Winsize = record rows, cols, xpixel, ypixel: U16; end;
137 (* A pseudo-terminal's terminal, tty, opened and held for pty *)
138 Held = record pty, tty: INT; end;
139 Pollfd = record fd: I32; events, revents: I16; end;
140
141 (* a socket's address, struct sockaddr_storage, which holds any:
142 a struct sockaddr_un, sockaddr_in or sockaddr_in6 *)
143 Sockaddr = record b: [(CAbi.sockaddrLen + 7) div 8]U64; end;
144 (* Whom a datagram came from, as receive says and reply takes: the
145 address recvfrom fills in, and its size. *)
146 Peer* = record
147 a: Sockaddr;
148 size: INT;
149 end;
150 (* Who is at the other end of a connected socket, as peer says. *)
151 Remote* = record
152 unix*: BOOL; (* a Unix socket: uid and pid say who; no addr or port *)
153 ipv6*: BOOL; (* addr is an IPv6 address, 16 bytes; else an IPv4 one, 4 bytes then zeros *)
154 addr*: [16]U8; (* an IP peer's address *)
155 port*: INT; (* an IP peer's port *)
156 uid*, pid*: INT; (* a Unix peer's user and process, as the system recorded them when it connected *)
157 end;
158 (* struct msghdr, what sendmsg and recvmsg take, as bytes: no
159 address, one buffer, and a control message, a struct cmsghdr
160 and the fds sent, at most 16 *)
161 Msghdr = record b: [(CAbi.msghdrLen + 7) div 8]U64; end;
162 Iovec = record base: ^U8; size: INT; end;
163 Control = record b: [(CAbi.cmsgDataAt + 4 * 16 + 7) div 8]U64; end;
164 Timespec = record sec, nsec: I64; end;
165
166var
167 cwd: [4096]U8; (* what workDir gives *)
168 linked: [4096]U8; (* what readLink gives *)
169 saved: [256]U8; (* the terminal as rawMode found it: a struct termios, of the C library's size *)
170 host: [256]U8; (* what hostName gives *)
171 sigRead, sigWrite: I32; (* the pipe the handler of caught signals writes their numbers to, once open *)
172 noted: [CAbi.sigMax + 1]INT; (* 1 at sig when a signal handle took has come, until came asks *)
173 broke: INT; (* 1 when one has come since a call that ready or readyFor makes again began *)
174 (* On macOS, where the controlling side of a pseudo-terminal takes
175 no modes and no size until its terminal is opened, and reads an
176 end once it has been and is closed again, openPty opens the
177 terminal and holds it, until spawn's child takes it over or the
178 pty is closed (CAbi.ptyHeld). A pty of 0 or less is none. *)
179 held: [16]Held;
180
181(* err, minus an errno of the C library's, as minus Linux's errno of
182 the same name; err itself if it has none *)
183proc linux(err: INT): INT;
184var i: INT;
185begin
186 for i := 0 to LEN(CAbi.errnos) - 2 by 2 do
187 if -INT(CAbi.errnos[i]) = err then return -INT(CAbi.errnos[i + 1]); end;
188 end;
189 return err;
190end;
191
192(* minus errno, Linux's, as a system call returns it *)
193proc failed: INT;
194var e: ^I32;
195begin
196 e := CAbi.errno();
197 return linux(-INT(e^));
198end;
199
200(* The integer of len bytes at p + at, a field of a C struct *)
201proc field(p: ^U8; at, len: INT): I64;
202var q8: ^I64; q4: ^U32; q2: ^U16;
203begin
204 if len = 8 then q8 := ^I64(p + at); return q8^;
205 elsif len = 4 then q4 := ^U32(p + at); return I64(q4^);
206 elsif len = 2 then q2 := ^U16(p + at); return I64(q2^);
207 end;
208 return I64(p[at]);
209end;
210
211(* Writes v to the field of len bytes at p + at, its low bytes *)
212proc setField(p: ^U8; at, len: INT; v: I64);
213var q8: ^I64; q4: ^U32; q2: ^U16;
214begin
215 if len = 8 then q8 := ^I64(p + at); q8^ := v;
216 elsif len = 4 then q4 := ^U32(p + at); q4^ := U32(v & 0FFFFFFFFH);
217 elsif len = 2 then q2 := ^U16(p + at); q2^ := U16(v & 0FFFFH);
218 else p[at] := U8(v & 0FFH);
219 end;
220end;
221
222(* Whether a call that failed is to be made again: when it failed with
223 EINTR because a signal catch took broke into it, since on Linux those
224 break into nothing; not when one handle took did, which the program
225 is to see. broke is set to 0 before the call. *)
226proc again: BOOL;
227begin
228 return (failed() = -4) and (XCHG(broke, 0) = 0);
229end;
230
231(* Writes s to the file descriptor fd; the number of bytes written, or
232 minus an errno. *)
233proc write*(fd: INT; s: []const U8): INT;
234var r: INT;
235begin
236 if LEN(s) = 0 then return 0; end;
237 r := C.write(I32(fd), SYSTEM.PTR(s), UINT(LEN(s)));
238 if r < 0 then return failed(); end;
239 return r;
240end;
241
242(* Reads into buf from fd; the number of bytes read, 0 at the end, or
243 minus an errno. *)
244proc read*(fd: INT; buf: []U8): INT;
245var r: INT;
246begin
247 if LEN(buf) = 0 then return 0; end;
248 r := C.read(I32(fd), SYSTEM.ADR(buf[0]), UINT(LEN(buf)));
249 if r < 0 then return failed(); end;
250 return r;
251end;
252
253(* path, a C string in buf, or false if it doesn't fit. *)
254proc cstr(path: []const U8; buf: []U8): BOOL;
255begin
256 if LEN(path) >= LEN(buf) then return false; end;
257 COPY(buf, path);
258 buf[LEN(path)] := 0;
259 return true;
260end;
261
262(* open's flags for how, with O_CLOEXEC *)
263proc flags(how: Accesses): I32;
264var f: I32;
265begin
266 f := CAbi.oRdonly | CAbi.oCloexec;
267 if writing in how then
268 f := CAbi.oWronly;
269 if reading in how then f := CAbi.oRdwr; end;
270 end;
271 if creating in how then f := f | CAbi.oCreat; end;
272 if exclusive in how then f := f | CAbi.oExcl; end;
273 if truncating in how then f := f | CAbi.oTrunc; end;
274 if appending in how then f := f | CAbi.oAppend; end;
275 if nonblocking in how then f := f | CAbi.oNonblock; end;
276 return f;
277end;
278
279(* The file at path, opened as how asks: its file descriptor, closed in
280 a program exec starts, or minus an errno. A file it creates has the
281 permission bits mode, less those the umask takes away. *)
282proc openMode*(path: []const U8; how: Accesses; mode: INT): INT;
283var buf: [4096]U8; r: INT;
284begin
285 if executing in how then return -22; end; (* EINVAL: access asks it, open can't *)
286 if not cstr(path, buf) then return -36; end;
287 r := INT(C.open(SYSTEM.ADR(buf[0]), flags(how), mode));
288 if r < 0 then return failed(); end;
289 return r;
290end;
291
292(* openMode with 644: a file it creates is readable by all, writable
293 by its owner. *)
294proc open*(path: []const U8; how: Accesses): INT;
295begin
296 return openMode(path, how, 1A4H); (* 644 *)
297end;
298
299(* The file at path, opened for reading, closed in a program exec
300 starts. *)
301proc openRead*(path: []const U8): INT;
302begin
303 return open(path, {reading});
304end;
305
306(* The file at path, made empty or new, opened for writing, closed in a
307 program exec starts. *)
308proc create*(path: []const U8): INT;
309begin
310 return open(path, {writing, creating, truncating});
311end;
312
313(* Moves fd to pos from the start of its file, or from the end if
314 fromEnd: the new position, or minus an errno. *)
315proc seek*(fd: INT; pos: I64; fromEnd: BOOL): I64;
316var r: I64;
317begin
318 if fromEnd then r := C.lseek(I32(fd), pos, CAbi.seekEnd);
319 else r := C.lseek(I32(fd), pos, CAbi.seekSet); end;
320 if r < 0 then return failed(); end;
321 return r;
322end;
323
324(* Where in its file fd is, without moving: the next read or write's
325 position, or minus an errno. *)
326proc position*(fd: INT): I64;
327var r: I64;
328begin
329 r := C.lseek(I32(fd), 0, CAbi.seekCur);
330 if r < 0 then return failed(); end;
331 return r;
332end;
333
334(* The file fd makes size bytes long, cut or filled with zeros; its
335 position stays. 0, or minus an errno. *)
336proc truncate*(fd: INT; size: I64): INT;
337begin
338 if C.ftruncate(I32(fd), size) # 0 then return failed(); end;
339 return 0;
340end;
341
342(* Returns once what was written to fd is on the disk: 0, or minus an
343 errno. *)
344proc sync*(fd: INT): INT;
345begin
346 if C.fsync(I32(fd)) # 0 then return failed(); end;
347 return 0;
348end;
349
350(* Returns once everything written to the file system that holds fd
351 is on the disk: 0, or minus an errno. POSIX has no call for one file
352 system, so it is sync's, which flushes them all and does no less;
353 fd is still asked whether it is open, for the -9 (EBADF) Linux's
354 syncfs gives one that isn't. *)
355proc syncAll*(fd: INT): INT;
356begin
357 if C.fcntl(I32(fd), CAbi.fGetfd, 0) < 0 then return failed(); end;
358 C.sync;
359 return 0;
360end;
361
362(* Takes the lock on the open file fd, which only one program holds at
363 a time, and which goes when fd is closed or the program ends,
364 however it ends. If another program holds it, waits for it if wait,
365 and otherwise returns -11 (EAGAIN). 0, or minus an errno. *)
366proc lock*(fd: INT; wait: BOOL): INT;
367var how: I32;
368begin
369 how := CAbi.lockEx;
370 if not wait then how := how | CAbi.lockNb; end;
371 if C.flock(I32(fd), how) # 0 then return failed(); end;
372 return 0;
373end;
374
375(* Takes the lock on the open file fd as lock does, but shared: any
376 number of programs may hold it so at once, as readers do, while none
377 holds it as lock takes it. 0, or minus an errno. *)
378proc lockShared*(fd: INT; wait: BOOL): INT;
379var how: I32;
380begin
381 how := CAbi.lockSh;
382 if not wait then how := how | CAbi.lockNb; end;
383 if C.flock(I32(fd), how) # 0 then return failed(); end;
384 return 0;
385end;
386
387(* Closes the file descriptor fd. *)
388proc release(pty: INT); forward;
389
390proc close*(fd: INT);
391begin
392 if CAbi.ptyHeld = 1 then release(fd); end;
393 _ := C.close(I32(fd));
394end;
395
396(* Closes the file descriptor fd, as close does, and says whether that
397 failed: 0, or minus an errno. A file system may report only at the
398 close that what was written to the file never reached it, -28
399 (ENOSPC) or -122 (EDQUOT) say, as NFS does; a program that must know
400 its writes landed asks so. The fd is closed either way, so it is never
401 closed again, after -4 (EINTR) too. *)
402proc closeChecked*(fd: INT): INT;
403begin
404 if CAbi.ptyHeld = 1 then release(fd); end;
405 if C.close(I32(fd)) # 0 then return failed(); end;
406 return 0;
407end;
408
409(* A new file descriptor for the file fd is open on, the lowest free:
410 it, or minus an errno. *)
411proc dup*(fd: INT): INT;
412var r: I32;
413begin
414 r := C.dup(I32(fd));
415 if r < 0 then return failed(); end;
416 return INT(r);
417end;
418
419(* Makes the file descriptor into stand for the file fd is open on,
420 closing what into was first: into, or minus an errno. *)
421proc dupTo*(fd, into: INT): INT;
422var r: I32;
423begin
424 r := C.dup2(I32(fd), I32(into));
425 if r < 0 then return failed(); end;
426 return INT(r);
427end;
428
429(* A new file descriptor for the file fd is open on, the lowest free
430 from least on, and closed on exec: it, or minus an errno. A shell
431 keeps its own at 10 and above, out of the way of those a script
432 names. *)
433proc dupAbove*(fd, least: INT): INT;
434var r: I32;
435begin
436 r := C.fcntl(I32(fd), CAbi.fDupfdCloexec, I32(least));
437 if r < 0 then return failed(); end;
438 return INT(r);
439end;
440
441(* Whether fd stays open in the program exec runs in this one's place:
442 yes, or no, closed then, as the fds open, pipe and socket give are at
443 first. 0, or minus an
444 errno. *)
445proc keepOnExec*(fd: INT; yes: BOOL): INT;
446var f: I32;
447begin
448 f := C.fcntl(I32(fd), CAbi.fGetfd, 0);
449 if f < 0 then return failed(); end;
450 if yes then f := f & ~I32(CAbi.fdCloexec); else f := f | CAbi.fdCloexec; end;
451 if C.fcntl(I32(fd), CAbi.fSetfd, f) < 0 then return failed(); end;
452 return 0;
453end;
454
455(* size bytes of fresh, zeroed memory from the system, a multiple of
456 pages, or nil. *)
457proc mmap*(size: INT): ^U8;
458var p: ^U8;
459begin
460 p := C.mmap(nil, UINT(size), CAbi.protRead | CAbi.protWrite, CAbi.mapPrivate | CAbi.mapAnonymous, -1, 0);
461 if INT(p) = -1 then return nil; end;
462 return p;
463end;
464
465(* Gives back to the system the size bytes at p that mmap gave. *)
466proc munmap*(p: ^U8; size: INT);
467begin
468 _ := C.munmap(p, UINT(size));
469end;
470
471(* A file in memory, with no name, of size zeroed bytes: its fd, or
472 minus an errno. It is closed in a program exec starts. *)
473proc memFile*(size: INT): INT;
474var fd: I32; err: INT;
475begin
476 fd := CAbi.memFile();
477 if fd < 0 then return failed(); end;
478 if C.ftruncate(fd, I64(size)) # 0 then
479 err := failed(); (* before close can change errno *)
480 _ := C.close(fd);
481 return err;
482 end;
483 return INT(fd);
484end;
485
486(* The first size bytes of the file fd, mapped to be read and written,
487 and shared: what this program writes there, every program that maps
488 the file sees. nil if it can't be; munmap gives them back. *)
489proc mapFile*(fd, size: INT): ^U8;
490var p: ^U8;
491begin
492 p := C.mmap(nil, UINT(size), CAbi.protRead | CAbi.protWrite, CAbi.mapShared, I32(fd), 0);
493 if INT(p) = -1 then return nil; end;
494 return p;
495end;
496
497(* The first size bytes of the file fd, which may be open only to
498 read, mapped to be read only: writing there stops the program. nil
499 if it can't be; munmap gives them back. *)
500proc mapRead*(fd, size: INT): ^U8;
501var p: ^U8;
502begin
503 p := C.mmap(nil, UINT(size), CAbi.protRead, CAbi.mapPrivate, I32(fd), 0);
504 if INT(p) = -1 then return nil; end;
505 return p;
506end;
507
508(* Lets the pages from p, size bytes from a page boundary, be read and
509 written as read and write say; neither, and touching them stops the
510 program. 0, or minus an errno. *)
511proc protect*(p: ^U8; size: INT; read, write: BOOL): INT;
512var prot: I32;
513begin
514 prot := 0; (* PROT_NONE *)
515 if read then prot := CAbi.protRead; end;
516 if write then prot := prot | CAbi.protWrite; end;
517 if C.mprotect(p, UINT(size), prot) # 0 then return failed(); end;
518 return 0;
519end;
520
521(* Renames old to new, replacing what new names: 0, or minus an errno. *)
522proc rename*(old, new: []const U8): INT;
523var a, b: [4096]U8;
524begin
525 if not cstr(old, a) or not cstr(new, b) then return -36; end;
526 if C.rename(SYSTEM.ADR(a[0]), SYSTEM.ADR(b[0])) # 0 then return failed(); end;
527 return 0;
528end;
529
530(* Removes the file at path; not a directory. *)
531proc remove*(path: []const U8): INT;
532var a: [4096]U8;
533begin
534 if not cstr(path, a) then return -36; end;
535 if C.unlink(SYSTEM.ADR(a[0])) # 0 then return failed(); end;
536 return 0;
537end;
538
539(* Makes a directory at path, readable by all, writable by its owner. *)
540proc makeDir*(path: []const U8): INT;
541var a: [4096]U8;
542begin
543 if not cstr(path, a) then return -36; end;
544 if C.mkdir(SYSTEM.ADR(a[0]), 1EDH) # 0 then return failed(); end; (* mode 755 *)
545 return 0;
546end;
547
548(* Makes a directory at path with the permission bits mode, less those
549 the umask takes away: 1C0H (700) for one only its owner may enter. Of
550 the bits above them Linux keeps only sticky, 200H. *)
551proc makeDirMode*(path: []const U8; mode: INT): INT;
552var a: [4096]U8;
553begin
554 if not cstr(path, a) then return -36; end;
555 if C.mkdir(SYSTEM.ADR(a[0]), U32(mode)) # 0 then return failed(); end;
556 return 0;
557end;
558
559(* Removes the directory at path, which must be empty. *)
560proc removeDir*(path: []const U8): INT;
561var a: [4096]U8;
562begin
563 if not cstr(path, a) then return -36; end;
564 if C.rmdir(SYSTEM.ADR(a[0])) # 0 then return failed(); end;
565 return 0;
566end;
567
568(* Sets the permission bits of what path names. *)
569proc chmod*(path: []const U8; mode: INT): INT;
570var a: [4096]U8;
571begin
572 if not cstr(path, a) then return -36; end;
573 if C.chmod(SYSTEM.ADR(a[0]), U32(mode)) # 0 then return failed(); end;
574 return 0;
575end;
576
577(* Makes a fifo (a named pipe) at path with the permission bits mode,
578 less those the umask takes away. 0, or minus an errno. *)
579proc makeFifo*(path: []const U8; mode: INT): INT;
580var a: [4096]U8;
581begin
582 if not cstr(path, a) then return -36; end;
583 if C.mkfifo(SYSTEM.ADR(a[0]), U32(mode & 1FFH)) # 0 then return failed(); end;
584 return 0;
585end;
586
587(* Sets the owner and group of what path names, following a symbolic
588 link: a user or group number, or -1 to leave it as it is. Only
589 root may give a file away. 0, or minus an errno. *)
590proc chown*(path: []const U8; uid, gid: INT): INT;
591var a: [4096]U8;
592begin
593 if not cstr(path, a) then return -36; end;
594 if C.chown(SYSTEM.ADR(a[0]), U32(uid & 0FFFFFFFFH), U32(gid & 0FFFFFFFFH)) # 0 then return failed(); end;
595 return 0;
596end;
597
598(* Sets when the contents of what path names last changed, and when it
599 was last read, to sec seconds and nsec nanoseconds since 1970, as a
600 program copying a file keeps its time: Info.seconds gives sec back,
601 whatever the time. *)
602proc setTime*(path: []const U8; sec: I64; nsec: INT): INT;
603var a: [4096]U8; t: [2]Timespec;
604begin
605 if not cstr(path, a) then return -36; end;
606 if (nsec < 0) or (nsec >= 1000000000) then return -22; end; (* EINVAL *)
607 t[0].sec := sec;
608 t[0].nsec := nsec;
609 t[1] := t[0];
610 if C.utimensat(CAbi.atFdcwd, SYSTEM.ADR(a[0]), ^U8(SYSTEM.ADR(t)), 0) # 0 then return failed(); end;
611 return 0;
612end;
613
614(* 0 if this user, by its real ids, may do with path what how asks:
615 reading, writing and executing; minus an errno, -13 (EACCES) if not.
616 An empty how asks only whether path is there. *)
617proc access*(path: []const U8; how: Accesses): INT;
618var a: [4096]U8; m: I32;
619begin
620 if not cstr(path, a) then return -36; end;
621 m := CAbi.fOk;
622 if reading in how then m := m | CAbi.rOk; end;
623 if writing in how then m := m | CAbi.wOk; end;
624 if executing in how then m := m | CAbi.xOk; end;
625 if C.access(SYSTEM.ADR(a[0]), m) # 0 then return failed(); end;
626 return 0;
627end;
628
629(* Sets the bits taken from every file this program, and the programs
630 it starts, make: the mask it was. *)
631proc umask*(mask: INT): INT;
632begin
633 return INT(C.umask(U32(mask & 1FFH)) & 1FFH);
634end;
635
636(* Makes path a symbolic link to target. *)
637proc symlink*(target, path: []const U8): INT;
638var a, b: [4096]U8;
639begin
640 if not cstr(target, a) or not cstr(path, b) then return -36; end;
641 if C.symlink(SYSTEM.ADR(a[0]), SYSTEM.ADR(b[0])) # 0 then return failed(); end;
642 return 0;
643end;
644
645(* What the symbolic link at path names, good until the next call; and
646 0, or minus an errno. *)
647proc readLink*(path: []const U8): ([]const U8, INT);
648var a: [4096]U8; n: INT;
649begin
650 if not cstr(path, a) then return "", -36; end;
651 n := C.readlink(SYSTEM.ADR(a[0]), SYSTEM.ADR(linked[0]), UINT(LEN(linked)));
652 if n < 0 then return "", failed(); end;
653 if n = LEN(linked) then return "", -36; end; (* it may be cut short *)
654 return linked[0..n], 0;
655end;
656
657type Stat = [(CAbi.statLen + 7) div 8]U64; (* a struct stat, as bytes *)
658
659(* The type of file a struct stat says, S_IFDIR, S_IFREG or another *)
660proc fileType(st: Stat): INT;
661begin
662 return INT(field(^U8(SYSTEM.ADR(st)), CAbi.stModeAt, CAbi.stModeLen)) & CAbi.sIfmt;
663end;
664
665(* An Info from a struct stat, all but symlink. *)
666proc fromStat(st: Stat): Info;
667var i: Info; p: ^U8;
668begin
669 p := ^U8(SYSTEM.ADR(st));
670 i.size := field(p, CAbi.stSizeAt, CAbi.stSizeLen);
671 i.dev := U64(field(p, CAbi.stDevAt, CAbi.stDevLen));
672 i.ino := U64(field(p, CAbi.stInoAt, CAbi.stInoLen));
673 i.links := U64(field(p, CAbi.stNlinkAt, CAbi.stNlinkLen));
674 i.mtime := field(p, CAbi.stMtimeAt, CAbi.stMtimeLen) * 1000000000 + field(p, CAbi.stMtimeNsAt, CAbi.stMtimeNsLen);
675 i.seconds := field(p, CAbi.stMtimeAt, CAbi.stMtimeLen);
676 i.mode := INT(field(p, CAbi.stModeAt, CAbi.stModeLen)) & 1FFH;
677 i.special := INT(field(p, CAbi.stModeAt, CAbi.stModeLen)) & 0E00H;
678 i.uid := INT(field(p, CAbi.stUidAt, CAbi.stUidLen));
679 i.gid := INT(field(p, CAbi.stGidAt, CAbi.stGidLen));
680 i.dir := fileType(st) = CAbi.sIfdir;
681 i.file := fileType(st) = CAbi.sIfreg;
682 return i;
683end;
684
685(* The size of what path names, whether it is a directory or a regular
686 file, following a symbolic link, and whether path is one; and 0, or
687 minus an errno. *)
688proc info*(path: []const U8): (Info, INT);
689var a: [4096]U8; st: Stat; i: Info; isLink: BOOL;
690begin
691 if not cstr(path, a) then return i, -36; end;
692 if C.lstat(SYSTEM.ADR(a[0]), ^U8(SYSTEM.ADR(st))) # 0 then return i, failed(); end;
693 isLink := fileType(st) = CAbi.sIflnk;
694 if C.stat(SYSTEM.ADR(a[0]), ^U8(SYSTEM.ADR(st))) # 0 then return i, failed(); end;
695 i := fromStat(st);
696 i.symlink := isLink;
697 return i, 0;
698end;
699
700(* info of path itself: if it is a symbolic link, of the link, not of
701 what it names, so that symlink is true, dir and file false, and the
702 size the length of what it names. *)
703proc linkInfo*(path: []const U8): (Info, INT);
704var a: [4096]U8; st: Stat; i: Info;
705begin
706 if not cstr(path, a) then return i, -36; end;
707 if C.lstat(SYSTEM.ADR(a[0]), ^U8(SYSTEM.ADR(st))) # 0 then return i, failed(); end;
708 i := fromStat(st);
709 i.symlink := fileType(st) = CAbi.sIflnk;
710 return i, 0;
711end;
712
713(* info of the file open on fd, which is never a link. *)
714proc infoOf*(fd: INT): (Info, INT);
715var st: Stat; i: Info;
716begin
717 if C.fstat(I32(fd), ^U8(SYSTEM.ADR(st))) # 0 then return i, failed(); end;
718 return fromStat(st), 0;
719end;
720
721(* The bytes free to an ordinary user on path's file system, and the
722 bytes in all. *)
723proc space*(path: []const U8): (I64, I64, INT);
724var a: [4096]U8; st: [(CAbi.statvfsLen + 7) div 8]U64; p: ^U8; unit: I64;
725begin
726 if not cstr(path, a) then return 0, 0, -36; end;
727 p := ^U8(SYSTEM.ADR(st));
728 if C.statvfs(SYSTEM.ADR(a[0]), p) # 0 then return 0, 0, failed(); end;
729 unit := field(p, CAbi.fFrsizeAt, CAbi.fFrsizeLen);
730 return field(p, CAbi.fBavailAt, CAbi.fBavailLen) * unit, field(p, CAbi.fBlocksAt, CAbi.fBlocksLen) * unit, 0;
731end;
732
733(* The Kind of a d_type, as readdir gives it: DT_REG, DT_DIR, DT_LNK,
734 DT_UNKNOWN, and the rest (pipes, devices, sockets) other things. *)
735proc kindOf(t: U8): Kind;
736begin
737 if t = CAbi.dtReg then return isFile;
738 elsif t = CAbi.dtDir then return isDir;
739 elsif t = CAbi.dtLnk then return isLink;
740 elsif t = CAbi.dtUnknown then return unknown;
741 end;
742 return isOther;
743end;
744
745(* Opens the directory at path, for nextEntry. *)
746proc openDir*(var d: Dir; path: []const U8): INT;
747var a: [4096]U8;
748begin
749 d.kind := unknown;
750 if not cstr(path, a) then return -36; end;
751 d.d := C.opendir(SYSTEM.ADR(a[0]));
752 if d.d = nil then return failed(); end;
753 return 0;
754end;
755
756(* The next name in the directory, good until the next call, but . and
757 .., in no order; false at the end. *)
758proc nextEntry*(var d: Dir): ([]const U8, BOOL);
759var e: ^U8; n: INT;
760begin
761 while true do
762 e := C.readdir(d.d);
763 if e = nil then return "", false; end;
764 d.kind := kindOf(e[CAbi.dTypeAt]);
765 e := e + CAbi.dNameAt;
766 n := 0;
767 while e[n] # 0 do INC(n); end;
768 if (e[0..n] # ".") and (e[0..n] # "..") then return e[0..n], true; end;
769 end;
770 return "", false;
771end;
772
773(* What the name nextEntry gave last is, as the directory says, so that
774 a walk needn't ask each file with linkInfo; unknown where the file
775 system doesn't say. A link is isLink, whatever it names. *)
776proc entryKind*(const d: Dir): Kind;
777begin
778 return d.kind;
779end;
780
781(* Closes the directory d that openDir opened. *)
782proc closeDir*(var d: Dir);
783begin
784 _ := C.closedir(d.d);
785end;
786
787(* Puts the terminal on fd into raw mode, as cfmakeraw makes it: no
788 echo, no lines, no signals, no flow control, no CR to NL, no NL to
789 CR NL; false if fd isn't a terminal. *)
790proc rawMode*(fd: INT): BOOL;
791var t: [256]U8;
792begin
793 if C.tcgetattr(I32(fd), SYSTEM.ADR(saved[0])) # 0 then return false; end;
794 t := saved;
795 C.cfmakeraw(SYSTEM.ADR(t[0]));
796 return C.tcsetattr(I32(fd), CAbi.tcsanow, SYSTEM.ADR(t[0])) = 0;
797end;
798
799(* The terminal on fd as rawMode found it. *)
800proc restoreMode*(fd: INT);
801begin
802 _ := C.tcsetattr(I32(fd), CAbi.tcsanow, SYSTEM.ADR(saved[0]));
803end;
804
805(* The modes of the terminal on fd, as a shell keeps them for each job;
806 and 0, or minus an errno, -25 (ENOTTY) if it isn't a terminal. *)
807proc getMode*(fd: INT): (Mode, INT);
808var m: Mode;
809begin
810 if C.tcgetattr(I32(fd), SYSTEM.ADR(m.t[0])) # 0 then return m, failed(); end;
811 return m, 0;
812end;
813
814(* Gives the terminal on fd the modes m, once what was written to it
815 is sent: 0, or minus an errno. *)
816proc setMode*(fd: INT; m: Mode): INT;
817begin
818 if C.tcsetattr(I32(fd), CAbi.tcsadrain, SYSTEM.ADR(m.t[0])) # 0 then return failed(); end;
819 return 0;
820end;
821
822(* The columns and rows of the terminal on fd; 80 by 24 if it doesn't
823 say. *)
824proc termSize*(fd: INT): (INT, INT);
825var w: Winsize;
826begin
827 if (C.ioctl(I32(fd), CAbi.tiocgwinsz, SYSTEM.ADR(w)) # 0) or (w.cols = 0) or (w.rows = 0) then
828 return 80, 24;
829 end;
830 return INT(w.cols), INT(w.rows);
831end;
832
833(* Whether fd has something to read within ms milliseconds; ms < 0
834 waits as long as it takes. *)
835proc ready*(fd, ms: INT): BOOL;
836var p: Pollfd; r: I32;
837begin
838 p := {fd: I32(fd), events: CAbi.pollin};
839 _ := XCHG(broke, 0);
840 repeat r := C.poll(^U8(SYSTEM.ADR(p)), 1, I32(ms)); until (r >= 0) or not again();
841 return r > 0;
842end;
843
844(* The time on clock, in nanoseconds. *)
845proc time(clock: I32): I64;
846var t: Timespec;
847begin
848 _ := C.clock_gettime(clock, ^U8(SYSTEM.ADR(t)));
849 return t.sec * 1000000000 + t.nsec;
850end;
851
852(* The clock that only goes forward, in nanoseconds: for how long
853 something takes. *)
854proc clock*: I64;
855begin
856 return time(CAbi.clockMonotonic);
857end;
858
859(* The time in nanoseconds since 1970-01-01, UTC. *)
860proc now*: I64;
861begin
862 return time(CAbi.clockRealtime);
863end;
864
865(* Waits ms milliseconds. *)
866proc sleep*(ms: INT);
867var t: Timespec; at: I64;
868begin
869 at := clock() + I64(ms) * 1000000;
870 t := {sec: at div 1000000000, nsec: at mod 1000000000};
871 CAbi.sleepUntil(^U8(SYSTEM.ADR(t)));
872end;
873
874(* Ends the program: random bytes can't be faked. *)
875proc noRandom;
876begin
877 _ := write(stderr, "Sys.random: the kernel gave no random bytes\n");
878 C._exit(2);
879end;
880
881(* Fills b with random bytes, from the kernel. Random bytes can't be
882 faked, so if the kernel can't give them (no getrandom, or a filter
883 refusing it) it says so on standard error and ends the program by
884 exit with status 2. *)
885proc random*(b: []U8);
886var n, r: INT;
887begin
888 n := 0;
889 while n < LEN(b) do (* a signal may cut it short *)
890 r := CAbi.random(SYSTEM.ADR(b[n]), UINT(LEN(b) - n));
891 if r > 0 then INC(n, r);
892 elsif (r >= 0) or (failed() # errIntr) then noRandom(); (* r = 0 can't be, and is no progress *)
893 end;
894 end;
895end;
896
897(* A socket of family and kind, connected to the address at a, of size
898 bytes, or, if serving, bound to it and taking connections: its file
899 descriptor, or minus an errno. It is closed in a program exec
900 starts. *)
901proc socket(family, kind: INT; a: ^U8; size: INT; serving: BOOL): INT;
902var fd, r, one: I32; err: INT;
903begin
904 fd := C.socket(I32(family), I32(kind) | CAbi.sockCloexec, 0);
905 if fd < 0 then return failed(); end;
906 if CAbi.sockCloexec = 0 then _ := keepOnExec(INT(fd), false); end;
907 if serving then
908 one := 1; (* so that a server can start again at once *)
909 _ := C.setsockopt(fd, CAbi.solSocket, CAbi.soReuseaddr, ^U8(SYSTEM.ADR(one)), 4);
910 r := C.bind(fd, a, U32(size));
911 if (r = 0) and (kind = CAbi.sockStream) then (* a stream socket takes connections; *)
912 r := C.listen(fd, 4096); (* one of datagrams only receives *)
913 end;
914 else
915 r := C.connect(fd, a, U32(size));
916 end;
917 if r # 0 then
918 err := failed(); (* before close can change errno *)
919 _ := C.close(fd);
920 return err;
921 end;
922 return INT(fd);
923end;
924
925(* Gives the address at p the family, and, on a system whose addresses
926 start with their length, size *)
927proc setFamily(p: ^U8; family, size: INT);
928begin
929 setField(p, CAbi.saFamilyAt, CAbi.saFamilyLen, family);
930 if CAbi.saLenAt >= 0 then p[CAbi.saLenAt] := U8(size); end;
931end;
932
933(* The family of the address at p *)
934proc familyOf(p: ^U8): INT;
935begin
936 return INT(field(p, CAbi.saFamilyAt, CAbi.saFamilyLen));
937end;
938
939(* path as a Unix socket's address in a, and the address's length, or
940 -36 (ENAMETOOLONG) if it is too long. A path that starts with a zero
941 byte is one of Linux's abstract names, which has no file and no
942 trailing zero: its length ends with the name's; on a system that has
943 none, -22 (EINVAL). *)
944proc unixAddr(path: []const U8; a: ^Sockaddr): INT;
945var p: ^U8;
946begin
947 if LEN(path) >= CAbi.sunPathLen then return -36; end;
948 if (LEN(path) > 0) and (path[0] = 0) and (CAbi.unixAbstract = 0) then return -22; end;
949 p := ^U8(a);
950 setFamily(p, CAbi.afUnix, CAbi.sockaddrUnLen);
951 COPY(p[CAbi.sunPathAt..CAbi.sunPathAt + LEN(path)], path);
952 if (LEN(path) > 0) and (path[0] = 0) then return CAbi.sunPathAt + LEN(path); end;
953 return CAbi.sockaddrUnLen;
954end;
955
956(* A stream socket connected to the Unix socket at path. *)
957proc connect*(path: []const U8): INT;
958var a: Sockaddr; size: INT;
959begin
960 size := unixAddr(path, SYSTEM.ADR(a));
961 if size < 0 then return size; end;
962 return socket(CAbi.afUnix, CAbi.sockStream, ^U8(SYSTEM.ADR(a)), size, false);
963end;
964
965(* A stream socket made at path, which must not be there yet, taking
966 connections. *)
967proc listen*(path: []const U8): INT;
968var a: Sockaddr; size: INT;
969begin
970 size := unixAddr(path, SYSTEM.ADR(a));
971 if size < 0 then return size; end;
972 return socket(CAbi.afUnix, CAbi.sockStream, ^U8(SYSTEM.ADR(a)), size, true);
973end;
974
975(* addr, an IPv4 or IPv6 address as numbers, and port, in a: the size
976 of its struct sockaddr_in or sockaddr_in6, or 0 if either is
977 wrong. *)
978proc inetAddr(addr: []const U8; port: INT; a: ^Sockaddr): INT;
979var s: [64]U8; b: [16]U8; p: ^U8; at, size: INT;
980begin
981 if (port < 0) or (port > 65535) or not cstr(addr, s) then return 0; end;
982 p := ^U8(a);
983 (* into b first, since musl's inet_pton leaves what it read of an
984 address it refuses, and the rest of the address is to be zero *)
985 if C.inet_pton(CAbi.afInet, SYSTEM.ADR(s[0]), SYSTEM.ADR(b[0])) = 1 then
986 size := CAbi.sockaddrInLen;
987 setFamily(p, CAbi.afInet, size);
988 COPY(p[CAbi.sinAddrAt..CAbi.sinAddrAt + 4], b[0..4]);
989 at := CAbi.sinPortAt;
990 elsif C.inet_pton(CAbi.afInet6, SYSTEM.ADR(s[0]), SYSTEM.ADR(b[0])) = 1 then
991 size := CAbi.sockaddrIn6Len;
992 setFamily(p, CAbi.afInet6, size);
993 COPY(p[CAbi.sin6AddrAt..CAbi.sin6AddrAt + 16], b);
994 at := CAbi.sin6PortAt;
995 else
996 return 0;
997 end;
998 p[at] := U8(port shr 8); (* in the network's order, the high byte first *)
999 p[at + 1] := U8(port & 255);
1000 return size;
1001end;
1002
1003(* The port in the IPv4 or IPv6 address at p *)
1004proc portOf(p: ^U8): INT;
1005var at: INT;
1006begin
1007 at := CAbi.sinPortAt;
1008 if familyOf(p) = CAbi.afInet6 then at := CAbi.sin6PortAt; end;
1009 return (INT(p[at]) shl 8) | INT(p[at + 1]);
1010end;
1011
1012(* A socket of kind at addr and port, as socket makes it; -22 (EINVAL)
1013 if they are wrong. *)
1014proc inet(addr: []const U8; port, kind: INT; serving: BOOL): INT;
1015var a: Sockaddr; size: INT;
1016begin
1017 size := inetAddr(addr, port, SYSTEM.ADR(a));
1018 if size = 0 then return -22; end;
1019 return socket(familyOf(^U8(SYSTEM.ADR(a))), kind, ^U8(SYSTEM.ADR(a)), size, serving);
1020end;
1021
1022(* A stream socket connected to port at addr, an IPv4 or IPv6 address
1023 as numbers. *)
1024proc connectTcp*(addr: []const U8; port: INT): INT;
1025begin
1026 return inet(addr, port, CAbi.sockStream, false);
1027end;
1028
1029(* A socket of datagrams to and from port at addr. *)
1030proc connectUdp*(addr: []const U8; port: INT): INT;
1031begin
1032 return inet(addr, port, CAbi.sockDgram, false);
1033end;
1034
1035(* A stream socket taking connections on port at addr; "0.0.0.0" or
1036 "::" is every address the machine has. *)
1037proc listenTcp*(addr: []const U8; port: INT): INT;
1038begin
1039 return inet(addr, port, CAbi.sockStream, true);
1040end;
1041
1042(* A socket of datagrams on port at addr, from anyone, for receive and
1043 reply. *)
1044proc listenUdp*(addr: []const U8; port: INT): INT;
1045begin
1046 return inet(addr, port, CAbi.sockDgram, true);
1047end;
1048
1049(* The next connection to the socket fd, waiting for one: a socket of
1050 its own, closed in a program exec starts; or minus an errno. *)
1051proc accept*(fd: INT): INT;
1052var r: I32;
1053begin
1054 r := CAbi.accepted(I32(fd));
1055 if r < 0 then return failed(); end;
1056 return INT(r);
1057end;
1058
1059(* Ends this side's writing to the socket fd, so that the other end
1060 reads an end of input and can still answer on it. 0, or minus an
1061 errno. *)
1062proc closeWrite*(fd: INT): INT;
1063begin
1064 if C.shutdown(I32(fd), CAbi.shutWr) # 0 then return failed(); end;
1065 return 0;
1066end;
1067
1068(* Who is at the other end of the connected socket fd, and 0; or minus
1069 an errno. *)
1070proc peer*(fd: INT): (Remote, INT);
1071var r: Remote; a: Sockaddr; size: U32; p: ^U8;
1072begin
1073 r := {unix: false, ipv6: false};
1074 size := U32(SIZE(Sockaddr));
1075 p := ^U8(SYSTEM.ADR(a));
1076 if C.getpeername(I32(fd), p, SYSTEM.ADR(size)) # 0 then return r, failed(); end;
1077 if familyOf(p) = CAbi.afUnix then (* ask who made the connection *)
1078 if CAbi.peer(I32(fd), r.pid, r.uid) # 0 then return r, failed(); end;
1079 r.unix := true;
1080 else
1081 r.port := portOf(p);
1082 if familyOf(p) = CAbi.afInet6 then
1083 r.ipv6 := true;
1084 COPY(r.addr[0..16], p[CAbi.sin6AddrAt..CAbi.sin6AddrAt + 16]);
1085 else
1086 COPY(r.addr[0..4], p[CAbi.sinAddrAt..CAbi.sinAddrAt + 4]);
1087 end;
1088 end;
1089 return r, 0;
1090end;
1091
1092(* Two connected stream sockets, as a Unix socket and the one that
1093 connects to it make: their fds and 0, closed in a program exec
1094 starts; or -1, -1 and minus an errno. *)
1095proc socketPair*: (INT, INT, INT);
1096var fds: [2]I32;
1097begin
1098 if C.socketpair(CAbi.afUnix, CAbi.sockStream | CAbi.sockCloexec, 0, SYSTEM.ADR(fds[0])) # 0 then
1099 return -1, -1, failed();
1100 end;
1101 if CAbi.sockCloexec = 0 then
1102 _ := keepOnExec(INT(fds[0]), false);
1103 _ := keepOnExec(INT(fds[1]), false);
1104 end;
1105 return INT(fds[0]), INT(fds[1]), 0;
1106end;
1107
1108(* Writes s to the socket fd, as write does, but returns -32 (EPIPE)
1109 where write would stop the program with SIGPIPE: when the other end
1110 has closed it. *)
1111proc send*(fd: INT; s: []const U8): INT;
1112var r: INT;
1113begin
1114 if LEN(s) = 0 then return 0; end;
1115 r := C.send(I32(fd), SYSTEM.PTR(s), UINT(LEN(s)), CAbi.msgNosignal);
1116 if r < 0 then return failed(); end;
1117 return r;
1118end;
1119
1120(* send, but never waits: returns -11 (EAGAIN) where send would wait for
1121 room, and doesn't make reads on fd non-blocking too. *)
1122proc sendNow*(fd: INT; s: []const U8): INT;
1123var r: INT;
1124begin
1125 if LEN(s) = 0 then return 0; end;
1126 r := CAbi.sendNow(I32(fd), SYSTEM.PTR(s), UINT(LEN(s)));
1127 if r < 0 then return failed(); end;
1128 return r;
1129end;
1130
1131(* Waits up to ms milliseconds (ms < 0: as long as it takes) until one
1132 of fds may be read or written as each one's read and write say, and
1133 sets each one's ready. The number ready, 0 on a timeout, or minus an
1134 errno. It takes as many as it is given: the system's list is built
1135 on the stack for 64 or fewer, else in memory from mmap, given back
1136 before it returns (-12 if there is none). A signal that a catch took
1137 doesn't end the wait; one that handle took does, with -4. *)
1138proc poll*(var fds: []Poll; ms: INT): INT;
1139var small: [64]Pollfd; list: []Pollfd; big: ^Pollfd; n, i, r, e: INT; events: I16;
1140begin
1141 n := LEN(fds);
1142 big := nil;
1143 if n <= LEN(small) then
1144 list := small[0..n];
1145 else
1146 big := ^Pollfd(mmap(n * SIZE(Pollfd)));
1147 if big = nil then return -12; end; (* ENOMEM *)
1148 list := big[0..n];
1149 end;
1150 for i := 0 to n - 1 do
1151 events := 0;
1152 if fds[i].read then events := CAbi.pollin; end;
1153 if fds[i].write then events := events | CAbi.pollout; end;
1154 list[i] := {fd: I32(fds[i].fd), events: events};
1155 end;
1156 _ := XCHG(broke, 0);
1157 repeat r := INT(C.poll(^U8(SYSTEM.PTR(list)), UINT(n), I32(ms))); until (r >= 0) or not again();
1158 e := 0;
1159 if r < 0 then e := failed(); end;
1160 for i := 0 to n - 1 do
1161 fds[i].ready := (r > 0) and (list[i].revents # 0);
1162 end;
1163 if big # nil then munmap(^U8(big), n * SIZE(Pollfd)); end;
1164 if r < 0 then return e; end;
1165 return r;
1166end;
1167
1168(* The first of reads that has something to read within ms
1169 milliseconds, or of writes that has room to write, or that has
1170 reached its end or failed, so that a read or a write won't wait; -1
1171 if none has. ms < 0 waits as long as it takes. At most 64 fds in
1172 all. *)
1173proc readyFor*(reads, writes: []const INT; ms: INT): INT;
1174var p: [64]Poll; ps: []Poll; n, i: INT;
1175begin
1176 n := 0;
1177 for i := 0 to LEN(reads) - 1 do
1178 if n < LEN(p) then
1179 p[n] := {fd: reads[i], read: true};
1180 INC(n);
1181 end;
1182 end;
1183 for i := 0 to LEN(writes) - 1 do
1184 if n < LEN(p) then
1185 p[n] := {fd: writes[i], write: true};
1186 INC(n);
1187 end;
1188 end;
1189 ps := p[0..n];
1190 if poll(ps, ms) <= 0 then return -1; end;
1191 for i := 0 to n - 1 do
1192 if p[i].ready then return p[i].fd; end;
1193 end;
1194 return -1;
1195end;
1196
1197(* The first of fds that has something to read within ms milliseconds,
1198 or that has reached its end or failed, so that a read won't wait; -1
1199 if none has. ms < 0 waits as long as it takes. At most 64 fds. *)
1200proc readyOf*(fds: []const INT; ms: INT): INT;
1201begin
1202 return readyFor(fds, [], ms);
1203end;
1204
1205(* Reads and writes on fd made to wait, as they do at first; or, if not
1206 yes, to return -11 (EAGAIN) at once where they would wait. 0, or
1207 minus an errno. *)
1208proc setBlocking*(fd: INT; yes: BOOL): INT;
1209var flags: I32;
1210begin
1211 flags := C.fcntl(I32(fd), CAbi.fGetfl, 0);
1212 if flags < 0 then return failed(); end;
1213 if yes then flags := flags & ~I32(CAbi.oNonblock); else flags := flags | CAbi.oNonblock; end;
1214 if C.fcntl(I32(fd), CAbi.fSetfl, flags) < 0 then return failed(); end;
1215 return 0;
1216end;
1217
1218(* Whether reads and writes on fd wait, as they do at first: 1 if they
1219 do, 0 if they return -11 (EAGAIN) at once, or minus an errno. *)
1220proc blocking*(fd: INT): INT;
1221var flags: I32;
1222begin
1223 flags := C.fcntl(I32(fd), CAbi.fGetfl, 0);
1224 if flags < 0 then return failed(); end;
1225 if flags & CAbi.oNonblock # 0 then return 0; end;
1226 return 1;
1227end;
1228
1229(* A stream socket connected to port at addr, as connectTcp makes it,
1230 or -110 (ETIMEDOUT) if it isn't connected within ms milliseconds.
1231 It starts to connect without waiting, then waits for the socket to
1232 be writable, which it is once connected or refused, and asks which. *)
1233proc connectTcpWithin*(addr: []const U8; port, ms: INT): INT;
1234var a: Sockaddr; size, r: INT; fd, err: I32; errSize: U32;
1235begin
1236 size := inetAddr(addr, port, SYSTEM.ADR(a));
1237 if size = 0 then return -22; end;
1238 fd := C.socket(I32(familyOf(^U8(SYSTEM.ADR(a)))), CAbi.sockStream | CAbi.sockCloexec | CAbi.sockNonblock, 0);
1239 if fd < 0 then return failed(); end;
1240 if CAbi.sockCloexec = 0 then _ := keepOnExec(INT(fd), false); end;
1241 if CAbi.sockNonblock = 0 then _ := setBlocking(INT(fd), false); end;
1242 r := 0;
1243 if C.connect(fd, ^U8(SYSTEM.ADR(a)), U32(size)) # 0 then r := failed(); end;
1244 if r = -115 then (* EINPROGRESS *)
1245 r := -110;
1246 if readyFor([], [INT(fd)], ms) = INT(fd) then
1247 errSize := 4;
1248 if C.getsockopt(fd, CAbi.solSocket, CAbi.soError, ^U8(SYSTEM.ADR(err)), SYSTEM.ADR(errSize)) = 0 then
1249 r := linux(-INT(err));
1250 else
1251 r := failed();
1252 end;
1253 end;
1254 end;
1255 if r = 0 then r := setBlocking(INT(fd), true); end;
1256 if r < 0 then _ := C.close(fd); return r; end;
1257 return INT(fd);
1258end;
1259
1260(* The port the socket fd is bound to, or minus an errno: for a socket
1261 made on port 0, the one the system chose. *)
1262proc localPort*(fd: INT): INT;
1263var a: Sockaddr; size: U32;
1264begin
1265 size := U32(SIZE(Sockaddr));
1266 if C.getsockname(I32(fd), ^U8(SYSTEM.ADR(a)), SYSTEM.ADR(size)) # 0 then return failed(); end;
1267 return portOf(^U8(SYSTEM.ADR(a)));
1268end;
1269
1270(* The next datagram to the socket fd, waiting for one: its first
1271 LEN(buf) bytes in buf, the rest lost, and who sent it. The number is
1272 the bytes in buf, or minus an errno. *)
1273proc receive*(fd: INT; buf: []U8): (INT, Peer);
1274var p: Peer; size: U32; n: INT;
1275begin
1276 size := U32(SIZE(Sockaddr));
1277 n := C.recvfrom(I32(fd), SYSTEM.PTR(buf), UINT(LEN(buf)), 0, ^U8(SYSTEM.ADR(p.a)), SYSTEM.ADR(size));
1278 if n < 0 then n := failed(); end;
1279 p.size := INT(size);
1280 return n, p;
1281end;
1282
1283(* Sends s, as one datagram, from the socket fd to peer, as receive
1284 gave it: the bytes sent, or minus an errno. *)
1285proc reply*(fd: INT; peer: Peer; s: []const U8): INT;
1286var r: INT;
1287begin
1288 r := C.sendto(I32(fd), SYSTEM.PTR(s), UINT(LEN(s)), CAbi.msgNosignal, ^U8(SYSTEM.ADR(peer.a)), U32(peer.size));
1289 if r < 0 then return failed(); end;
1290 return r;
1291end;
1292
1293(* Sends s, at least one byte, to the Unix socket fd, as send does, and
1294 with it the files fds, at most 16, which the program that receives
1295 them then has open too: the bytes sent, or minus an errno. *)
1296proc sendFds*(fd: INT; s: []const U8; fds: []const INT): INT;
1297var m: Msghdr; v: Iovec; c: Control; mp, cp: ^U8; sent: ^I32; i, r, size: INT;
1298begin
1299 if (LEN(s) = 0) or (LEN(fds) > 16) then return -22; end;
1300 v := {base: SYSTEM.PTR(s), size: LEN(s)};
1301 mp := ^U8(SYSTEM.ADR(m));
1302 setField(mp, CAbi.msgIovAt, SIZE(^U8), INT(SYSTEM.ADR(v)));
1303 setField(mp, CAbi.msgIovlenAt, CAbi.msgIovlenLen, 1);
1304 if LEN(fds) > 0 then
1305 (* a struct cmsghdr, its level and type ints, then the fds *)
1306 cp := ^U8(SYSTEM.ADR(c));
1307 size := CAbi.cmsgDataAt + 4 * LEN(fds);
1308 setField(cp, CAbi.cmsgLenAt, CAbi.cmsgLenLen, size);
1309 setField(cp, CAbi.cmsgLevelAt, 4, CAbi.solSocket);
1310 setField(cp, CAbi.cmsgTypeAt, 4, CAbi.scmRights);
1311 sent := ^I32(cp + CAbi.cmsgDataAt);
1312 for i := 0 to LEN(fds) - 1 do sent[i] := I32(fds[i]); end;
1313 setField(mp, CAbi.msgControlAt, SIZE(^U8), INT(cp));
1314 (* CMSG_SPACE: rounded up to the C library's alignment *)
1315 setField(mp, CAbi.msgControllenAt, CAbi.msgControllenLen, (size + CAbi.cmsgAlign - 1) & ~(CAbi.cmsgAlign - 1));
1316 end;
1317 r := C.sendmsg(I32(fd), mp, CAbi.msgNosignal);
1318 if r < 0 then return failed(); end;
1319 return r;
1320end;
1321
1322(* Reads into buf from the Unix socket fd, as read does, and puts the
1323 files sent with what it read in fds, as many as fit, closing the
1324 rest: the bytes read, or minus an errno, and the files put in fds.
1325 Each is closed in a program exec starts. *)
1326proc receiveFds*(fd: INT; buf: []U8; fds: []INT): (INT, INT);
1327var m: Msghdr; v: Iovec; c: Control; mp, cp: ^U8; got: ^I32; n, k, i, size: INT;
1328begin
1329 v := {base: SYSTEM.PTR(buf), size: LEN(buf)};
1330 mp := ^U8(SYSTEM.ADR(m));
1331 cp := ^U8(SYSTEM.ADR(c));
1332 setField(mp, CAbi.msgIovAt, SIZE(^U8), INT(SYSTEM.ADR(v)));
1333 setField(mp, CAbi.msgIovlenAt, CAbi.msgIovlenLen, 1);
1334 setField(mp, CAbi.msgControlAt, SIZE(^U8), INT(cp));
1335 setField(mp, CAbi.msgControllenAt, CAbi.msgControllenLen, SIZE(Control));
1336 n := C.recvmsg(I32(fd), mp, CAbi.msgCmsgCloexec);
1337 if n < 0 then return failed(), 0; end;
1338 k := 0;
1339 if (field(mp, CAbi.msgControllenAt, CAbi.msgControllenLen) >= CAbi.cmsgDataAt)
1340 and (field(cp, CAbi.cmsgLevelAt, 4) = CAbi.solSocket) and (field(cp, CAbi.cmsgTypeAt, 4) = CAbi.scmRights) then
1341 size := INT(field(cp, CAbi.cmsgLenAt, CAbi.cmsgLenLen));
1342 got := ^I32(cp + CAbi.cmsgDataAt);
1343 for i := 0 to (size - CAbi.cmsgDataAt) div 4 - 1 do
1344 if k < LEN(fds) then
1345 fds[k] := INT(got[i]);
1346 if CAbi.msgCmsgCloexec = 0 then _ := keepOnExec(fds[k], false); end;
1347 INC(k);
1348 else
1349 _ := C.close(got[i]);
1350 end;
1351 end;
1352 end;
1353 return n, k;
1354end;
1355
1356(* What errno err, or minus it, means, as the C library's strerror
1357 says it. *)
1358proc errorText*(err: INT): []const U8;
1359var s: ^U8; n, i: INT;
1360begin
1361 if err < 0 then err := -err; end;
1362 if (err < 0) or (err > 7FFFFFFFH) then return "unknown error"; end; (* the smallest INT, or past an int *)
1363 for i := 0 to LEN(CAbi.errnos) - 2 by 2 do (* Linux's errno as the C library's *)
1364 if INT(CAbi.errnos[i + 1]) = err then err := INT(CAbi.errnos[i]); break; end;
1365 end;
1366 s := C.strerror(I32(err));
1367 if s = nil then return "unknown error"; end;
1368 n := 0;
1369 while s[n] # 0 do INC(n); end;
1370 return s[0..n];
1371end;
1372
1373(* The value of the environment variable name and true, or "" and
1374 false if it isn't set: "" and true if it is set to nothing. *)
1375proc findEnv*(name: []const U8): ([]const U8, BOOL);
1376var a: [4096]U8; s: ^U8; n: INT;
1377begin
1378 if not cstr(name, a) then return "", false; end;
1379 s := C.getenv(SYSTEM.ADR(a[0]));
1380 if s = nil then return "", false; end;
1381 n := 0;
1382 while s[n] # 0 do INC(n); end;
1383 return s[0..n], true;
1384end;
1385
1386(* The value of the environment variable name; "" if it isn't set. *)
1387proc env*(name: []const U8): []const U8;
1388var v: []const U8;
1389begin
1390 v, _ := findEnv(name);
1391 return v;
1392end;
1393
1394(* The environment's ith NAME=value, from 0, and true; "" and false
1395 past the last. *)
1396proc envAt*(i: INT): ([]const U8, BOOL);
1397var e: ^^U8; s: ^U8; j, n: INT;
1398begin
1399 if i < 0 then return "", false; end;
1400 e := C.environ;
1401 for j := 0 to i do
1402 if e[j] = nil then return "", false; end;
1403 end;
1404 s := e[i];
1405 n := 0;
1406 while s[n] # 0 do INC(n); end;
1407 return s[0..n], true;
1408end;
1409
1410(* The working directory, good until the next call; and 0, or minus an
1411 errno. *)
1412proc workDir*: ([]const U8, INT);
1413var n: INT;
1414begin
1415 if C.getcwd(SYSTEM.ADR(cwd[0]), LEN(cwd)) = nil then return "", failed(); end;
1416 n := 0;
1417 while cwd[n] # 0 do INC(n); end;
1418 return cwd[0..n], 0;
1419end;
1420
1421(* Makes path the working directory. *)
1422proc setWorkDir*(path: []const U8): INT;
1423var a: [4096]U8;
1424begin
1425 if not cstr(path, a) then return -36; end;
1426 if C.chdir(SYSTEM.ADR(a[0])) # 0 then return failed(); end;
1427 return 0;
1428end;
1429
1430proc ptyName(fd: INT; name: []U8): INT; forward;
1431
1432(* A pseudo-terminal: the file descriptor of its controlling side, or
1433 minus an errno. Its other side, the terminal its programs run on, is
1434 unlocked, for spawn to open. *)
1435proc openPty*: INT;
1436var fd, t: I32; err, i, k: INT; name: [256]U8;
1437begin
1438 fd := C.posix_openpt(CAbi.oRdwr | CAbi.oNoctty);
1439 if fd < 0 then return failed(); end;
1440 if (C.grantpt(fd) # 0) or (C.unlockpt(fd) # 0) then
1441 err := failed();
1442 _ := C.close(fd);
1443 return err;
1444 end;
1445 if CAbi.ptyHeld = 1 then (* macOS: its terminal held (held) *)
1446 release(INT(fd)); (* one an fd closed since had *)
1447 k := -1;
1448 for i := 0 to LEN(held) - 1 do
1449 if (held[i].pty <= 0) and (k < 0) then k := i; end;
1450 end;
1451 err := -24; (* EMFILE: none free *)
1452 if k >= 0 then err := ptyName(INT(fd), name); end;
1453 if err = 0 then
1454 t := C.open(SYSTEM.ADR(name[0]), CAbi.oRdwr | CAbi.oNoctty | CAbi.oCloexec);
1455 if t < 0 then err := failed(); else held[k] := {pty: INT(fd), tty: INT(t)}; end;
1456 end;
1457 if err # 0 then _ := C.close(fd); return err; end;
1458 end;
1459 return INT(fd);
1460end;
1461
1462(* The terminal openPty holds for pty, or -1 *)
1463proc heldTty(pty: INT): INT;
1464var i: INT;
1465begin
1466 for i := 0 to LEN(held) - 1 do
1467 if held[i].pty = pty then return held[i].tty; end;
1468 end;
1469 return -1;
1470end;
1471
1472(* The terminal openPty holds for pty, if any, closed *)
1473proc release(pty: INT);
1474var i: INT;
1475begin
1476 for i := 0 to LEN(held) - 1 do
1477 if held[i].pty = pty then
1478 _ := C.close(I32(held[i].tty));
1479 held[i].pty := -1;
1480 end;
1481 end;
1482end;
1483
1484(* Tells the terminal of the pseudo-terminal fd that it has cols
1485 columns and rows rows: 0, or minus an errno. *)
1486proc setTermSize*(fd, cols, rows: INT): INT;
1487var w: Winsize;
1488begin
1489 w := {rows: U16(rows), cols: U16(cols)};
1490 if C.ioctl(I32(fd), CAbi.tiocswinsz, SYSTEM.ADR(w)) # 0 then return failed(); end;
1491 return 0;
1492end;
1493
1494(* Copies s and a zero to at: the byte after them. *)
1495proc put(s: []const U8; at: ^U8): ^U8;
1496begin
1497 COPY(at[0..LEN(s)], s);
1498 at[LEN(s)] := 0;
1499 return at + (LEN(s) + 1);
1500end;
1501
1502(* Whether the NAME=value s, a C string, names a variable that one of
1503 env gives. *)
1504proc replaced(s: ^U8; env: [][]const U8): BOOL;
1505var i, n: INT;
1506begin
1507 for i := 0 to LEN(env) - 1 do
1508 n := 0;
1509 while (n < LEN(env[i])) and (s[n] = env[i][n]) and (s[n] # '=') do INC(n); end;
1510 if (n < LEN(env[i])) and (env[i][n] = '=') and (s[n] = '=') then return true; end;
1511 end;
1512 return false;
1513end;
1514
1515(* What execve takes, in fresh memory of the size returned: args as C
1516 strings and a nil, then the environment old with each NAME=value of
1517 env in place of its variable or added, and a nil; or nil. The
1518 environment follows the arguments. *)
1519proc argsAndEnv(args, env: [][]const U8; old: ^^U8): (^^U8, INT);
1520var p: ^^U8; s: ^U8; size, n, i, k: INT;
1521begin
1522 n := 0;
1523 while old[n] # nil do INC(n); end;
1524 size := (LEN(args) + n + LEN(env) + 2) * SIZE(^U8);
1525 for i := 0 to LEN(args) - 1 do INC(size, LEN(args[i]) + 1); end;
1526 for i := 0 to LEN(env) - 1 do INC(size, LEN(env[i]) + 1); end;
1527 p := ^^U8(mmap(size));
1528 if p = nil then return nil, 0; end;
1529 s := ^U8(p + (LEN(args) + n + LEN(env) + 2));
1530 k := 0;
1531 for i := 0 to LEN(args) - 1 do p[k] := s; s := put(args[i], s); INC(k); end;
1532 p[k] := nil;
1533 INC(k);
1534 for i := 0 to n - 1 do
1535 if not replaced(old[i], env) then p[k] := old[i]; INC(k); end;
1536 end;
1537 for i := 0 to LEN(env) - 1 do p[k] := s; s := put(env[i], s); INC(k); end;
1538 p[k] := nil;
1539 return p, size;
1540end;
1541
1542(* Sets the environment variable name to value, for env and for the
1543 programs this one starts; 0, or minus an errno: -22 if name is empty
1544 or holds an = or a 0, or value a 0, and -12 if there is no memory.
1545 The C library's setenv keeps the environment. It isn't safe while
1546 another thread reads the environment or starts a program. *)
1547proc setEnv*(name, value: []const U8): INT;
1548var p: ^U8; size, i, r: INT;
1549begin
1550 if LEN(name) = 0 then return -22; end; (* EINVAL *)
1551 for i := 0 to LEN(name) - 1 do
1552 if (name[i] = '=') or (name[i] = 0) then return -22; end;
1553 end;
1554 for i := 0 to LEN(value) - 1 do
1555 if value[i] = 0 then return -22; end;
1556 end;
1557 (* both as C strings, in memory that comes zeroed *)
1558 size := LEN(name) + LEN(value) + 2;
1559 p := mmap(size);
1560 if p = nil then return -12; end; (* ENOMEM *)
1561 COPY(p[0..LEN(name)], name);
1562 COPY(p[LEN(name) + 1..size - 1], value);
1563 r := 0;
1564 if C.setenv(p, p + (LEN(name) + 1), 1) # 0 then r := failed(); end;
1565 munmap(p, size);
1566 return r;
1567end;
1568
1569(* A pipe: the fd to read and the fd to write, both closed in a program
1570 exec starts; or minus an errno and -1. *)
1571proc pipe*: (INT, INT);
1572var fds: [2]I32;
1573begin
1574 if CAbi.makePipe(SYSTEM.ADR(fds[0]), CAbi.oCloexec) # 0 then return failed(), -1; end;
1575 return INT(fds[0]), INT(fds[1]);
1576end;
1577
1578(* This program's process id. *)
1579proc pid*: INT;
1580begin
1581 return INT(C.getpid());
1582end;
1583
1584(* The user this program runs as: its real id. *)
1585proc uid*: INT;
1586begin
1587 return INT(C.getuid());
1588end;
1589
1590(* The user whose rights this program has, its effective id: 0 is
1591 root. *)
1592proc euid*: INT;
1593begin
1594 return INT(C.geteuid());
1595end;
1596
1597(* The name of this machine, good until the next call; and 0, or minus
1598 an errno. *)
1599proc hostName*: ([]const U8, INT);
1600var n: INT;
1601begin
1602 if C.gethostname(SYSTEM.ADR(host[0]), LEN(host) - 1) # 0 then return "", failed(); end;
1603 host[LEN(host) - 1] := 0; (* POSIX doesn't promise one if it is cut *)
1604 n := 0;
1605 while host[n] # 0 do INC(n); end;
1606 return host[0..n], 0;
1607end;
1608
1609(* The number of processors this program may run on, at least 1. *)
1610proc processors*: INT;
1611var count: INT;
1612begin
1613 count := CAbi.processors();
1614 if count < 1 then return 1; end;
1615 return count;
1616end;
1617
1618(* The struct timeval at p, in ns *)
1619proc ns(p: ^U8): I64;
1620begin
1621 return field(p, CAbi.tvSecAt, CAbi.tvSecLen) * 1000000000 + field(p, CAbi.tvUsecAt, CAbi.tvUsecLen) * 1000;
1622end;
1623
1624(* The time on the processor, in ns, that this program has used, or,
1625 if children, the programs it started and waited for: in the program
1626 itself, and in the system for it. *)
1627proc cpuTime*(children: BOOL): (I64, I64);
1628var ru: [64]U64; p: ^U8; (* struct rusage, which cabi checks fits *)
1629begin
1630 p := ^U8(SYSTEM.ADR(ru));
1631 if children then _ := C.getrusage(CAbi.rusageChildren, p);
1632 else _ := C.getrusage(CAbi.rusageSelf, p);
1633 end;
1634 return ns(p + CAbi.ruUtimeAt), ns(p + CAbi.ruStimeAt);
1635end;
1636
1637(* The limit which, one of the limit constants: the soft one, which
1638 this program may raise up to the hard one; -1 for none; and 0, or
1639 minus an errno. *)
1640proc limit*(which: INT): (I64, I64, INT);
1641var r: [2]I64; i: INT; (* struct rlimit *)
1642begin
1643 if C.getrlimit(I32(which), ^U8(SYSTEM.ADR(r))) # 0 then return 0, 0, failed(); end;
1644 for i := 0 to 1 do
1645 if r[i] = CAbi.rlimInfinity then r[i] := -1; end;
1646 end;
1647 return r[0], r[1], 0;
1648end;
1649
1650(* Sets the limit which to soft and hard, -1 for none: 0, or minus an
1651 errno. *)
1652proc setLimit*(which: INT; soft, hard: I64): INT;
1653var r: [2]I64; i: INT;
1654begin
1655 r := [soft, hard];
1656 for i := 0 to 1 do
1657 if r[i] = -1 then r[i] := CAbi.rlimInfinity; end;
1658 end;
1659 if C.setrlimit(I32(which), ^U8(SYSTEM.ADR(r))) # 0 then return failed(); end;
1660 return 0;
1661end;
1662
1663(* Moves the program pid, or this one if pid is 0, to the process group
1664 group, or to a new one it leads if group is 0. *)
1665proc setGroup*(pid, group: INT): INT;
1666begin
1667 if C.setpgid(I32(pid), I32(group)) # 0 then return failed(); end;
1668 return 0;
1669end;
1670
1671(* The process group this program is in. *)
1672proc group*: INT;
1673begin
1674 return INT(C.getpgrp());
1675end;
1676
1677(* Gives the keys of the terminal on fd, and its signals, to the process
1678 group group. *)
1679proc foreground*(fd, group: INT): INT;
1680begin
1681 if C.tcsetpgrp(I32(fd), I32(group)) # 0 then return failed(); end;
1682 return 0;
1683end;
1684
1685(* The process group the terminal on fd gives its keys to, or minus an
1686 errno. *)
1687proc foregroundOf*(fd: INT): INT;
1688var g: I32;
1689begin
1690 g := C.tcgetpgrp(I32(fd));
1691 if g < 0 then return failed(); end;
1692 return INT(g);
1693end;
1694
1695(* Where spawn looks for a program named without a /, if PATH is unset
1696 or empty: glibc's execvp looks in these. *)
1697const defaultPath = "/bin:/usr/bin";
1698
1699(* The ith directory of search, a list of them with : between, as PATH
1700 is: dir, "." if it is empty, and where the next starts; -1 past the
1701 last. *)
1702proc pathDir(search: []const U8; i: INT): ([]const U8, INT);
1703var j: INT;
1704begin
1705 if i > LEN(search) then return "", -1; end;
1706 j := i;
1707 while (j < LEN(search)) and (search[j] # ':') do INC(j); end;
1708 if j = i then return ".", j + 1; end;
1709 return search[i..j], j + 1;
1710end;
1711
1712(* dir, a /, and name, a C string in buf; false if it doesn't fit. *)
1713proc joinPath(dir, name: []const U8; buf: []U8): BOOL;
1714var n: INT;
1715begin
1716 n := LEN(dir) + 1 + LEN(name);
1717 if n >= LEN(buf) then return false; end;
1718 COPY(buf, dir);
1719 buf[LEN(dir)] := '/';
1720 COPY(buf[LEN(dir) + 1..n], name);
1721 buf[n] := 0;
1722 return true;
1723end;
1724
1725(* Whether name holds a /, and so is a path, not a name to look for. *)
1726proc isPath(name: []const U8): BOOL;
1727var i: INT;
1728begin
1729 for i := 0 to LEN(name) - 1 do
1730 if name[i] = '/' then return true; end;
1731 end;
1732 return false;
1733end;
1734
1735(* Runs the program at name, as execve does; or, for a name without a
1736 /, the first program of that name in the directories of search, as
1737 execvp does: each in turn, an empty one being the working directory.
1738 It returns only if none could be run. It runs in spawn's child, after
1739 the fork, so it takes no memory: each path is made in buf. *)
1740proc run(name, search: []const U8; buf: []U8; argv, envp: ^^U8);
1741var dir: []const U8; i: INT;
1742begin
1743 if isPath(name) or (LEN(name) = 0) then
1744 if cstr(name, buf) then _ := C.execve(SYSTEM.ADR(buf[0]), argv, envp); end;
1745 return;
1746 end;
1747 dir, i := pathDir(search, 0);
1748 while i >= 0 do
1749 if joinPath(dir, name, buf) then _ := C.execve(SYSTEM.ADR(buf[0]), argv, envp); end;
1750 dir, i := pathDir(search, i);
1751 end;
1752end;
1753
1754(* The program exec runs for name, as a C string in buf: name itself
1755 if it has a /, or else the first file of that name in the
1756 directories of search that is no directory and that this user may
1757 run. 0; or -2 (ENOENT) if there is none, or -13 (EACCES) if one is
1758 there and can't be run. *)
1759proc find(name, search: []const U8; buf: []U8): INT;
1760var dir: []const U8; i, err, r: INT; f: Info;
1761begin
1762 if isPath(name) then
1763 if not cstr(name, buf) then return -36; end;
1764 return 0;
1765 end;
1766 r := -2; (* ENOENT *)
1767 dir, i := pathDir(search, 0);
1768 while (LEN(name) > 0) and (i >= 0) do
1769 if joinPath(dir, name, buf) then
1770 f, err := info(buf[0..LEN(dir) + 1 + LEN(name)]);
1771 if (err = 0) and not f.dir then
1772 if C.access(SYSTEM.ADR(buf[0]), 1) = 0 then return 0; end; (* X_OK *)
1773 r := -13; (* EACCES *)
1774 end;
1775 end;
1776 dir, i := pathDir(search, i);
1777 end;
1778 return r;
1779end;
1780
1781(* The name of the terminal of the pseudo-terminal fd, as a C string
1782 in name, which isn't safe to ask after a fork: 0, or minus an
1783 errno. *)
1784proc ptyName(fd: INT; name: []U8): INT;
1785var s: ^U8; n: INT;
1786begin
1787 s := C.ptsname(I32(fd));
1788 if s = nil then return failed(); end;
1789 n := 0;
1790 while s[n] # 0 do INC(n); end;
1791 if not cstr(s[0..n], name) then return -36; end;
1792 return 0;
1793end;
1794
1795(* Closes every fd from 3 on but those of keep, which stay open in the
1796 program exec starts. It runs in spawn's child, after the fork, so it
1797 takes no memory: it closes the runs between the fds kept, the lowest
1798 first, each with one closeFrom. *)
1799proc closeAllBut(keep: []const INT);
1800var lo, next, i: INT;
1801begin
1802 lo := 3;
1803 repeat
1804 next := -1;
1805 for i := 0 to LEN(keep) - 1 do
1806 if (keep[i] >= lo) and ((next < 0) or (keep[i] < next)) then next := keep[i]; end;
1807 end;
1808 if next < 0 then
1809 CAbi.closeFrom(lo, -1); (* the rest *)
1810 else
1811 if next > lo then CAbi.closeFrom(lo, next - 1); end;
1812 _ := C.fcntl(I32(next), CAbi.fSetfd, 0); (* kept on exec *)
1813 lo := next + 1;
1814 end;
1815 until next < 0;
1816end;
1817
1818(* What p asks of the program before it runs, done to this one: a
1819 session on the terminal name, if p.tty, or else its group, its
1820 terminal's foreground; then its standard input, output and error,
1821 each p.fds names over the terminal's; then its working directory,
1822 the C string dir. 0, or minus an errno. *)
1823proc takeOn(p: Program; name, dir: []const U8): INT;
1824var fd: I32; i: INT;
1825begin
1826 if p.tty # 0 then
1827 _ := C.setsid();
1828 fd := I32(heldTty(p.tty)); (* the terminal openPty holds, on macOS *)
1829 if fd < 0 then fd := C.open(SYSTEM.PTR(name), CAbi.oRdwr); end;
1830 if fd < 0 then return failed(); end;
1831 if C.ioctl(fd, CAbi.tiocsctty, 0) # 0 then return failed(); end;
1832 for i := 0 to 2 do _ := C.dup2(fd, I32(i)); end;
1833 else
1834 if p.group = -1 then _ := C.setpgid(0, 0);
1835 elsif p.group # 0 then _ := C.setpgid(0, I32(p.group));
1836 end;
1837 if p.foreground then _ := C.tcsetpgrp(0, C.getpgrp()); end;
1838 end;
1839 for i := 0 to 2 do
1840 if p.fds[i] = i then
1841 _ := keepOnExec(i, true); (* dup2 of a file onto itself would leave it closed on exec *)
1842 elsif p.fds[i] # 0 then
1843 _ := C.dup2(I32(p.fds[i]), I32(i));
1844 end;
1845 end;
1846 if (LEN(p.dir) > 0) and (C.chdir(SYSTEM.PTR(dir)) # 0) then return failed(); end;
1847 return 0;
1848end;
1849
1850(* Whether the struct sigaction a says SIG_IGN. *)
1851proc ignoredIn(var a: Sigaction): BOOL;
1852var h: ^UINT;
1853begin
1854 h := ^UINT(^U8(SYSTEM.ADR(a)) + CAbi.saHandlerAt);
1855 return h^ = 1;
1856end;
1857
1858(* Whether the signal sig does nothing now, as ignore(sig, true) or the
1859 program that started this one left it: its handler is SIG_IGN. *)
1860proc ignored*(sig: INT): BOOL;
1861var a: Sigaction;
1862begin
1863 _ := C.sigaction(I32(sig), nil, ^U8(SYSTEM.ADR(a)));
1864 return ignoredIn(a);
1865end;
1866
1867(* Starts the program p describes, found as run says: its process id,
1868 or minus an errno: -2 (ENOENT) or -13 (EACCES) as exec says, before
1869 the fork, if there is no program to run. A program found that
1870 execve then refuses ends with status 127. Every signal is blocked
1871 from the fork until the program has its own: its group, its
1872 terminal's foreground, and signals as they are at first. *)
1873proc spawn*(p: Program): INT;
1874var
1875 a, dir, name: [4096]U8; argv: ^^U8; none: ^U8; size, err, i, g: INT; search: []const U8;
1876 all, old, empty: Sigset; dfl: Sigaction; pid: I32;
1877begin
1878 if not cstr(p.path, a) or not cstr(p.dir, dir) then return -36; end; (* ENAMETOOLONG *)
1879 if p.tty # 0 then
1880 err := ptyName(p.tty, name); (* here, since it isn't safe after fork *)
1881 if err # 0 then return err; end;
1882 end;
1883 none := nil;
1884 if p.onlyEnv then
1885 argv, size := argsAndEnv(p.args, p.env, SYSTEM.ADR(none));
1886 else
1887 argv, size := argsAndEnv(p.args, p.env, C.environ);
1888 end;
1889 if argv = nil then return -12; end; (* ENOMEM *)
1890 search := env("PATH"); (* read here, before the fork *)
1891 if LEN(search) = 0 then search := defaultPath; end;
1892 err := find(p.path, search, a);
1893 if err < 0 then munmap(^U8(argv), size); return err; end;
1894 for i := 0 to LEN(all) - 1 do all[i] := 0FFFFFFFFFFFFFFFFH; end;
1895 _ := C.sigprocmask(CAbi.sigSetmask, ^U8(SYSTEM.ADR(all)), ^U8(SYSTEM.ADR(old)));
1896 pid := C.fork();
1897 if pid = 0 then
1898 if takeOn(p, name, dir) # 0 then C._exit(127); end;
1899 closeAllBut(p.more);
1900 for i := 1 to CAbi.sigMax do
1901 if not (p.keepIgnored and ignored(i)) then _ := C.sigaction(I32(i), ^U8(SYSTEM.ADR(dfl)), nil); end;
1902 end;
1903 _ := C.sigprocmask(CAbi.sigSetmask, ^U8(SYSTEM.ADR(empty)), nil);
1904 run(p.path, search, a, argv, argv + (LEN(p.args) + 1));
1905 C._exit(127);
1906 end;
1907 err := failed();
1908 if (pid > 0) and (p.tty # 0) and (CAbi.ptyHeld = 1) then
1909 release(p.tty); (* the child holds the terminal now *)
1910 end;
1911 if (pid > 0) and (p.tty = 0) then
1912 (* as the program does, for whichever of the two runs first *)
1913 g := p.group;
1914 if g = -1 then g := INT(pid); elsif g = 0 then g := INT(C.getpgrp()); end;
1915 if p.group # 0 then _ := C.setpgid(pid, I32(g)); end;
1916 if p.foreground then _ := C.tcsetpgrp(0, I32(g)); end;
1917 end;
1918 _ := C.sigprocmask(CAbi.sigSetmask, ^U8(SYSTEM.ADR(old)), nil);
1919 munmap(^U8(argv), size);
1920 if pid < 0 then return err; end;
1921 return INT(pid);
1922end;
1923
1924(* Runs the program p describes in this one's place, as spawn would
1925 start it, but keeping this program's other fds as they are, open
1926 unless closed on exec (as open and pipe give) and not kept by
1927 keepOnExec; the fds of p.more are kept. It returns
1928 only if it can't: -2 (ENOENT) or -13 (EACCES) if there is no
1929 program to run, before anything is done; or, once the program's
1930 terminal, group, fds and working directory are as p asks, which
1931 stay so, minus the errno that stopped it, with this program's
1932 signals given back as they were. *)
1933proc exec*(p: Program): INT;
1934var
1935 a, dir, name: [4096]U8; argv: ^^U8; none: ^U8; size, r, i: INT; search: []const U8;
1936 all, old, empty: Sigset; dfl: Sigaction; acts: [CAbi.sigMax + 1]Sigaction;
1937begin
1938 if not cstr(p.dir, dir) then return -36; end; (* ENAMETOOLONG *)
1939 if p.tty # 0 then
1940 r := ptyName(p.tty, name);
1941 if r # 0 then return r; end;
1942 end;
1943 search := env("PATH");
1944 if LEN(search) = 0 then search := defaultPath; end;
1945 r := find(p.path, search, a);
1946 if r < 0 then return r; end;
1947 none := nil;
1948 if p.onlyEnv then
1949 argv, size := argsAndEnv(p.args, p.env, SYSTEM.ADR(none));
1950 else
1951 argv, size := argsAndEnv(p.args, p.env, C.environ);
1952 end;
1953 if argv = nil then return -12; end; (* ENOMEM *)
1954 r := takeOn(p, name, dir);
1955 if r = 0 then
1956 for i := 0 to LEN(p.more) - 1 do
1957 if p.more[i] > 2 then _ := keepOnExec(p.more[i], true); end;
1958 end;
1959 (* every signal as it is at first and none blocked, as spawn
1960 gives them, each kept to give back if execve fails *)
1961 for i := 0 to LEN(all) - 1 do all[i] := 0FFFFFFFFFFFFFFFFH; end;
1962 _ := C.sigprocmask(CAbi.sigSetmask, ^U8(SYSTEM.ADR(all)), ^U8(SYSTEM.ADR(old)));
1963 for i := 1 to CAbi.sigMax do
1964 _ := C.sigaction(I32(i), nil, ^U8(SYSTEM.ADR(acts[i]))); (* as it is *)
1965 if not (p.keepIgnored and ignoredIn(acts[i])) then
1966 _ := C.sigaction(I32(i), ^U8(SYSTEM.ADR(dfl)), nil);
1967 end;
1968 end;
1969 _ := C.sigprocmask(CAbi.sigSetmask, ^U8(SYSTEM.ADR(empty)), nil);
1970 _ := C.execve(SYSTEM.ADR(a[0]), argv, argv + (LEN(p.args) + 1));
1971 r := failed();
1972 _ := C.sigprocmask(CAbi.sigSetmask, ^U8(SYSTEM.ADR(all)), nil);
1973 for i := 1 to CAbi.sigMax do _ := C.sigaction(I32(i), ^U8(SYSTEM.ADR(acts[i])), nil); end;
1974 _ := C.sigprocmask(CAbi.sigSetmask, ^U8(SYSTEM.ADR(old)), nil);
1975 end;
1976 munmap(^U8(argv), size);
1977 return r;
1978end;
1979
1980(* Runs the program at path in this one's place, with args, the first
1981 its name, and env, NAME=value, its whole environment, as the
1982 kernel's execve does and a shell wants: no search, and every fd and
1983 signal as it is, but that a handled signal does what it does at
1984 first. It returns only if it can't: minus an errno. *)
1985proc execve*(path: []const U8; args, env: [][]const U8): INT;
1986var a: [4096]U8; argv: ^^U8; none: ^U8; size, r: INT;
1987begin
1988 if not cstr(path, a) then return -36; end; (* ENAMETOOLONG *)
1989 none := nil;
1990 argv, size := argsAndEnv(args, env, SYSTEM.ADR(none));
1991 if argv = nil then return -12; end; (* ENOMEM *)
1992 _ := C.execve(SYSTEM.ADR(a[0]), argv, argv + (LEN(args) + 1));
1993 r := failed();
1994 munmap(^U8(argv), size);
1995 return r;
1996end;
1997
1998(* waitpid with options, its status read as C's macros read it. *)
1999proc waitFor(pid: INT; options: I32): (INT, Status, INT);
2000var status, r: I32;
2001begin
2002 (* again after EINTR, unless a signal handle took broke in: macOS
2003 breaks into a wait for a SIGCHLD that nothing catches *)
2004 _ := XCHG(broke, 0);
2005 repeat r := C.waitpid(I32(pid), SYSTEM.ADR(status), options); until (r >= 0) or not again();
2006 if r < 0 then return failed(), running, 0; end;
2007 if r = 0 then return 0, running, 0; end;
2008 if status & 7FH = 0 then return INT(r), exited, INT(status) shr 8 & 0FFH; end;
2009 if status & 0FFH = 7FH then return INT(r), stopped, INT(status) shr 8 & 0FFH; end;
2010 return INT(r), killed, INT(status) & 7FH;
2011end;
2012
2013(* Waits for the program pid, any of this program's if pid is -1, or
2014 any of the group g if pid is -g, to change, if block, and says which one changed and how: exited, with
2015 its exit status; killed or stopped, with the signal's number. Without
2016 block it doesn't wait: 0 and running if none has changed. Minus an
2017 errno, and running, if there is none to wait for. The status is read
2018 as C's macros read it, which every Unix encodes alike. *)
2019proc wait*(pid: INT; block: BOOL): (INT, Status, INT);
2020var options: I32;
2021begin
2022 options := CAbi.wNohang | CAbi.wUntraced;
2023 if block then options := CAbi.wUntraced; end;
2024 return waitFor(pid, options);
2025end;
2026
2027(* Waits for the program pid as wait does, but only for one to end:
2028 a stopped program is not waited for, so the status is exited or
2029 killed, or running if there is none to wait for. *)
2030proc waitExit*(pid: INT): (INT, Status, INT);
2031begin
2032 return waitFor(pid, 0);
2033end;
2034
2035(* Sends the program pid, or the group -pid, the signal: 0, or minus an
2036 errno. *)
2037proc kill*(pid, signal: INT): INT;
2038begin
2039 if C.kill(I32(pid), I32(signal)) # 0 then return failed(); end;
2040 return 0;
2041end;
2042
2043(* The handler of caught signals: their numbers go down the pipe, which
2044 catch gives the end of to read. *)
2045proc onSignal(sig: I32);
2046var e: ^I32; saved: I32; b: [1]U8;
2047begin
2048 e := CAbi.errno();
2049 saved := e^; (* as the code it stopped left it *)
2050 b[0] := U8(sig);
2051 _ := C.write(sigWrite, SYSTEM.ADR(b[0]), 1);
2052 e^ := saved;
2053end;
2054
2055(* A struct sigaction with the handler h, nil for SIG_DFL, and flags,
2056 and no signal blocked while it runs *)
2057proc action(h: Handler; flags: INT): Sigaction;
2058var a: Sigaction; p: ^Handler;
2059begin
2060 p := ^Handler(^U8(SYSTEM.ADR(a)) + CAbi.saHandlerAt);
2061 p^ := h;
2062 setField(^U8(SYSTEM.ADR(a)), CAbi.saFlagsAt, CAbi.saFlagsLen, flags);
2063 return a;
2064end;
2065
2066(* Whether sig is a signal a program may take: not SIGKILL or SIGSTOP,
2067 which can't be, nor SIGFPE or SIGSEGV, Rt's *)
2068proc takable(sig: INT): BOOL;
2069begin
2070 return (sig >= 1) and (sig <= CAbi.sigMax) and (sig # sigKill) and (sig # sigStop)
2071 and (sig # CAbi.sigFpe) and (sig # CAbi.sigSegv);
2072end;
2073
2074(* Catches the signals sigs: they don't do what they would, but give
2075 their numbers on an fd, which a later catch adds to and gives again;
2076 or minus an errno. *)
2077proc catch*(sigs: []const INT): INT;
2078var fds: [2]I32; act: Sigaction; i: INT;
2079begin
2080 for i := 0 to LEN(sigs) - 1 do
2081 if not takable(sigs[i]) then return -22; end; (* EINVAL *)
2082 end;
2083 if sigWrite = 0 then
2084 if CAbi.makePipe(SYSTEM.ADR(fds[0]), CAbi.oNonblock | CAbi.oCloexec) # 0 then return failed(); end;
2085 sigRead := fds[0];
2086 sigWrite := fds[1];
2087 end;
2088 act := action(onSignal, CAbi.saRestart);
2089 for i := 0 to LEN(sigs) - 1 do
2090 if C.sigaction(I32(sigs[i]), ^U8(SYSTEM.ADR(act)), nil) # 0 then return failed(); end;
2091 end;
2092 return INT(sigRead);
2093end;
2094
2095(* The next signal catch's fd has, or 0 if none is waiting. *)
2096proc caught*(fd: INT): INT;
2097var b: [1]U8;
2098begin
2099 if read(fd, b) # 1 then return 0; end;
2100 return INT(b[0]);
2101end;
2102
2103(* Makes the signal sig do nothing, or, if not yes, what it does at
2104 first: 0, or minus an errno. A signal catch took is given up: it is
2105 caught no more (a number already on catch's fd is still given). *)
2106proc ignore*(sig: INT; yes: BOOL): INT;
2107var act: Sigaction;
2108begin
2109 if yes then act := action(Handler(1), 0); end; (* SIG_IGN *)
2110 if C.sigaction(I32(sig), ^U8(SYSTEM.ADR(act)), nil) # 0 then return failed(); end;
2111 return 0;
2112end;
2113
2114(* Whether the file descriptor fd is a terminal. *)
2115proc isTerminal*(fd: INT): BOOL;
2116begin
2117 return C.isatty(I32(fd)) = 1;
2118end;
2119
2120(* The handler of the signals handle takes: it notes that sig came, and
2121 does nothing else, since it runs between any two instructions of the
2122 program, perhaps while Out or Heap holds its lock. *)
2123proc onNoted(sig: I32);
2124begin
2125 _ := XCHG(noted[sig], 1);
2126 _ := XCHG(broke, 1);
2127end;
2128
2129(* Takes the signal sig away from what it would do: it is noted, for
2130 came to see, and a system call it comes during fails with -4 (EINTR)
2131 rather than going on, so that a program waiting for another, or for
2132 a key, sees Ctrl-C at once. 0, or minus an errno. ignore(sig, false)
2133 gives it back what it does at first. *)
2134proc handle*(sig: INT): INT;
2135var act: Sigaction;
2136begin
2137 if not takable(sig) then return -22; end; (* EINVAL *)
2138 act := action(onNoted, 0); (* no SA_RESTART *)
2139 if C.sigaction(I32(sig), ^U8(SYSTEM.ADR(act)), nil) # 0 then return failed(); end;
2140 return 0;
2141end;
2142
2143(* Whether the signal sig, which handle took, came since the last time
2144 it was asked. *)
2145proc came*(sig: INT): BOOL;
2146begin
2147 if (sig < 1) or (sig > CAbi.sigMax) then return false; end;
2148 return XCHG(noted[sig], 0) = 1;
2149end;
2150
2151(* A copy of this program, which goes on from here: 0 in the copy, its
2152 process id in this one, or minus an errno. Only the thread that
2153 calls it is copied, so a program with threads mustn't; and what Out
2154 keeps is copied too, to be written twice, so the program flushes it
2155 first. *)
2156proc fork*: INT;
2157var r: I32;
2158begin
2159 r := C.fork();
2160 if r < 0 then return failed(); end;
2161 return INT(r);
2162end;
2163
2164(* A new session and process group, led by this program, with no
2165 controlling terminal: its process id, or minus an errno (-1, EPERM,
2166 if it leads a process group already, as a program just forked
2167 doesn't). *)
2168proc setsid*: INT;
2169var r: I32;
2170begin
2171 r := C.setsid();
2172 if r < 0 then return failed(); end;
2173 return INT(r);
2174end;
2175
2176(* Gives the processor to another thread. *)
2177proc yield*;
2178begin
2179 _ := C.sched_yield();
2180end;
2181
2182(* Ends the program, at once, with status. *)
2183proc exit*(status: INT);
2184begin
2185 C._exit(I32(status));
2186end;
2187
2188(* The test of programs: one on a pseudo-terminal of 100 by 30 prints
2189 its arguments, a variable put in place and its size, and leads the
2190 terminal's foreground until it ends with status 3; one in a
2191 directory and an environment of its own writes to a pipe; one in a
2192 group of its own is stopped and killed through it; one that isn't
2193 there is no child, and one found that execve refuses ends with 127;
2194 ignored signals stay so only with keepIgnored; fds replace a
2195 terminal's files. Then signals: caught as a program ends and as
2196 one is sent; and a program starts with them neither caught nor
2197 ignored. *)
2198proc testPrograms;
2199var pty, child, n, m, r, w, sigs, c: INT; st: Status; buf: [64]U8;
2200begin
2201 pty := openPty();
2202 if (pty < 0) or (setTermSize(pty, 100, 30) # 0) then exit(2); end;
2203 child := spawn({path: "/bin/sh", args: ["sh", "-c", "echo $0 $1 $HOME; stty size; read x; exit 3", "a", "b"],
2204 env: ["HOME=/h"], tty: pty});
2205 if child <= 0 then exit(2); end;
2206 n := 0;
2207 while n < 16 do
2208 if not ready(pty, 5000) then exit(2); end;
2209 m := read(pty, buf[n..LEN(buf)]);
2210 if m <= 0 then exit(2); end;
2211 INC(n, m);
2212 end;
2213 if (buf[0..n] # "a b /h\r\n30 100\r\n") or (foregroundOf(pty) # child) then exit(2); end;
2214 if write(pty, "\n") # 1 then exit(2); end;
2215 repeat
2216 if not ready(pty, 5000) then exit(2); end;
2217 until read(pty, buf) <= 0; (* -5, EIO, once the terminal has no program *)
2218 close(pty);
2219 r, st, c := wait(child, true);
2220 if (r # child) or (st # exited) or (c # 3) then exit(2); end;
2221
2222 r, w := pipe();
2223 if w < 0 then exit(2); end;
2224 (* in /usr, which is no link, on macOS too, where /tmp is one *)
2225 child := spawn({path: "/bin/sh", args: ["sh", "-c", "echo $X $HOME; pwd"], env: ["X=x"], onlyEnv: true,
2226 dir: "/usr", fds: [0, w, 0]});
2227 close(w);
2228 n := 0;
2229 repeat
2230 m := read(r, buf[n..LEN(buf)]);
2231 if m > 0 then INC(n, m); end;
2232 until m <= 0;
2233 close(r);
2234 if buf[0..n] # "x\n/usr\n" then exit(2); end;
2235 r, st, c := wait(child, true);
2236 if (r # child) or (st # exited) or (c # 0) then exit(2); end;
2237
2238 (* a pipe filled without waiting, then emptied: room to write again *)
2239 r, w := pipe();
2240 if (w < 0) or (setBlocking(w, false) # 0) or (setBlocking(r, false) # 0) then exit(2); end;
2241 repeat n := write(w, buf); until n < 0;
2242 if (n # -11) or (readyFor([], [w], 0) # -1) or (readyFor([r], [w], 0) # r) then exit(2); end;
2243 repeat n := read(r, buf); until n < 0;
2244 if (n # -11) or (readyFor([r], [w], 0) # w) or (setBlocking(w, true) # 0) then exit(2); end;
2245 close(r);
2246 close(w);
2247
2248 (* blocking: a fresh pipe waits, a non-blocking one doesn't, a closed fd is -9 *)
2249 r, w := pipe();
2250 if (blocking(r) # 1) or (setBlocking(r, false) # 0) or (blocking(r) # 0) then exit(2); end;
2251 if (setBlocking(r, true) # 0) or (blocking(r) # 1) then exit(2); end;
2252 close(r);
2253 close(w);
2254 if blocking(r) # -9 then exit(2); end;
2255
2256 (* setsid: a forked child leads a session of its own, once; a group leader can't *)
2257 child := fork();
2258 if child = 0 then
2259 if (setsid() # pid()) or (setsid() # -1) then exit(2); end;
2260 exit(0);
2261 end;
2262 r, st, c := wait(child, true);
2263 if (r # child) or (st # exited) or (c # 0) then exit(2); end;
2264 child := fork();
2265 if child = 0 then
2266 if (setGroup(0, 0) # 0) or (setsid() # -1) then exit(2); end;
2267 exit(0);
2268 end;
2269 r, st, c := wait(child, true);
2270 if (r # child) or (st # exited) or (c # 0) then exit(2); end;
2271
2272 child := spawn({path: "/bin/sleep", args: ["sleep", "10"], group: -1});
2273 r, st, c := wait(child, false);
2274 if (r # 0) or (st # running) or (kill(-child, sigStop) # 0) then exit(2); end;
2275 r, st, c := wait(child, true);
2276 if (r # child) or (st # stopped) or (c # sigStop) or (kill(-child, sigKill) # 0) then exit(2); end;
2277 r, st, c := wait(-1, true);
2278 if (r # child) or (st # killed) or (c # sigKill) then exit(2); end;
2279 r, st, c := wait(-1, true);
2280 if r # -10 then exit(2); end; (* ECHILD: none left *)
2281 child := spawn({path: "/no/such/program", args: ["x"]});
2282 r, st, c := wait(child, true);
2283 if (r # child) or (st # exited) or (c # 127) then exit(2); end;
2284 (* a name without a / is looked for along PATH *)
2285 child := spawn({path: "sh", args: ["sh", "-c", "exit 4"]});
2286 r, st, c := wait(child, true);
2287 if (r # child) or (st # exited) or (c # 4) then exit(2); end;
2288 (* one not on PATH is no child at all *)
2289 if spawn({path: "no-such-program-on-path", args: ["x"]}) # -2 then exit(2); end;
2290 r, st, c := wait(-1, false);
2291 if r # -10 then exit(2); end; (* ECHILD: none was made *)
2292 (* an ignored signal stays so only with keepIgnored *)
2293 if ignore(sigInt, true) # 0 then exit(2); end;
2294 child := spawn({path: "sh", args: ["sh", "-c", "kill -INT $$; exit 6"], keepIgnored: true});
2295 r, st, c := waitExit(child);
2296 if (r # child) or (st # exited) or (c # 6) then exit(2); end;
2297 child := spawn({path: "sh", args: ["sh", "-c", "kill -INT $$; exit 6"]});
2298 r, st, c := waitExit(child);
2299 if (r # child) or (st # killed) or (c # sigInt) then exit(2); end;
2300 if ignore(sigInt, false) # 0 then exit(2); end;
2301 (* fds replace the terminal's files, with tty *)
2302 pty := openPty();
2303 r, w := pipe();
2304 child := spawn({path: "sh", args: ["sh", "-c", "echo out; echo err >&2"], tty: pty, fds: [0, w, 0]});
2305 close(w);
2306 n := 0;
2307 repeat
2308 m := read(r, buf[n..LEN(buf)]);
2309 if m > 0 then INC(n, m); end;
2310 until m <= 0;
2311 close(r);
2312 (* the pty closed first: macOS's last close of a terminal, the
2313 child's at its exit, waits until what was written to it is read *)
2314 close(pty);
2315 r, st, c := waitExit(child);
2316 if (buf[0..n] # "out\n") or (r # child) or (st # exited) or (c # 0) then exit(2); end;
2317
2318 sigs := catch([sigChld, sigHup]);
2319 if (sigs < 0) or (catch([sigWinch]) # sigs) or (catch([CAbi.sigSegv]) # -22) or (catch([sigKill]) # -22) then exit(2); end;
2320 if (caught(sigs) # 0) or (ignore(sigInt, true) # 0) then exit(2); end;
2321 child := spawn({path: "/bin/sh", args: ["sh", "-c", "kill -INT $$; exit 0"]});
2322 if not ready(sigs, 5000) or (caught(sigs) # sigChld) then exit(2); end;
2323 r, st, c := wait(child, true);
2324 if (st # killed) or (c # sigInt) then exit(2); end;
2325 child := spawn({path: "/bin/sh", args: ["sh", "-c", "kill -HUP $$; exit 0"]});
2326 r, st, c := wait(child, true);
2327 if (st # killed) or (c # sigHup) then exit(2); end;
2328 while caught(sigs) # 0 do end;
2329 if (kill(pid(), sigHup) # 0) or not ready(sigs, 1000) or (caught(sigs) # sigHup) then exit(2); end;
2330 if ignore(sigInt, false) # 0 then exit(2); end;
2331end;
2332
2333(* The test of what a shell needs: fds copied, moved and kept on
2334 exec; a program given an fd at its own number, and one not; access,
2335 the umask and the environment by number; a terminal's modes; time
2336 used; limits; who and where; and exec, with nothing to run, and
2337 with a program that can't be run, after which the signals caught
2338 are caught still. *)
2339proc testShell;
2340var
2341 r, w, fd, n, k, child, c, err, pty, sigs, mask, parent: INT; t: I64; st: Status; buf: [64]U8;
2342 m, raw, back: Mode; soft, hard, s2, h2, user, system: I64; e: []const U8; ok, path: BOOL;
2343begin
2344 r, w := pipe();
2345 if w < 0 then exit(2); end;
2346 fd := dup(w);
2347 if (fd < 0) or (write(fd, "ab") # 2) or (read(r, buf) # 2) then exit(2); end;
2348 close(fd);
2349 if (dupTo(w, 9) # 9) or (write(9, "c") # 1) or (read(r, buf) # 1) or (buf[0] # 'c') then exit(2); end;
2350 if (keepOnExec(9, false) # 0) or (keepOnExec(9, true) # 0) or (keepOnExec(-1, true) # -9) then exit(2); end;
2351 child := spawn({path: "/bin/sh", args: ["sh", "-c", "echo more >&9"], more: [9]});
2352 close(9);
2353 close(w);
2354 n := 0;
2355 repeat
2356 k := read(r, buf[n..LEN(buf)]);
2357 if k > 0 then INC(n, k); end;
2358 until k <= 0;
2359 close(r);
2360 if buf[0..n] # "more\n" then exit(2); end;
2361 k, st, c := wait(child, true);
2362 if (st # exited) or (c # 0) then exit(2); end;
2363 r, w := pipe();
2364 if (w < 0) or (dupTo(w, 9) # 9) then exit(2); end;
2365 child := spawn({path: "/bin/sh", args: ["sh", "-c", "{ echo none >&9; } 2>/dev/null"]}); (* 9 is closed in it *)
2366 close(9);
2367 close(w);
2368 if read(r, buf) # 0 then exit(2); end;
2369 close(r);
2370 k, st, c := wait(child, true);
2371 if (st # exited) or (c = 0) then exit(2); end;
2372
2373 if (access("/bin/sh", {executing}) # 0) or (access("/", {reading}) # 0)
2374 or (access("/no/such/file", {}) # -2) or (open("/bin/sh", {executing}) # -22) then exit(2); end;
2375 mask := umask(3FH); (* 077 *)
2376 if umask(mask) # 3FH then exit(2); end;
2377 path := false;
2378 n := 0;
2379 repeat
2380 e, ok := envAt(n);
2381 if ok and (LEN(e) > 5) and (e[0..5] = "PATH=") then path := true; end;
2382 INC(n);
2383 until not ok;
2384 e, ok := envAt(-1);
2385 if not path or ok or (LEN(e) # 0) then exit(2); end;
2386
2387 (* a terminal's modes, kept and given back *)
2388 pty := openPty();
2389 m, err := getMode(pty);
2390 if (err # 0) or not rawMode(pty) then exit(2); end;
2391 raw, err := getMode(pty);
2392 if (err # 0) or (raw.t = m.t) or (setMode(pty, m) # 0) then exit(2); end;
2393 (* not raw again, and as it was, but for what the system notes
2394 itself, as macOS's PENDIN after raw mode *)
2395 back, err := getMode(pty);
2396 if (err # 0) or (back.t = raw.t) then exit(2); end;
2397 if (CAbi.ptyHeld = 0) and (back.t # m.t) then exit(2); end;
2398 m, err := getMode(-1);
2399 if err # -9 then exit(2); end; (* EBADF *)
2400 r, w := pipe();
2401 m, err := getMode(r);
2402 if err # -25 then exit(2); end; (* ENOTTY *)
2403 close(r);
2404 close(w);
2405 close(pty);
2406
2407 user, system := cpuTime(false);
2408 if (user < 0) or (system < 0) or (user + system = 0) then exit(2); end;
2409 user, system := cpuTime(true);
2410 if (user < 0) or (system < 0) then exit(2); end;
2411 soft, hard, err := limit(limitFiles);
2412 if (err # 0) or (soft < 16) or (setLimit(limitFiles, soft - 1, hard) # 0) then exit(2); end;
2413 s2, h2, err := limit(limitFiles);
2414 if (err # 0) or (s2 # soft - 1) or (h2 # hard) or (setLimit(limitFiles, soft, hard) # 0) then exit(2); end;
2415 soft, hard, err := limit(10000);
2416 if err # -22 then exit(2); end; (* EINVAL *)
2417 e, err := hostName();
2418 if (err # 0) or (LEN(e) = 0) or (uid() < 0) or (euid() < 0) then exit(2); end;
2419
2420 (* a copy of an fd out of the way; this program's group; a copy of
2421 this program, waited for by the group; a signal noted, and a wait
2422 it breaks into *)
2423 r, w := pipe();
2424 fd := dupAbove(w, 10);
2425 if (fd < 10) or (write(fd, "d") # 1) or (read(r, buf) # 1) or (dupAbove(-1, 10) # -9) then exit(2); end;
2426 close(fd);
2427 if group() <= 0 then exit(2); end;
2428 child := fork();
2429 if child = 0 then exit(7); end;
2430 k, st, c := wait(-group(), true);
2431 if (k # child) or (st # exited) or (c # 7) then exit(2); end;
2432 if (handle(sigUsr2) # 0) or came(sigUsr2) or (handle(sigKill) # -22) then exit(2); end;
2433 if (kill(pid(), sigUsr2) # 0) or not came(sigUsr2) or came(sigUsr2) then exit(2); end;
2434 parent := pid();
2435 child := fork();
2436 if child = 0 then sleep(100); _ := kill(parent, sigUsr2); exit(0); end;
2437 t := clock();
2438 if ready(r, 5000) or not came(sigUsr2) or (clock() - t > 4000000000) then exit(2); end;
2439 k, st, c := wait(child, true);
2440 if (k # child) or (ignore(sigUsr2, false) # 0) then exit(2); end;
2441 close(r);
2442 close(w);
2443
2444 sigs := catch([sigUsr1]);
2445 while caught(sigs) # 0 do end; (* the sigChld of the programs above *)
2446 if (sigs < 0) or (exec({path: "no-such-program-on-path", args: ["x"]}) # -2) then exit(2); end;
2447 if exec({path: "/etc/passwd", args: ["x"]}) # -13 then exit(2); end; (* not executable *)
2448 if (kill(pid(), sigUsr1) # 0) or not ready(sigs, 1000) or (caught(sigs) # sigUsr1) then exit(2); end;
2449end;
2450
2451(* The test of time, random bytes and the network: a sleep the clock
2452 sees; addresses read and refused; a TCP connection on the loopback;
2453 a datagram to a port where no one listens, refused; servers on
2454 ports the system chooses, of streams and of datagrams. *)
2455proc testNet;
2456var t: I64; l, c, a, u, port, n, i: INT; x, y: [16]U8; s, s6: Sockaddr; p, q: ^U8; peer: Peer;
2457begin
2458 t := clock();
2459 sleep(20);
2460 t := clock() - t;
2461 if (t < 20000000) or (t > 2000000000) or (now() < 1700000000 * 1000000000) then exit(2); end;
2462 random(x);
2463 random(y);
2464 if x[0..16] = y[0..16] then exit(2); end;
2465 p := ^U8(SYSTEM.ADR(s));
2466 q := ^U8(SYSTEM.ADR(s6)) + CAbi.sin6AddrAt;
2467 if (inetAddr("10.0.0.255", 80, SYSTEM.ADR(s)) # CAbi.sockaddrInLen) or (portOf(p) # 80)
2468 or (p[CAbi.sinAddrAt] # 10) or (p[CAbi.sinAddrAt + 2] # 0) or (p[CAbi.sinAddrAt + 3] # 255) then
2469 exit(2);
2470 end;
2471 if (inetAddr("1:aBcd::ff", 258, SYSTEM.ADR(s6)) # CAbi.sockaddrIn6Len) or (portOf(^U8(SYSTEM.ADR(s6))) # 258)
2472 or (q[1] # 1) or (q[2] # 0ABH) or (q[3] # 0CDH) or (q[14] # 0) or (q[15] # 0FFH) then
2473 exit(2);
2474 end;
2475 q := ^U8(SYSTEM.ADR(s6));
2476 for i := CAbi.sin6PortAt + 2 to CAbi.sin6AddrAt - 1 do (* the flow, zero *)
2477 if q[i] # 0 then exit(2); end;
2478 end;
2479 if (inetAddr("::", 0, SYSTEM.ADR(s6)) # CAbi.sockaddrIn6Len) or (inetAddr("1:2:3:4:5:6:7:8", 0, SYSTEM.ADR(s6)) # CAbi.sockaddrIn6Len) then exit(2); end;
2480 if (connectTcp("1.2.3", 80) # -22) or (connectTcp("1.2.3.256", 80) # -22) or (connectTcp("1::2::3", 80) # -22)
2481 or (connectTcp("1:2:3:4:5:6:7:8:9", 80) # -22) or (connectTcp("1:", 80) # -22)
2482 or (connectTcp("12345::", 80) # -22) or (connectTcp("::1", 65536) # -22) then
2483 exit(2);
2484 end;
2485 l := listenTcp("127.0.0.1", 47391);
2486 c := connectTcp("127.0.0.1", 47391);
2487 if (l < 0) or (c < 0) then exit(2); end;
2488 a := accept(l);
2489 if (a < 0) or (send(c, "hi") # 2) or (read(a, x) # 2) or (x[0..2] # "hi") then exit(2); end;
2490 close(a);
2491 close(c);
2492 close(l);
2493 u := connectUdp("127.0.0.1", 47391);
2494 if (u < 0) or (send(u, "x") # 1) or not ready(u, 1000) or (read(u, x) # -111) then exit(2); end; (* ECONNREFUSED *)
2495 close(u);
2496 (* a server on a port the system chooses, and a connection to it
2497 within a time; then none, where no one listens *)
2498 l := listenTcp("127.0.0.1", 0);
2499 port := localPort(l);
2500 if (l < 0) or (port <= 0) then exit(2); end;
2501 c := connectTcpWithin("127.0.0.1", port, 1000);
2502 a := accept(l);
2503 if (c < 0) or (a < 0) or (send(c, "hi") # 2) or (read(a, x) # 2) then exit(2); end;
2504 close(a);
2505 close(c);
2506 close(l);
2507 if connectTcpWithin("127.0.0.1", port, 1000) # -111 then exit(2); end;
2508 (* a datagram to a server, and its answer *)
2509 l := listenUdp("127.0.0.1", 0);
2510 port := localPort(l);
2511 u := connectUdp("127.0.0.1", port);
2512 if (l < 0) or (port <= 0) or (u < 0) or (send(u, "ping") # 4) then exit(2); end;
2513 n, peer := receive(l, x[0..2]);
2514 if (n # 2) or (x[0..2] # "pi") or (reply(l, peer, "pong") # 4) then exit(2); end;
2515 if (read(u, x) # 4) or (x[0..4] # "pong") then exit(2); end;
2516 close(u);
2517 close(l);
2518end;
2519
2520(* Runs a copy of this program that catches sigUsr1 and sigUsr2, gives
2521 up sigUsr1 by ignore(sigUsr1, yes) and sends itself send. The copy
2522 exits 0 if sigUsr1 then does nothing, or sigUsr2 still comes on
2523 catch's fd, and 1 if not; this says how it ended. *)
2524proc giveUpChild(yes: BOOL; send: INT): (Status, INT);
2525var child, c, fd: INT; st: Status;
2526begin
2527 child := fork();
2528 if child = 0 then
2529 fd := catch([sigUsr1, sigUsr2]);
2530 if fd < 0 then exit(3); end;
2531 while caught(fd) # 0 do end; (* what the parent had left there *)
2532 if (ignore(sigUsr1, yes) # 0) or (kill(pid(), send) # 0) then exit(3); end;
2533 if send = sigUsr1 then
2534 if ready(fd, 100) then exit(1); end; (* it ought to have ended, or be ignored *)
2535 exit(0);
2536 end;
2537 if not ready(fd, 1000) or (caught(fd) # sigUsr2) then exit(1); end;
2538 exit(0);
2539 end;
2540 _, st, c := wait(child, true);
2541 return st, c;
2542end;
2543
2544(* The test of giving a caught signal up: with the default back it
2545 ends the program; ignored it does nothing; and the signals still
2546 caught still come on catch's fd. *)
2547proc testGiveUp;
2548var st: Status; c: INT;
2549begin
2550 st, c := giveUpChild(false, sigUsr1);
2551 if (st # killed) or (c # sigUsr1) then exit(2); end;
2552 st, c := giveUpChild(true, sigUsr1);
2553 if (st # exited) or (c # 0) then exit(2); end;
2554 st, c := giveUpChild(false, sigUsr2);
2555 if (st # exited) or (c # 0) then exit(2); end;
2556end;
2557
2558(* The test of what a program asks of itself: a signal ignored or not,
2559 an environment variable unset or empty, and the processors. *)
2560proc testProcess;
2561var v: []const U8; found: BOOL;
2562begin
2563 if (ignore(sigUsr1, true) # 0) or not ignored(sigUsr1) then exit(2); end;
2564 if (ignore(sigUsr1, false) # 0) or ignored(sigUsr1) then exit(2); end;
2565 v, found := findEnv("RAZ_NO_SUCH_VARIABLE");
2566 if found or (LEN(v) # 0) then exit(2); end;
2567 if setEnv("RAZ_SYS_TEST_EMPTY", "") # 0 then exit(2); end;
2568 v, found := findEnv("RAZ_SYS_TEST_EMPTY");
2569 if not found or (LEN(v) # 0) then exit(2); end;
2570 v, found := findEnv("PATH");
2571 if not found or (LEN(v) = 0) then exit(2); end;
2572 if processors() < 1 then exit(2); end;
2573end;
2574
2575(* The test of what a server needs: a pair of sockets, one end told
2576 it has no more to read, who is at the other end of a Unix socket and
2577 of a TCP one, a send that doesn't wait, and a fifo opened without
2578 waiting. *)
2579proc testServer;
2580var a, b, l, c, s, port, n, r: INT; buf: [8]U8; full: [4096]U8; w: Remote; j: Info;
2581begin
2582 a, b, r := socketPair();
2583 if (r # 0) or (send(a, "hi") # 2) or (read(b, buf) # 2) or (buf[0..2] # "hi") then exit(2); end;
2584 if (closeWrite(a) # 0) or (read(b, buf) # 0) then exit(2); end; (* b reads an end, *)
2585 if (send(b, "yo") # 2) or (read(a, buf) # 2) or (buf[0..2] # "yo") then exit(2); end; (* and can still answer *)
2586 w, r := peer(a);
2587 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;
2588 close(a);
2589 close(b);
2590 a, b, r := socketPair(); (* sendNow gives -11 once the socket is full, *)
2591 if r # 0 then exit(2); end;
2592 n := 0;
2593 while sendNow(a, full) = LEN(full) do INC(n); end;
2594 if (n = 0) or (sendNow(a, full) # errAgain) then exit(2); end; (* where send would wait *)
2595 close(a);
2596 close(b);
2597 _, r := peer(-1);
2598 if r # errBadFd then exit(2); end;
2599 l := listenTcp("127.0.0.1", 0);
2600 port := localPort(l);
2601 c := connectTcp("127.0.0.1", port);
2602 s := accept(l);
2603 if (l < 0) or (c < 0) or (s < 0) then exit(2); end;
2604 w, r := peer(c);
2605 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;
2606 w, r := peer(s);
2607 if (r # 0) or (w.port = port) or (w.addr[3] # 1) or (w.addr[4] # 0) then exit(2); end;
2608 close(s);
2609 close(c);
2610 close(l);
2611 _ := remove("/tmp/raz-sys-fifo");
2612 if makeFifo("/tmp/raz-sys-fifo", 1A4H) # 0 then exit(2); end;
2613 j, r := info("/tmp/raz-sys-fifo");
2614 if (r # 0) or j.file or j.dir then exit(2); end; (* a fifo is neither *)
2615 if j.uid # uid() then exit(2); end; (* made by this user *)
2616 if (chown("/tmp/raz-sys-fifo", j.uid, j.gid) # 0) or (chown("/tmp/raz-sys-fifo", -1, -1) # 0) then exit(2); end;
2617 if chown("/no/such/file", -1, -1) # -2 then exit(2); end;
2618 if open("/tmp/raz-sys-fifo", {writing, nonblocking}) # -6 then exit(2); end; (* ENXIO: no reader, and it didn't wait *)
2619 a := open("/tmp/raz-sys-fifo", {reading, nonblocking});
2620 b := open("/tmp/raz-sys-fifo", {writing, nonblocking});
2621 if (a < 0) or (b < 0) or (read(a, buf) # errAgain) then exit(2); end; (* nothing to read, and it didn't wait *)
2622 close(a);
2623 close(b);
2624 _ := remove("/tmp/raz-sys-fifo");
2625end;
2626
2627(* The test of memory and files mapped: a file open only to read, mapped
2628 to be read, and not to be written; and pages that change what may be
2629 done with them. *)
2630proc testMaps;
2631var fd: INT; p, q: ^U8;
2632begin
2633 fd := create("/tmp/raz-sys-map");
2634 if (fd < 0) or (write(fd, "hello") # 5) then exit(2); end;
2635 close(fd);
2636 fd := openRead("/tmp/raz-sys-map");
2637 if (fd < 0) or (mapFile(fd, 5) # nil) then exit(2); end; (* shared and writable: not for a file open to read *)
2638 p := mapRead(fd, 5);
2639 if (p = nil) or (p[0..5] # "hello") then exit(2); end;
2640 munmap(p, 5);
2641 close(fd);
2642 _ := remove("/tmp/raz-sys-map");
2643 (* by 16 KB, a page of arm64 macOS's and four of x86-64's *)
2644 p := mmap(32768);
2645 if p = nil then exit(2); end;
2646 p[0] := 1;
2647 q := p + 16384;
2648 if (protect(q, 16384, true, false) # 0) or (q[0] # 0) then exit(2); end;
2649 if protect(q, 16384, true, true) # 0 then exit(2); end;
2650 q[0] := 2;
2651 if (protect(p, 16384, false, false) # 0) or (protect(p, 16384, true, true) # 0) or (p[0] # 1) then exit(2); end; (* its bytes stay *)
2652 munmap(p, 32768);
2653end;
2654
2655(* poll over 100 socket pairs with a byte sent on three, so that all
2656 three are reported in one call, at their places; a timeout, 0; a
2657 closed descriptor, ready, and -9 from a read; and an abstract Unix
2658 socket, whose name starts with a zero byte. *)
2659proc testPoll;
2660var a: [100]Poll; ends: [100]INT; ps: []Poll; nm: [18]U8; buf: [4]U8; x, y, r, i, l, c, s: INT;
2661begin
2662 for i := 0 to 99 do
2663 x, y, r := socketPair();
2664 if r # 0 then exit(2); end;
2665 a[i] := {fd: x, read: true};
2666 ends[i] := y;
2667 end;
2668 ps := a[0..100];
2669 if poll(ps, 0) # 0 then exit(2); end; (* a timeout *)
2670 for i := 3 to 77 by 37 do (* 3, 40, 77 *)
2671 if send(ends[i], "x") # 1 then exit(2); end;
2672 end;
2673 if poll(ps, 1000) # 3 then exit(2); end;
2674 for i := 0 to 99 do
2675 if a[i].ready # ((i = 3) or (i = 40) or (i = 77)) then exit(2); end;
2676 end;
2677 for i := 3 to 77 by 37 do
2678 if read(a[i].fd, buf) # 1 then exit(2); end;
2679 end;
2680 if poll(ps, 0) # 0 then exit(2); end;
2681 close(a[5].fd); (* not open: ready, and a read says why *)
2682 if (poll(ps, 0) # 1) or not a[5].ready or (read(a[5].fd, buf) # -9) then exit(2); end;
2683 for i := 0 to 99 do
2684 close(ends[i]);
2685 if i # 5 then close(a[i].fd); end;
2686 end;
2687 nm[0] := 0; (* an abstract name: a zero byte, then 17 *)
2688 COPY(nm[1..18], "raz-abstract-test");
2689 l := listen(nm);
2690 if CAbi.unixAbstract = 0 then (* not Linux: none *)
2691 if (l # -22) or (connect(nm) # -22) then exit(2); end;
2692 return;
2693 end;
2694 c := connect(nm);
2695 if (l < 0) or (c < 0) or (readyOf([c, l], 1000) # l) then exit(2); end;
2696 s := accept(l);
2697 if (s < 0) or (send(s, "x") # 1) or (readyOf([l, c], 1000) # c) then exit(2); end;
2698 close(s);
2699 close(c);
2700 close(l);
2701end;
2702
2703(* The module's test, as Linux's Sys has it: a file written, read back
2704 and closed; a directory made, listed and emptied; no terminal; a
2705 socket, sent to after its end; programs; time and the network. *)
2706proc main*;
2707var 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;
2708begin
2709 testPoll();
2710 fd := create("/tmp/raz-sys-test");
2711 if fd < 0 then exit(2); end;
2712 if write(fd, "hello") # 5 then exit(2); end;
2713 close(fd);
2714 fd := openRead("/tmp/raz-sys-test");
2715 if fd < 0 then exit(2); end;
2716 n := read(fd, buf);
2717 if (n # 5) or (buf[0..5] # "hello") or (read(fd, buf) # 0) then exit(2); end;
2718 close(fd);
2719 if openRead("/no/such/file") >= 0 then exit(2); end;
2720 if (errorText(-2) # "No such file or directory") or (errorText(13) # "Permission denied") then exit(2); end;
2721 if isTerminal(-1) then exit(2); end;
2722 p := mmap(100);
2723 if (p = nil) or (p[99] # 0) then exit(2); end;
2724 munmap(p, 100);
2725 (* files and directories *)
2726 _ := remove("/tmp/raz-sys-dir/f");
2727 _ := remove("/tmp/raz-sys-dir/g");
2728 _ := makeDir("/tmp/raz-sys-dir");
2729 fd := create("/tmp/raz-sys-dir/f");
2730 if (fd < 0) or (write(fd, "abc") # 3) then exit(2); end;
2731 close(fd);
2732 if rename("/tmp/raz-sys-dir/f", "/tmp/raz-sys-dir/g") # 0 then exit(2); end;
2733 i, err := info("/tmp/raz-sys-dir/g");
2734 if (err # 0) or (i.size # 3) or i.dir or not i.file or i.symlink then exit(2); end;
2735 i, err := info("/tmp/raz-sys-dir");
2736 if (err # 0) or not i.dir or i.file then exit(2); end;
2737 i, err := info("/dev/null");
2738 if (err # 0) or i.dir or i.file then exit(2); end;
2739 free, total, err := space("/tmp");
2740 if (err # 0) or (total <= 0) or (free < 0) or (free > total) then exit(2); end;
2741 free, total, err := space("/no/such/dir");
2742 if err # -2 then exit(2); end;
2743 _ := remove("/tmp/raz-sys-link");
2744 if symlink("/tmp/raz-sys-dir", "/tmp/raz-sys-link") # 0 then exit(2); end;
2745 i, err := info("/tmp/raz-sys-link");
2746 if (err # 0) or not i.dir or not i.symlink then exit(2); end;
2747 i, err := linkInfo("/tmp/raz-sys-link");
2748 if (err # 0) or i.dir or i.file or not i.symlink or (i.size # 16) then exit(2); end;
2749 i, err := linkInfo("/tmp/raz-sys-dir");
2750 if (err # 0) or not i.dir or i.symlink or (i.ino = 0) then exit(2); end;
2751 name, err := readLink("/tmp/raz-sys-link");
2752 if (err # 0) or (name # "/tmp/raz-sys-dir") then exit(2); end;
2753 name, err := readLink("/tmp/raz-sys-dir");
2754 if err # -22 then exit(2); end; (* EINVAL: not a link *)
2755 _ := remove("/tmp/raz-sys-link");
2756 if symlink("/no/such/file", "/tmp/raz-sys-link") # 0 then exit(2); end; (* dangling *)
2757 i, err := linkInfo("/tmp/raz-sys-link");
2758 if (err # 0) or not i.symlink or (i.size # 13) then exit(2); end;
2759 _ := remove("/tmp/raz-sys-link");
2760 (* open as asked, seek, the mode and the time *)
2761 _ := remove("/tmp/raz-sys-dir/h");
2762 fd := open("/tmp/raz-sys-dir/h", {writing, creating, exclusive});
2763 if (fd < 0) or (write(fd, "abc") # 3) then exit(2); end;
2764 close(fd);
2765 if open("/tmp/raz-sys-dir/h", {writing, creating, exclusive}) # -17 then exit(2); end;
2766 fd := open("/tmp/raz-sys-dir/h", {writing, appending});
2767 if (fd < 0) or (seek(fd, 0, false) # 0) or (write(fd, "de") # 2) then exit(2); end;
2768 close(fd);
2769 fd := open("/tmp/raz-sys-dir/h", {reading, writing});
2770 if (seek(fd, -2, true) # 3) or (read(fd, buf) # 2) or (buf[0..2] # "de") then exit(2); end;
2771 if (seek(fd, 1, false) # 1) or (write(fd, "B") # 1) or (seek(fd, 0, false) # 0) then exit(2); end;
2772 if (read(fd, buf) # 5) or (buf[0..5] # "aBcde") then exit(2); end;
2773 (* where it is, its size open, cut short, on the disk *)
2774 if (position(fd) # 5) or (seek(fd, 2, false) # 2) or (position(fd) # 2) then exit(2); end;
2775 if (truncate(fd, 4) # 0) or (position(fd) # 2) or (sync(fd) # 0) then exit(2); end;
2776 i, err := infoOf(fd);
2777 if (err # 0) or (i.size # 4) or not i.file or i.symlink then exit(2); end;
2778 m := INT(i.ino);
2779 i, err := info("/tmp/raz-sys-dir/h");
2780 if (err # 0) or (INT(i.ino) # m) or (syncAll(fd) # 0) then exit(2); end;
2781 if syncAll(-1) # -9 then exit(2); end; (* EBADF *)
2782 (* the lock: one open file holds it, another can't take it until
2783 the first is closed *)
2784 k := openRead("/tmp/raz-sys-dir/h");
2785 if (lock(fd, false) # 0) or (lock(k, false) # -11) then exit(2); end;
2786 close(fd);
2787 if lock(k, true) # 0 then exit(2); end;
2788 close(k);
2789 (* the shared lock: two open files hold it at once, lock is refused
2790 until both have gone, and a shared one while lock holds it *)
2791 fd := openRead("/tmp/raz-sys-dir/h");
2792 k := openRead("/tmp/raz-sys-dir/h");
2793 if (lockShared(fd, false) # 0) or (lockShared(k, true) # 0) then exit(2); end;
2794 o := openRead("/tmp/raz-sys-dir/h");
2795 if lock(o, false) # -11 then exit(2); end;
2796 close(fd);
2797 close(k);
2798 if lock(o, false) # 0 then exit(2); end;
2799 fd := openRead("/tmp/raz-sys-dir/h");
2800 if lockShared(fd, false) # -11 then exit(2); end;
2801 close(fd);
2802 close(o);
2803 if (position(fd) # -9) or (truncate(fd, 0) # -9) or (sync(fd) # -9) then exit(2); end; (* EBADF *)
2804 k := openRead("/tmp/raz-sys-dir/h");
2805 if (closeChecked(k) # 0) or (closeChecked(k) # -9) then exit(2); end;
2806 i, err := infoOf(fd);
2807 if err # -9 then exit(2); end;
2808 i, err := info("/tmp/raz-sys-dir/h");
2809 if (err # 0) or (i.mode & 1C0H # 180H) or (i.mtime < 1700000000 * 1000000000) then exit(2); end;
2810 if chmod("/tmp/raz-sys-dir/h", 1EDH) # 0 then exit(2); end;
2811 i, err := info("/tmp/raz-sys-dir/h");
2812 if i.mode # 1EDH then exit(2); end;
2813 (* setTime, after 1970 and before it, to the nanosecond *)
2814 if setTime("/tmp/raz-sys-dir/h", 1234567890, 123456789) # 0 then exit(2); end;
2815 i, err := info("/tmp/raz-sys-dir/h");
2816 if (i.mtime # 1234567890123456789) or (i.seconds # 1234567890) then exit(2); end;
2817 if setTime("/tmp/raz-sys-dir/h", -2, 500000000) # 0 then exit(2); end;
2818 i, err := info("/tmp/raz-sys-dir/h");
2819 if (i.mtime # -1500000000) or (i.seconds # -2) then exit(2); end;
2820 if setTime("/tmp/raz-sys-dir/h", 10413792000, 0) # 0 then exit(2); end; (* 2300, past mtime's reach *)
2821 i, err := info("/tmp/raz-sys-dir/h");
2822 (* exact, or, where the file system keeps no time past 2262, as
2823 APFS, which holds nanoseconds in 64 bits, its last second *)
2824 if (i.seconds # 10413792000) and (i.seconds # 9223372036) then exit(2); end;
2825 if setTime("/tmp/raz-sys-dir/h", 0, 1000000000) # -22 then exit(2); end;
2826 if setTime("/no/such/file", 0, 0) # -2 then exit(2); end;
2827 (* the special bits: set-user-id by chmod, and sticky by makeDirMode *)
2828 if chmod("/tmp/raz-sys-dir/h", 9EDH) # 0 then exit(2); end;
2829 i, err := info("/tmp/raz-sys-dir/h");
2830 if (i.mode # 1EDH) or (i.special # 800H) then exit(2); end;
2831 if makeDirMode("/tmp/raz-sys-dir/m", 3C0H) # 0 then exit(2); end;
2832 i, err := info("/tmp/raz-sys-dir/m");
2833 (* Linux gives it sticky, macOS doesn't, and chmod does *)
2834 if (err # 0) or not i.dir or (i.mode # 1C0H) or (i.special & ~200H # 0) then exit(2); end;
2835 if chmod("/tmp/raz-sys-dir/m", 3C0H) # 0 then exit(2); end;
2836 i, err := info("/tmp/raz-sys-dir/m");
2837 if (err # 0) or (i.special # 200H) then exit(2); end;
2838 if removeDir("/tmp/raz-sys-dir/m") # 0 then exit(2); end;
2839 _ := remove("/tmp/raz-sys-dir/h");
2840 fd := openMode("/tmp/raz-sys-dir/h", {writing, creating}, 1C0H); (* rwx------ *)
2841 close(fd);
2842 i, err := info("/tmp/raz-sys-dir/h");
2843 if (fd < 0) or (err # 0) or (i.mode # 1C0H) then exit(2); end;
2844 _ := remove("/tmp/raz-sys-dir/h");
2845 i, err := info("/no/such/file");
2846 if err >= 0 then exit(2); end;
2847 if openDir(d, "/tmp/raz-sys-dir") # 0 then exit(2); end;
2848 name, ok := nextEntry(d);
2849 if not ok or (name # "g") then exit(2); end;
2850 if (entryKind(d) # isFile) and (entryKind(d) # unknown) then exit(2); end;
2851 i, err := info("/tmp/raz-sys-dir/g");
2852 j, err := info("/tmp/raz-sys-dir");
2853 if (err # 0) or (i.dev # j.dev) or (i.ino = j.ino) or (i.links # 1) then exit(2); end;
2854 name, ok := nextEntry(d);
2855 if ok then exit(2); end;
2856 closeDir(d);
2857 if (remove("/tmp/raz-sys-dir/g") # 0) or (remove("/tmp/raz-sys-dir/g") >= 0) then exit(2); end;
2858 if openDir(d, "/no/such/dir") >= 0 then exit(2); end;
2859 (* the terminal: none here, fd -1 *)
2860 if rawMode(-1) or ready(-1, 0) then exit(2); end;
2861 w, h := termSize(-1);
2862 if (w # 80) or (h # 24) then exit(2); end;
2863 (* the environment *)
2864 if (LEN(env("PATH")) = 0) or (LEN(env("RAZ_NO_SUCH_VARIABLE")) # 0) then exit(2); end;
2865 (* the environment set: refused, added, set again, grown past its first array *)
2866 if (setEnv("", "x") # -22) or (setEnv("A=B", "x") # -22) or (setEnv("A", "\x00") # -22) then exit(2); end;
2867 if (setEnv("RAZ_SYS_TEST", "one") # 0) or (env("RAZ_SYS_TEST") # "one") then exit(2); end;
2868 (* what env gave before may be gone now: macOS's setenv writes the
2869 new value over the old where it fits *)
2870 if (setEnv("RAZ_SYS_TEST", "") # 0) or (env("RAZ_SYS_TEST") # "") then exit(2); end;
2871 buf := "RAZ_SYS_TEST_..";
2872 for k := 0 to 99 do
2873 buf[13] := U8('0' + k div 10);
2874 buf[14] := U8('0' + k mod 10);
2875 if setEnv(buf[0..15], buf[13..15]) # 0 then exit(2); end;
2876 end;
2877 if (env("RAZ_SYS_TEST_42") # "42") or (env("RAZ_SYS_TEST") # "") or (LEN(env("PATH")) = 0) then exit(2); end;
2878 n := 0;
2879 k := 0;
2880 repeat
2881 name, ok := envAt(k);
2882 if (LEN(name) > 12) and (name[0..12] = "RAZ_SYS_TEST") then INC(n); end;
2883 INC(k);
2884 until not ok;
2885 if n # 101 then exit(2); end;
2886 name, err := workDir();
2887 if (err # 0) or (LEN(name) = 0) or (name[0] # '/') then exit(2); end;
2888 if (setWorkDir("/tmp/raz-sys-dir") # 0) or (removeDir("/tmp/raz-sys-dir") # 0) then exit(2); end;
2889 if (setWorkDir("/") # 0) or (removeDir("/tmp/raz-sys-dir") # -2) then exit(2); end;
2890 (* a socket: nothing at a path, then a listener that a connection
2891 makes ready, and a byte from it to the connection *)
2892 if connect("/tmp/raz-no-such-socket") # -2 then exit(2); end; (* ENOENT *)
2893 _ := remove("/tmp/raz-sys-socket");
2894 l := listen("/tmp/raz-sys-socket");
2895 if (l < 0) or (listen("/tmp/raz-sys-socket") # -98) then exit(2); end; (* EADDRINUSE: there already *)
2896 c := connect("/tmp/raz-sys-socket");
2897 if c < 0 then exit(2); end;
2898 if readyOf([c], 0) # -1 then exit(2); end;
2899 if readyOf([c, l], 1000) # l then exit(2); end;
2900 a := accept(l);
2901 if (a < 0) or (send(a, "x") # 1) or (readyOf([l, c], 1000) # c) then exit(2); end;
2902 if (read(c, buf) # 1) or (buf[0] # 'x') then exit(2); end;
2903 close(a);
2904 if (readyOf([c], 1000) # c) or (read(c, buf) # 0) then exit(2); end; (* its end *)
2905 if send(c, "x") # -32 then exit(2); end; (* EPIPE, and no SIGPIPE *)
2906 close(c);
2907 close(l);
2908 _ := remove("/tmp/raz-sys-socket");
2909 (* a file in memory, mapped, and passed with a byte down a socket
2910 twice, with room for one: what the other side maps is the same *)
2911 m := memFile(8192);
2912 p := mapFile(m, 8192);
2913 if (m < 0) or (p = nil) or (p[8191] # 0) then exit(2); end;
2914 p[100] := 42;
2915 l := listen("/tmp/raz-sys-socket");
2916 c := connect("/tmp/raz-sys-socket");
2917 a := accept(l);
2918 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;
2919 n, k := receiveFds(a, buf, got);
2920 if (n # 1) or (k # 1) or (buf[0] # 'f') then exit(2); end;
2921 q := mapFile(got[0], 8192);
2922 if (q = nil) or (q[100] # 42) then exit(2); end;
2923 q[200] := 7;
2924 if p[200] # 7 then exit(2); end;
2925 munmap(p, 8192);
2926 munmap(q, 8192);
2927 close(got[0]);
2928 close(m);
2929 close(a);
2930 close(c);
2931 close(l);
2932 _ := remove("/tmp/raz-sys-socket");
2933 testPrograms;
2934 testShell;
2935 testNet;
2936 testProcess;
2937 testGiveUp;
2938 testServer;
2939 testMaps;
2940end;
2941
2942end Sys.