From 55bc6c0d6259db84244248bab75c2e3caa4dd65d Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Wed, 14 Oct 2026 13:09:09 +0100 Subject: [PATCH] sbcl: the whole library of volume 2 Heap, Arena, Buf, Fmt, List, Map, Sort, Math, Files, Opt, Thread, Bytes and the rest of Sys: directories, the terminal, polling, programs, signals and sockets. Fixes: volatile scalars assign, FENCE alone, ^T(x) takes selectors, code bodies only after a signature. --- diff --git a/sbcl/lib/Arena.raz b/sbcl/lib/Arena.raz new file mode 100644 index 0000000..ec99954 --- /dev/null +++ b/sbcl/lib/Arena.raz @@ -0,0 +1,54 @@ +(* An allocator that hands out memory from one block: its free does + nothing, and reset forgets everything at once. *) +module Arena; +import Mem; + +type Arena* = record + base*: Mem.Allocator; (* first, so that ^Arena(a) finds the rest *) + mem: ^U8; + size, used: INT; +end; + +proc alloc(a: ^Mem.Allocator; size, align: INT): ^U8; +var ar: ^Arena; start: INT; +begin + ar := ^Arena(a); + start := (ar^.used + align - 1) div align * align; + if start + size > ar^.size then return nil; end; + ar^.used := start + size; + return ar^.mem + start; +end; + +proc free(a: ^Mem.Allocator; p: ^U8); +begin +end; + +(* an arena of size bytes; false if the system has none *) +proc init*(ar: ^Arena; size: INT): BOOL; +begin + ar^.base.alloc := alloc; + ar^.base.free := free; + ar^.mem := Mem.pages(size); + ar^.size := size; + ar^.used := 0; + return ar^.mem # nil; +end; + +(* every allocation forgotten; the memory used again, zeroed *) +proc reset*(ar: ^Arena); +var i: INT; +begin + for i := 0 to ar^.used - 1 do ar^.mem[i] := 0; end; + ar^.used := 0; +end; + +(* its memory given back *) +proc done*(ar: ^Arena); +begin + if ar^.mem # nil then Mem.unmap(ar^.mem, ar^.size); end; + ar^.mem := nil; + ar^.size := 0; + ar^.used := 0; +end; + +end Arena. diff --git a/sbcl/lib/Buf.raz b/sbcl/lib/Buf.raz new file mode 100644 index 0000000..0b4793a --- /dev/null +++ b/sbcl/lib/Buf.raz @@ -0,0 +1,75 @@ +(* A growable byte buffer, its memory from the allocator init gives it. *) +module Buf; +import Mem; + +type Buf* = record + len*: INT; + data: ^U8; + cap: INT; + a: ^Mem.Allocator; +end; + +proc init*(b: ^Buf; a: ^Mem.Allocator); +begin + b^.len := 0; + b^.data := nil; + b^.cap := 0; + b^.a := a; +end; + +(* room for n more bytes; false if the allocator has none *) +proc room*(b: ^Buf; n: INT): BOOL; +var cap: INT; p: ^U8; +begin + if b^.len + n <= b^.cap then return true; end; + cap := b^.cap * 2; + if cap < 64 then cap := 64; end; + while cap < b^.len + n do cap := cap * 2; end; + p := Mem.alloc(b^.a, cap, 1); + if p = nil then return false; end; + if b^.len > 0 then COPY(p[0..b^.len], b^.data[0..b^.len]); end; + if b^.data # nil then Mem.free(b^.a, b^.data); end; + b^.data := p; + b^.cap := cap; + return true; +end; + +proc add*(b: ^Buf; c: U8); +begin + if room(b, 1) then + b^.data[b^.len] := c; + INC(b^.len); + end; +end; + +proc str*(b: ^Buf; s: []U8); +begin + if room(b, LEN(s)) then + COPY(b^.data[b^.len..b^.len + LEN(s)], s); + b^.len := b^.len + LEN(s); + end; +end; + +(* what it holds, until it next grows *) +proc bytes*(b: ^Buf): []U8; +begin + if b^.data = nil then return ""; end; + return b^.data[0..b^.len]; +end; + +(* emptied, its memory kept *) +proc reset*(b: ^Buf); +begin + b^.len := 0; +end; + +(* its memory given back *) +proc done*(b: ^Buf); +begin + if b^.data # nil then Mem.free(b^.a, b^.data); end; + b^.data := nil; + b^.len := 0; + b^.cap := 0; +end; + +end Buf. diff --git a/sbcl/lib/Bytes.raz b/sbcl/lib/Bytes.raz new file mode 100644 index 0000000..7eede6f --- /dev/null +++ b/sbcl/lib/Bytes.raz @@ -0,0 +1,44 @@ +(* Searches of bytes in a []U8. *) +module Bytes; + +(* where b first is in s, or -1 *) +proc index*(s: []U8; b: U8): INT; +var i: INT; +begin + for i := 0 to LEN(s) - 1 do + if s[i] = b then return i; end; + end; + return -1; +end; + +(* where b last is in s, or -1 *) +proc last*(s: []U8; b: U8): INT; +var i: INT; +begin + for i := LEN(s) - 1 to 0 by -1 do + if s[i] = b then return i; end; + end; + return -1; +end; + +(* how many times b is in s *) +proc count*(s: []U8; b: U8): INT; +var i, n: INT; +begin + for i := 0 to LEN(s) - 1 do + if s[i] = b then INC(n); end; + end; + return n; +end; + +(* where sub first starts in s, or -1 *) +proc find*(s, sub: []U8): INT; +var i: INT; +begin + for i := 0 to LEN(s) - LEN(sub) do + if s[i..i + LEN(sub)] = sub then return i; end; + end; + return -1; +end; + +end Bytes. diff --git a/sbcl/lib/Files.raz b/sbcl/lib/Files.raz new file mode 100644 index 0000000..728fd91 --- /dev/null +++ b/sbcl/lib/Files.raz @@ -0,0 +1,46 @@ +(* An argument as a string, and a whole file read or written. *) +module Files; +import Sys, Buf; + +(* argument i; 0 is the program's name *) +proc arg*(i: INT): []U8; +var s: ^U8; n: INT; +begin + if i < 0 or i >= ARGC() then return ""; end; + s := ARGV()[i]; + while s[n] # 0 do INC(n); end; + return s[0..n]; +end; + +(* the whole file added to b *) +proc read*(path: []U8; b: ^Buf.Buf): BOOL; +var fd, n: INT; chunk: [4096]U8; +begin + fd := Sys.openRead(path); + if fd < 0 then return false; end; + defer Sys.close(fd); + n := Sys.read(fd, chunk); + while n > 0 do + if not Buf.room(b, n) then return false; end; + Buf.str(b, chunk[0..n]); + n := Sys.read(fd, chunk); + end; + return n = 0; +end; + +(* the file made to hold data *) +proc write*(path, data: []U8): BOOL; +var fd, n, done: INT; +begin + fd := Sys.create(path); + if fd < 0 then return false; end; + defer Sys.close(fd); + while done < LEN(data) do + n := Sys.write(fd, data[done..LEN(data)]); + if n <= 0 then return false; end; + done := done + n; + end; + return true; +end; + +end Files. diff --git a/sbcl/lib/Fmt.raz b/sbcl/lib/Fmt.raz new file mode 100644 index 0000000..13a0e97 --- /dev/null +++ b/sbcl/lib/Fmt.raz @@ -0,0 +1,146 @@ +(* Formatted output: Fmt.print("{} of {}\n", [Fmt.int(n), Fmt.real(x, 2)]), + or into a Buf with Fmt.write. Each {} takes the next argument; {{ and + }} stand for { and }. *) +module Fmt; +import Out, Buf; + +type Arg* = variant + int(i: I64); + uint(u: U64); + hex(h: U64); + str(s: []U8); + char(c: U8); + bool(b: BOOL); + real(r: F64; places: INT); +end; + +const digits = "0123456789ABCDEF"; + +(* Text is made in a Piece before it goes out, a piece at a time. *) +type Piece = record bytes: [64]U8; len: INT; end; + +proc add(p: ^Piece; c: U8); +begin + p^.bytes[p^.len] := c; + INC(p^.len); +end; + +(* u in base, at least min digits *) +proc unsigned(p: ^Piece; u: U64; base: U64; min: INT); +var d: [20]U8; n: INT; +begin + repeat + d[n] := digits[INT(u mod base)]; + u := u div base; + INC(n); + until u = 0; + while n < min do d[n] := '0'; INC(n); end; + while n > 0 do DEC(n); add(p, d[n]); end; +end; + +proc signed(p: ^Piece; i: I64); +begin + if i < 0 then add(p, '-'); unsigned(p, 0 - U64(i), 10, 1); + else unsigned(p, U64(i), 10, 1); + end; +end; + +(* x, at least 0 and below 1e15, with places digits after the point *) +proc fixed(p: ^Piece; x: F64; places: INT); +var whole, scale: F64; ip, frac, one: U64; i: INT; +begin + one := 1; + for i := 1 to places do one := one * 10; end; + scale := F64(one); + ip := U64(x); + whole := F64(ip); + frac := U64((x - whole) * scale + 0.5); + if frac >= one then INC(ip); frac := frac - one; end; + unsigned(p, ip, 10, 1); + if places > 0 then + add(p, '.'); + unsigned(p, frac, 10, places); + end; +end; + +proc writeReal(p: ^Piece; x: F64; places: INT); +var e, i: INT; m: F64; q: Piece; +begin + if places < 0 then places := 0; end; + if places > 9 then places := 9; end; + if x # x then add(p, 'n'); add(p, 'a'); add(p, 'n'); return; end; + if x < 0.0 or (x = 0.0 and 1.0 / x < 0.0) then add(p, '-'); x := -x; end; + if x > 1.7976931348623157E308 then add(p, 'i'); add(p, 'n'); add(p, 'f'); return; end; + if x < 1.0E15 then fixed(p, x, places); return; end; + (* m times ten to the e, m from 1 to 10 *) + m := x; + while m >= 10.0 do m := m / 10.0; INC(e); end; + fixed(ADR(q), m, places); + if q.bytes[0] = '1' and q.bytes[1] = '0' then + (* m rounded up to 10 *) + q.len := 0; + fixed(ADR(q), m / 10.0, places); + INC(e); + end; + for i := 0 to q.len - 1 do add(p, q.bytes[i]); end; + add(p, 'e'); + signed(p, I64(e)); +end; + +(* The text of each piece of f, and of each argument, given to put. *) +proc format(f: []U8; args: []Arg; out: proc(s: []U8; b: ^Buf.Buf); b: ^Buf.Buf); +var i, start, next: INT; p: Piece; +begin + while i < LEN(f) do + if (f[i] = '{' or f[i] = '}') and i + 1 < LEN(f) and f[i + 1] = f[i] then + out(f[start..i + 1], b); + i := i + 2; + start := i; + elsif f[i] = '{' and i + 1 < LEN(f) and f[i + 1] = '}' then + out(f[start..i], b); + if next < LEN(args) then + p.len := 0; + match args[next] of + | int(n): signed(ADR(p), n); + | uint(u): unsigned(ADR(p), u, 10, 1); + | hex(h): unsigned(ADR(p), h, 16, 1); + | str(s): out(s, b); + | char(c): add(ADR(p), c); + | bool(v): if v then out("true", b); else out("false", b); end; + | real(x, places): writeReal(ADR(p), x, places); + end; + out(p.bytes[0..p.len], b); + INC(next); + end; + i := i + 2; + start := i; + else + INC(i); + end; + end; + out(f[start..LEN(f)], b); +end; + +proc toOut(s: []U8; b: ^Buf.Buf); +begin + Out.str(s); +end; + +proc toBuf(s: []U8; b: ^Buf.Buf); +begin + Buf.str(b, s); +end; + +(* to standard output *) +proc print*(f: []U8; args: []Arg); +begin + format(f, args, toOut, nil); +end; + +(* added to b *) +proc write*(b: ^Buf.Buf; f: []U8; args: []Arg); +begin + format(f, args, toBuf, b); +end; + +end Fmt. diff --git a/sbcl/lib/Heap.raz b/sbcl/lib/Heap.raz new file mode 100644 index 0000000..7d1f95c --- /dev/null +++ b/sbcl/lib/Heap.raz @@ -0,0 +1,117 @@ +(* A general allocator, Heap.heap, safe to call from several threads. + + A small block comes from one of eight free lists, by its size: 16 to + 2048 bytes, each twice the one before, a header of 16 bytes included. + The lists are filled from chunks of pages. A big block, or one aligned + to more than 16 bytes, has pages of its own. The header says which + list a block belongs to, or how many bytes of pages it has, and + whether it is given out: freeing a block twice, or one the heap never + gave, stops the program. *) +module Heap; +import Mem, Lock, Rt; + +const + classes = 8; (* the free lists: blocks of 16 shl i bytes *) + chunkSize = 65536; (* the pages a list is filled from at once *) + given = 0A110CA7EDH; (* a header's mark for a block given out *) + freed = 0F7EEDH; (* and for one on a free list *) + +type + Header = record + size: INT; (* the list, from 0; or minus the bytes of the block's own pages *) + mark: INT; (* given or freed *) + end; + Free = record next: ^Free; end; (* a block on a free list, past its header *) + +var + allocator: Mem.Allocator; + heap*: ^Mem.Allocator; + lists: [classes]^Free; + lock: Lock.Lock; + +(* A block with pages of its own: the header sits just before the + aligned start. *) +proc big(size, align: INT): ^U8; +var bytes, lead: INT; p: ^U8; h: ^Header; base: ^^U8; +begin + lead := 16; + if align > 16 then lead := align; end; + bytes := (size + lead + Mem.Page - 1) div Mem.Page * Mem.Page; + p := Mem.pages(bytes); + if p = nil then return nil; end; + p := p + lead; + (* past an alignment's lead, the pages' start, for free *) + if lead > 16 then base := ^^U8(p - 24); base^ := p - lead; end; + h := ^Header(p - 16); + h^.size := -bytes; + h^.mark := given; + return p; +end; + +(* List c filled from a new chunk; false if the system has no room. *) +proc fill(c: INT): BOOL; +var chunk: ^U8; size, i: INT; f: ^Free; h: ^Header; +begin + chunk := Mem.pages(chunkSize); + if chunk = nil then return false; end; + size := 16 shl c; + for i := 0 to chunkSize div size - 1 do + h := ^Header(chunk + i * size); + h^.size := c; + h^.mark := freed; + f := ^Free(chunk + i * size + 16); + f^.next := lists[c]; + lists[c] := f; + end; + return true; +end; + +proc alloc(a: ^Mem.Allocator; size, align: INT): ^U8; +var c: INT; f: ^Free; h: ^Header; +begin + (* a size the memory can't hold, or an alignment that isn't a power + of 2 up to a page, is refused *) + if size < 0 or size > 1 shl 46 or align <= 0 or align > Mem.Page or align & (align - 1) # 0 then + return nil; + end; + if size + 16 > 16 shl (classes - 1) or align > 16 then return big(size, align); end; + c := 0; + while 16 shl c < size + 16 do INC(c); end; + Lock.take(ADR(lock)); + if lists[c] = nil and not fill(c) then Lock.give(ADR(lock)); return nil; end; + f := lists[c]; + lists[c] := f^.next; + h := ^Header(^U8(f) - 16); + h^.mark := given; + Lock.give(ADR(lock)); + return ^U8(f); +end; + +proc free(a: ^Mem.Allocator; p: ^U8); +var h: ^Header; f: ^Free; +begin + if p = nil then return; end; + h := ^Header(p - 16); + if h^.mark # given then Rt.stop("Heap: a block freed twice, or one the heap never gave"); end; + if h^.size < 0 then + h^.mark := 0; + if INT(p) mod Mem.Page = 16 then + Mem.unmap(p - 16, -h^.size); + else + Mem.unmap(^^U8(p - 24)^, -h^.size); + end; + return; + end; + Lock.take(ADR(lock)); + h^.mark := freed; + f := ^Free(p); + f^.next := lists[h^.size]; + lists[h^.size] := f; + Lock.give(ADR(lock)); +end; + +begin + allocator.alloc := alloc; + allocator.free := free; + heap := ADR(allocator); +end Heap. diff --git a/sbcl/lib/List.raz b/sbcl/lib/List.raz new file mode 100644 index 0000000..73b0437 --- /dev/null +++ b/sbcl/lib/List.raz @@ -0,0 +1,68 @@ +(* A generic singly linked list, its nodes from an allocator. *) +module List(T); +import Mem; + +type + Node* = record next*: ^Node; val*: T; end; + List* = record head*: ^Node; len*: INT; a: ^Mem.Allocator; end; + +proc init*(l: ^List; a: ^Mem.Allocator); +begin + l^.head := nil; + l^.len := 0; + l^.a := a; +end; + +(* v at the front; false if the allocator has no room *) +proc push*(l: ^List; v: T): BOOL; +var n: ^Node; +begin + NEW(n, l^.a); + if n = nil then return false; end; + n^.val := v; + n^.next := l^.head; + l^.head := n; + INC(l^.len); + return true; +end; + +(* the front value, taken off; false if the list is empty *) +proc pop*(l: ^List): (T, BOOL); +var n: ^Node; v: T; +begin + n := l^.head; + if n = nil then return v, false; end; + v := n^.val; + l^.head := n^.next; + DEC(l^.len); + Mem.free(l^.a, ^U8(n)); + return v, true; +end; + +proc reverse*(l: ^List); +var prev, n, next: ^Node; +begin + n := l^.head; + while n # nil do + next := n^.next; + n^.next := prev; + prev := n; + n := next; + end; + l^.head := prev; +end; + +proc clear*(l: ^List); +var n, next: ^Node; +begin + n := l^.head; + while n # nil do + next := n^.next; + Mem.free(l^.a, ^U8(n)); + n := next; + end; + l^.head := nil; + l^.len := 0; +end; + +end List. diff --git a/sbcl/lib/Map.raz b/sbcl/lib/Map.raz new file mode 100644 index 0000000..ed30b90 --- /dev/null +++ b/sbcl/lib/Map.raz @@ -0,0 +1,124 @@ +(* A generic hash map, open addressing with linear probing; it hashes and + compares its keys with the procedures it is given. *) +module Map(K, V; hash: proc(k: K): U64; eq: proc(a, b: K): BOOL); +import Mem; + +type + Entry = record key: K; val: V; used: BOOL; end; + Map* = record + len*: INT; + slots: ^Entry; (* cap of them; cap is 0 or a power of 2 *) + cap: INT; + a: ^Mem.Allocator; + end; + +proc init*(m: ^Map; a: ^Mem.Allocator); +begin + m^.len := 0; + m^.slots := nil; + m^.cap := 0; + m^.a := a; +end; + +(* the slot of k: where it is, or the free slot it would go in *) +proc slot(m: ^Map; k: K): INT; +var i: INT; +begin + i := INT(hash(k) & U64(m^.cap - 1)); + while m^.slots[i].used and not eq(m^.slots[i].key, k) do + i := (i + 1) & (m^.cap - 1); + end; + return i; +end; + +(* twice the slots, every entry moved; false if there is no room *) +proc grow(m: ^Map): BOOL; +var old: ^Entry; n, i, j, cap: INT; p: ^U8; +begin + cap := m^.cap * 2; + if cap = 0 then cap := 8; end; + p := Mem.alloc(m^.a, cap * SIZE(Entry), 8); + if p = nil then return false; end; + for i := 0 to cap * SIZE(Entry) - 1 do p[i] := 0; end; + old := m^.slots; + n := m^.cap; + m^.slots := ^Entry(p); + m^.cap := cap; + for i := 0 to n - 1 do + if old[i].used then + j := slot(m, old[i].key); + m^.slots[j] := old[i]; + end; + end; + if old # nil then Mem.free(m^.a, ^U8(old)); end; + return true; +end; + +(* k now maps to v; false if there was no room *) +proc put*(m: ^Map; k: K; v: V): BOOL; +var i: INT; +begin + if (m^.len + 1) * 4 > m^.cap * 3 and not grow(m) then return false; end; + i := slot(m, k); + if not m^.slots[i].used then + m^.slots[i].used := true; + m^.slots[i].key := k; + INC(m^.len); + end; + m^.slots[i].val := v; + return true; +end; + +(* the slot k's hash points at *) +proc home(m: ^Map; k: K): INT; +begin + return INT(hash(k) & U64(m^.cap - 1)); +end; + +(* false if k wasn't there *) +proc remove*(m: ^Map; k: K): BOOL; +var i, j, h: INT; +begin + if m^.cap = 0 then return false; end; + i := slot(m, k); + if not m^.slots[i].used then return false; end; + m^.slots[i].used := false; + DEC(m^.len); + (* each entry after it in the run moves back into the hole, unless its + home is between the hole and where it is *) + j := (i + 1) & (m^.cap - 1); + while m^.slots[j].used do + h := home(m, m^.slots[j].key); + if (j > i and (h <= i or h > j)) or (j < i and h <= i and h > j) then + m^.slots[i] := m^.slots[j]; + m^.slots[j].used := false; + i := j; + end; + j := (j + 1) & (m^.cap - 1); + end; + return true; +end; + +(* what k maps to, and whether it maps to anything *) +proc get*(m: ^Map; k: K): (V, BOOL); +var i: INT; v: V; +begin + if m^.cap = 0 then return v, false; end; + i := slot(m, k); + if not m^.slots[i].used then return v, false; end; + return m^.slots[i].val, true; +end; + +(* the entry after i: from 0, the next entry and the number to pass for + the one after it; -1 when there are no more *) +proc next*(m: ^Map; i: INT): (INT, K, V); +var k: K; v: V; +begin + while i < m^.cap do + if m^.slots[i].used then return i + 1, m^.slots[i].key, m^.slots[i].val; end; + INC(i); + end; + return -1, k, v; +end; + +end Map. diff --git a/sbcl/lib/Math.raz b/sbcl/lib/Math.raz new file mode 100644 index 0000000..8783ff0 --- /dev/null +++ b/sbcl/lib/Math.raz @@ -0,0 +1,93 @@ +(* Roots, powers, logarithms, rounding and trigonometry, for F64: C's + math.h, called through the run time. *) +module Math; + +const pi* = 3.141592653589793; + +proc sqrt*(x: F64): F64; +code + (c-call "sqrt" double-float double-float x); +end; + +(* x to the power y *) +proc pow*(x, y: F64): F64; +code + (c-call "pow" double-float double-float x double-float y); +end; + +proc floor*(x: F64): F64; +code + (c-call "floor" double-float double-float x); +end; + +proc ceil*(x: F64): F64; +code + (c-call "ceil" double-float double-float x); +end; + +(* to the nearest whole number; a half away from 0 *) +proc round*(x: F64): F64; +code + (c-call "round" double-float double-float x); +end; + +proc exp*(x: F64): F64; +code + (c-call "exp" double-float double-float x); +end; + +proc ln*(x: F64): F64; +code + (c-call "log" double-float double-float x); +end; + +proc log2*(x: F64): F64; +code + (c-call "log2" double-float double-float x); +end; + +proc log10*(x: F64): F64; +code + (c-call "log10" double-float double-float x); +end; + +proc sin*(x: F64): F64; +code + (c-call "sin" double-float double-float x); +end; + +proc cos*(x: F64): F64; +code + (c-call "cos" double-float double-float x); +end; + +proc tan*(x: F64): F64; +code + (c-call "tan" double-float double-float x); +end; + +(* from -pi/2 to pi/2 *) +proc asin*(x: F64): F64; +code + (c-call "asin" double-float double-float x); +end; + +(* from 0 to pi *) +proc acos*(x: F64): F64; +code + (c-call "acos" double-float double-float x); +end; + +(* from -pi/2 to pi/2 *) +proc atan*(x: F64): F64; +code + (c-call "atan" double-float double-float x); +end; + +(* the angle of (x, y) from the x axis, from -pi to pi *) +proc atan2*(y, x: F64): F64; +code + (c-call "atan2" double-float double-float y double-float x); +end; + +end Math. diff --git a/sbcl/lib/Opt.raz b/sbcl/lib/Opt.raz new file mode 100644 index 0000000..891b769 --- /dev/null +++ b/sbcl/lib/Opt.raz @@ -0,0 +1,362 @@ +(* A command line read through one table, by getopt's rules with GNU's + long options; the help and the mistakes are made from the table. + + The parser walks the arguments with arg, the next word, and pos, the + next letter in a group such as -lw (0 outside one). Each step is read + by step, which never ends the program: init and scope use it to look + ahead for -h and --help, and next to read the options one by one. *) +module Opt; +import Out, Sys, Rt, Str, Buf, Heap, Files; + +type + Row* = variant + usage(scope, line: []U8); (* a synopsis line, without "usage: " *) + sub(scope, name, help: []U8); (* a subcommand *) + option(scope: []U8; letter: U8; long, value, help: []U8); + end; + Parser* = record + letter*: U8; (* the option just read *) + value*: []U8; (* its value; "" for a flag *) + long*: BOOL; (* it was written by its long name *) + name: []U8; (* the program's *) + table: []Row; + scope: []U8; + arg, pos: INT; + ended: BOOL; (* the options have ended: what is left are operands *) + end; + Step = (anOption, theEnd, aHelp, aMistake); (* what step read *) + +var text: Buf.Buf; (* a mistake's sentence, as step makes it *) + +(* What an option row says, if row r is an option of scope s. *) +proc optionOf(r: Row; s: []U8): (BOOL, U8, []U8, []U8); +begin + match r of + | option(scope, letter, long, value, help): + if scope = s then return true, letter, long, value; end; + | else: + end; + return false, 0, "", ""; +end; + +proc say(s: []U8); +begin + Buf.str(ADR(text), s); +end; + +(* The option of p's scope with the letter c (or, if c is 0, the long + name n): its row, or -1. *) +proc find(p: ^Parser; c: U8; n: []U8): INT; +var i: INT; is: BOOL; letter: U8; long, value: []U8; +begin + for i := 0 to LEN(p^.table) - 1 do + is, letter, long, value := optionOf(p^.table[i], p^.scope); + if is and ((c # 0 and letter = c) or (c = 0 and LEN(n) > 0 and long = n)) then return i; end; + end; + return -1; +end; + +(* The next option of p, by getopt's rules. *) +proc step(p: ^Parser): Step; +var w, n: []U8; i, eq: INT; is: BOOL; letter: U8; long, value: []U8; +begin + Buf.reset(ADR(text)); + p^.value := ""; + p^.long := false; + if p^.ended or p^.arg >= ARGC() then return theEnd; end; + w := Files.arg(p^.arg); + if p^.pos = 0 then + if w = "--" then INC(p^.arg); p^.ended := true; return theEnd; end; + if LEN(w) < 2 or w[0] # '-' then return theEnd; end; + if w[1] = '-' then + (* --name, --name=value or --name value *) + INC(p^.arg); + eq := 2; + while eq < LEN(w) and w[eq] # '=' do INC(eq); end; + n := w[2..eq]; + if n = "help" then return aHelp; end; + i := find(p, 0, n); + if i < 0 then say("unknown option --"); say(n); return aMistake; end; + is, letter, long, value := optionOf(p^.table[i], p^.scope); + p^.letter := letter; + p^.long := true; + if LEN(value) = 0 then + if eq < LEN(w) then say("--"); say(n); say(" takes no value"); return aMistake; end; + elsif eq < LEN(w) then + p^.value := w[eq + 1..LEN(w)]; + elsif p^.arg < ARGC() then + p^.value := Files.arg(p^.arg); + INC(p^.arg); + else + say("--"); say(n); say(" needs a "); say(value); return aMistake; + end; + return anOption; + end; + p^.pos := 1; + end; + (* a letter of a group *) + letter := w[p^.pos]; + INC(p^.pos); + if p^.pos = LEN(w) then p^.pos := 0; INC(p^.arg); end; + if letter = 'h' then return aHelp; end; + i := find(p, letter, ""); + if i < 0 or letter < '!' then say("unknown option -"); Buf.add(ADR(text), letter); return aMistake; end; + is, letter, long, value := optionOf(p^.table[i], p^.scope); + p^.letter := letter; + if LEN(value) > 0 then + (* the rest of the word, or the whole next word *) + if p^.pos > 0 then + p^.value := w[p^.pos..LEN(w)]; + p^.pos := 0; + INC(p^.arg); + elsif p^.arg < ARGC() then + p^.value := Files.arg(p^.arg); + INC(p^.arg); + else + say("-"); Buf.add(ADR(text), letter); say(" needs a "); say(value); return aMistake; + end; + end; + return anOption; +end; + +(* The words of the scope's name, "remote.add" as "remote add". *) +proc scopeWords(p: ^Parser; b: ^Buf.Buf); +var i: INT; +begin + for i := 0 to LEN(p^.scope) - 1 do + if p^.scope[i] = '.' then Buf.add(b, ' '); else Buf.add(b, p^.scope[i]); end; + end; +end; + +(* The scope's synopsis lines, as the help and the mistakes begin. *) +proc synopsis(p: ^Parser; b: ^Buf.Buf); +var i: INT; first: BOOL; +begin + first := true; + for i := 0 to LEN(p^.table) - 1 do + match p^.table[i] of + | usage(scope, line): + if scope = p^.scope then + if first then Buf.str(b, "usage: "); else Buf.str(b, " "); end; + Buf.str(b, line); + Buf.add(b, '\n'); + first := false; + end; + | else: + end; + end; + if first then + Buf.str(b, "usage: "); + Buf.str(b, p^.name); + if LEN(p^.scope) > 0 then Buf.add(b, ' '); scopeWords(p, b); end; + Buf.add(b, '\n'); + end; +end; + +(* The left column of a help line for an option. *) +proc left(b: ^Buf.Buf; letter: U8; long, value: []U8); +begin + Buf.str(b, " "); + if letter >= '!' then + Buf.add(b, '-'); Buf.add(b, letter); + if LEN(long) > 0 then Buf.str(b, ", "); end; + else + Buf.str(b, " "); + end; + if LEN(long) > 0 then Buf.str(b, "--"); Buf.str(b, long); end; + if LEN(value) > 0 then Buf.add(b, ' '); Buf.str(b, value); end; +end; + +(* The help: the synopsis, a blank line, and each subcommand and option + of the scope, and the help itself, each with its line of help, the + helps in a column as far right as the longest left column needs. *) +proc printHelp(p: ^Parser); +var out, line: Buf.Buf; width, i, k, round: INT; help: []U8; +begin + Buf.init(ADR(out), Heap.heap); + Buf.init(ADR(line), Heap.heap); + synopsis(p, ADR(out)); + Buf.add(ADR(out), '\n'); + (* round 0 measures the left column, round 1 writes the lines *) + for round := 0 to 1 do + for i := 0 to LEN(p^.table) do + Buf.reset(ADR(line)); + help := ""; + if i = LEN(p^.table) then + left(ADR(line), 'h', "help", ""); + help := "print this and exit"; + else + match p^.table[i] of + | sub(scope, name, h): + if scope = p^.scope then Buf.str(ADR(line), " "); Buf.str(ADR(line), name); help := h; end; + | option(scope, letter, long, value, h): + if scope = p^.scope then left(ADR(line), letter, long, value); help := h; end; + | else: + end; + end; + if line.len > 0 then + if round = 0 then + if line.len > width then width := line.len; end; + else + Buf.str(ADR(out), Buf.bytes(ADR(line))); + for k := line.len to width + 2 do Buf.add(ADR(out), ' '); end; + Buf.str(ADR(out), help); + Buf.add(ADR(out), '\n'); + end; + end; + end; + end; + Out.str(Buf.bytes(ADR(out))); + Rt.exit(0); +end; + +(* "name: sentence" on standard error, the synopsis after it if wanted, + and the end, with status. *) +proc complain(p: ^Parser; sentence: []U8; withSynopsis: BOOL; status: INT); +var b: Buf.Buf; +begin + Buf.init(ADR(b), Heap.heap); + Buf.str(ADR(b), p^.name); + Buf.str(ADR(b), ": "); + Buf.str(ADR(b), sentence); + Buf.add(ADR(b), '\n'); + if withSynopsis then synopsis(p, ADR(b)); end; + Out.flush; + _ := Sys.write(Sys.stderr, Buf.bytes(ADR(b))); + Rt.exit(status); +end; + +(* -h or --help among the scope's options, before the program sees any: + read ahead by a copy of the parser *) +proc lookForHelp(p: ^Parser); +var q: Parser; s: Step; +begin + q := p^; + repeat + s := step(ADR(q)); + if s = aHelp then printHelp(p); end; + until s = theEnd; +end; + +proc decimal(b: ^Buf.Buf; n: I64); +var d: [20]U8; i: INT; u: U64; +begin + u := U64(n); + if n < 0 then Buf.add(b, '-'); u := 0 - u; end; + i := LEN(d); + repeat DEC(i); d[i] := U8(u mod 10) + '0'; u := u div 10; until u = 0; + Buf.str(b, d[i..LEN(d)]); +end; + +(* The table checked before a word is read: a mistake in it is the + program's, status 1. *) +proc checkTable(p: ^Parser); +var i, j, k: INT; is, other: BOOL; letter, l2: U8; long, value, l3, v3, why: []U8; b: Buf.Buf; +begin + for i := 0 to LEN(p^.table) - 1 do + why := ""; + match p^.table[i] of + | option(scope, letter, long, value, help): + if letter = 0 and LEN(long) = 0 then why := "the option has neither a letter nor a long name"; + elsif letter = '-' then why := "the letter is -"; + elsif letter = 'h' or long = "help" then why := "-h and --help are Opt's"; + else + for k := 0 to LEN(long) - 1 do + if long[k] = '=' then why := "the long name has = in it"; end; + end; + for j := 0 to i - 1 do + other, l2, l3, v3 := optionOf(p^.table[j], scope); + if other and ((letter # 0 and l2 = letter) or (LEN(long) > 0 and l3 = long)) then + why := "the option is in the scope already"; + end; + end; + end; + | else: + end; + if LEN(why) > 0 then + Buf.init(ADR(b), Heap.heap); + Buf.str(ADR(b), "option table, row "); + decimal(ADR(b), I64(i + 1)); + Buf.str(ADR(b), ": "); + Buf.str(ADR(b), why); + complain(p, Buf.bytes(ADR(b)), false, 1); + end; + end; +end; + +(* the arguments from 1 on, by table *) +proc init*(p: ^Parser; name: []U8; table: []Row); +begin + if text.len = 0 then Buf.init(ADR(text), Heap.heap); end; + p^.letter := 0; p^.value := ""; p^.long := false; + p^.name := name; + p^.table := table; + p^.scope := ""; + p^.arg := 1; + p^.pos := 0; + p^.ended := false; + checkTable(p); + lookForHelp(p); +end; + +(* the next option; false when they end *) +proc next*(p: ^Parser): BOOL; +begin + match step(p) of + | anOption: return true; + | theEnd: return false; + | aHelp: printHelp(p); + | aMistake: complain(p, Buf.bytes(ADR(text)), true, 2); + end; + return false; +end; + +(* the next operand; false when there are no more *) +proc operand*(p: ^Parser): ([]U8, BOOL); +begin + while next(p) do end; + p^.ended := true; + if p^.arg >= ARGC() then return "", false; end; + INC(p^.arg); + return Files.arg(p^.arg - 1), true; +end; + +(* subcommand name's options, from the word after it *) +proc scope*(p: ^Parser; name: []U8); +begin + p^.scope := name; + p^.ended := false; + p^.pos := 0; + lookForHelp(p); +end; + +(* the value just read, a number from lo to hi *) +proc number*(p: ^Parser; lo, hi: I64): I64; +var n: I64; ok: BOOL; b: Buf.Buf; i: INT; is: BOOL; letter: U8; long, value: []U8; +begin + n, ok := Str.toInt(p^.value); + if ok and n >= lo and n <= hi then return n; end; + Buf.init(ADR(b), Heap.heap); + i := find(p, p^.letter, ""); + is, letter, long, value := optionOf(p^.table[i], p^.scope); + if p^.long then Buf.str(ADR(b), "--"); Buf.str(ADR(b), long); + else Buf.add(ADR(b), '-'); Buf.add(ADR(b), letter); + end; + Buf.str(ADR(b), " wants a number from "); + decimal(ADR(b), lo); + Buf.str(ADR(b), " to "); + decimal(ADR(b), hi); + Buf.str(ADR(b), ", not '"); + Buf.str(ADR(b), p^.value); + Buf.str(ADR(b), "'"); + complain(p, Buf.bytes(ADR(b)), true, 2); + return 0; +end; + +(* the program's own mistake *) +proc fail*(p: ^Parser; text: []U8); +begin + complain(p, text, false, 2); +end; + +end Opt. diff --git a/sbcl/lib/Sort.raz b/sbcl/lib/Sort.raz new file mode 100644 index 0000000..90dfdae --- /dev/null +++ b/sbcl/lib/Sort.raz @@ -0,0 +1,30 @@ +(* Sorting a slice in place, by heapsort: n log n at most, and no memory + of its own. *) +module Sort(T; less: proc(a, b: T): BOOL); + +(* the element at i moved down the heap of the first n elements *) +proc sift(s: []T; i, n: INT); +var child: INT; t: T; +begin + child := 2 * i + 1; + while child < n do + if child + 1 < n and less(s[child], s[child + 1]) then INC(child); end; + if not less(s[i], s[child]) then return; end; + t := s[i]; s[i] := s[child]; s[child] := t; + i := child; + child := 2 * i + 1; + end; +end; + +proc sort*(s: []T); +var i, n: INT; t: T; +begin + n := LEN(s); + for i := n div 2 - 1 to 0 by -1 do sift(s, i, n); end; + for i := n - 1 to 1 by -1 do + t := s[0]; s[0] := s[i]; s[i] := t; + sift(s, 0, i); + end; +end; + +end Sort. diff --git a/sbcl/lib/Sys.raz b/sbcl/lib/Sys.raz index 108d976..260ccd4 100644 --- a/sbcl/lib/Sys.raz +++ b/sbcl/lib/Sys.raz @@ -18,8 +18,21 @@ sysGetcwd = 79; sysChdir = 80; sysRename = 82; sysMkdir = 83; sysRmdir = 84; sysUnlink = 87; sysSymlink = 88; sysReadlink = 89; sysChmod = 90; sysClockGettime = 228; sysExitGroup = 231; - sysOpenat = 257; sysGetrandom = 318; + sysOpenat = 257; sysGetrandom = 318; sysPoll = 7; sysDup2 = 33; + sysSocket = 41; sysConnect = 42; sysAccept4 = 288; sysSendto = 44; + sysBind = 49; sysListen = 50; sysSetsockopt = 54; sysFork = 57; + sysExecve = 59; sysExit = 60; sysWait4 = 61; sysFcntl = 72; + sysSetpgid = 109; sysSetsid = 112; sysStatfs = 137; + sysGetdents64 = 217; sysPipe2 = 293; sysCloseRange = 436; + sysRtSigaction = 13; sysRtSigprocmask = 14; + + (* ioctls of terminals *) + tcgets = 5401H; tcsets = 5402H; tiocgwinsz = 5413H; tiocswinsz = 5414H; + tiocspgrp = 5410H; tiocgpgrp = 540FH; tiocsctty = 540EH; + tiocsptlck = 40045431H; tiocgptn = 80045430H; + cloexec = 80000H; nonblock = 800H; + atFdCwd = -100; pathMax = 4096; @@ -35,8 +48,29 @@ symlink*: BOOL; (* the path itself is a symbolic link *) end; Path = [pathMax]U8; (* a path with a zero after it, as Linux takes it *) + Dir* = record (* an open directory *) + fd: INT; + buf: [4096]U8; (* entries as getdents64 gives them *) + pos, len: INT; + end; + Program* = record + path*: []U8; + args*: [][]U8; (* the first is its name *) + env*: [][]U8; (* NAME=value, each added to this program's environment *) + onlyEnv*: BOOL; (* env is its whole environment *) + dir*: []U8; (* its working directory; "" for this program's *) + fds*: [3]INT; (* its standard input, output and error; 0 for this program's own *) + group*: INT; (* the process group it joins: 0 for this program's, -1 a new one it leads *) + foreground*: BOOL; (* its group takes the terminal on standard input *) + tty*: INT; (* a pseudo-terminal's fd, to start a session on; 0 for none *) + end; + Status* = (running, exited, killed, stopped); + Termios = [64]U8; (* the kernel's struct termios, with room *) var + saved: Termios; (* the terminal's mode before rawMode *) + savedFd: INT; + haveSaved: BOOL; linkBuf: [pathMax]U8; dirBuf: [pathMax]U8; envp: ^^U8; @@ -52,6 +86,7 @@ proc write*(fd: INT; s: []U8): INT; begin + if LEN(s) = 0 then return 0; end; return SYSCALL(sysWrite, fd, ADR(s[0]) , LEN(s)); end; @@ -288,6 +323,513 @@ n := SYSCALL(sysGetrandom, ADR(b[done]), LEN(b) - done, 0); if n > 0 then done := done + n; end; end; +end; + +(* the bytes free and in all on path's file system *) +proc space*(path: []U8): (I64, I64, INT); +var c: Path; st: [16]I64; r: INT; +begin + if not cPath(path, c) then return 0, 0, -36; end; + r := SYSCALL(sysStatfs, ADR(c), ADR(st)); + if r < 0 then return 0, 0, r; end; + return st[4] * st[1], st[2] * st[1], 0; +end; + +(* Directories: getdents64's entries, read a buffer at a time. *) + +proc openDir*(d: ^Dir; path: []U8): INT; +var fd: INT; +begin + fd := open(path, {reading}); + if fd < 0 then return fd; end; + d^.fd := fd; + d^.pos := 0; + d^.len := 0; + return 0; +end; + +(* a name, good until the next call; false at the end *) +proc nextEntry*(d: ^Dir): ([]U8, BOOL); +var n, reclen, i: INT; name: []U8; +begin + while true do + if d^.pos >= d^.len then + n := SYSCALL(sysGetdents64, d^.fd, ADR(d^.buf), LEN(d^.buf)); + if n <= 0 then return "", false; end; + d^.pos := 0; + d^.len := n; + end; + reclen := INT(^U16(ADR(d^.buf[d^.pos + 16]))^); + i := d^.pos + 19; + while d^.buf[i] # 0 do INC(i); end; + name := d^.buf[d^.pos + 19..i]; + d^.pos := d^.pos + reclen; + if name # "." and name # ".." then return name, true; end; + end; + return "", false; +end; + +proc closeDir*(d: ^Dir); +begin + close(d^.fd); +end; + +(* The terminal. *) + +(* the terminal on fd: no echo, no lines, no signals *) +proc rawMode*(fd: INT): BOOL; +var t: Termios; iflag, oflag, cflag, lflag: ^U32; +begin + if SYSCALL(sysIoctl, fd, tcgets, ADR(t)) # 0 then return false; end; + if not haveSaved then saved := t; savedFd := fd; haveSaved := true; end; + iflag := ^U32(ADR(t[0])); oflag := ^U32(ADR(t[4])); + cflag := ^U32(ADR(t[8])); lflag := ^U32(ADR(t[12])); + iflag^ := iflag^ & ~U32(1H | 2H | 8H | 20H | 40H | 80H | 100H | 400H); + oflag^ := oflag^ & ~U32(1H); + lflag^ := lflag^ & ~U32(8H | 40H | 2H | 1H | 8000H); + cflag^ := (cflag^ & ~U32(30H | 100H)) | 30H; + t[17 + 6] := 1; (* VMIN *) + t[17 + 5] := 0; (* VTIME *) + return SYSCALL(sysIoctl, fd, tcsets, ADR(t)) = 0; +end; + +(* as rawMode found it *) +proc restoreMode*(fd: INT); +begin + if haveSaved then _ := SYSCALL(sysIoctl, fd, tcsets, ADR(saved)); end; +end; + +(* columns and rows; 80 and 24 if unknown *) +proc termSize*(fd: INT): (INT, INT); +var w: [4]U16; +begin + if SYSCALL(sysIoctl, fd, tiocgwinsz, ADR(w)) # 0 or w[1] = 0 then return 80, 24; end; + return INT(w[1]), INT(w[0]); +end; + +(* the size its programs are told of *) +proc setTermSize*(fd, cols, rows: INT): INT; +var w: [4]U16; +begin + w[0] := U16(rows); + w[1] := U16(cols); + return SYSCALL(sysIoctl, fd, tiocswinsz, ADR(w)); +end; + +(* Waiting: poll on up to 64 descriptors. *) + +type PollFd = record fd: I32; events, revents: I16; end; + +(* poll on n of fds, again if a signal interrupts it *) +proc poll(fds: ^PollFd; n, ms: INT): INT; +var r: INT; +begin + repeat + r := SYSCALL(sysPoll, fds, n, ms); + until r # -4; + return r; +end; + +(* something to read within ms, or ever if ms < 0 *) +proc ready*(fd, ms: INT): BOOL; +var p: PollFd; +begin + p.fd := I32(fd); + p.events := 1; + return poll(ADR(p), 1, ms) > 0; +end; + +(* readyOf, and the first of writes with room to write *) +proc readyFor*(reads, writes: []INT; ms: INT): INT; +var p: [64]PollFd; n, i, j: INT; found: BOOL; +begin + for i := 0 to LEN(reads) - 1 do + if n < LEN(p) then p[n].fd := I32(reads[i]); p[n].events := 1; INC(n); end; + end; + for i := 0 to LEN(writes) - 1 do + if n < LEN(p) then + found := false; + for j := 0 to n - 1 do + if p[j].fd = I32(writes[i]) then p[j].events := p[j].events | 4; found := true; end; + end; + if not found then p[n].fd := I32(writes[i]); p[n].events := 4; INC(n); end; + end; + end; + if poll(ADR(p[0]), n, ms) <= 0 then return -1; end; + for i := 0 to n - 1 do + if p[i].revents # 0 then return INT(p[i].fd); end; + end; + return -1; +end; + +(* the first of fds with something to read within ms, or -1 *) +proc readyOf*(fds: []INT; ms: INT): INT; +var none: [1]INT; +begin + return readyFor(fds, none[0..0], ms); +end; + +(* if not yes, a read or write that would wait is -11 at once *) +proc setBlocking*(fd: INT; yes: BOOL): INT; +var flags: INT; +begin + flags := SYSCALL(sysFcntl, fd, 3); + if flags < 0 then return flags; end; + if yes then flags := flags & ~nonblock; else flags := flags | nonblock; end; + return SYSCALL(sysFcntl, fd, 4, flags); +end; + +(* Programs. *) + +(* the fd to read and the fd to write; or minus an errno and -1 *) +proc pipe*: (INT, INT); +var fds: [2]I32; r: INT; +begin + r := SYSCALL(sysPipe2, ADR(fds), cloexec); + if r < 0 then return r, -1; end; + return INT(fds[0]), INT(fds[1]); +end; + +(* a pseudo-terminal: the fd of its controlling side *) +proc openPty*: INT; +var fd: INT; zero: I32; +begin + fd := open("/dev/ptmx", {reading, writing}); + if fd < 0 then return fd; end; + _ := SYSCALL(sysIoctl, fd, tiocsptlck, ADR(zero)); + return fd; +end; + +(* s with a zero after it, in memory of its own, for the new program *) +proc cString(s: []U8): ^U8; +var p: ^U8; +begin + p := mmap(LEN(s) + 1); + if p # nil and LEN(s) > 0 then COPY(p[0..LEN(s)], s); end; + return p; +end; + +(* The new program's environment: this one's with p.env put in, or p.env alone. *) +proc environment(p: Program): ^^U8; +var e: ^^U8; n, i, j, k, eq: INT; s: ^U8; replaced: BOOL; +begin + if envp = nil then envp := environ(); end; + while envp[n] # nil do INC(n); end; + e := ^^U8(mmap((n + LEN(p.env) + 1) * 8)); + k := 0; + if not p.onlyEnv then + for i := 0 to n - 1 do + s := envp[i]; + replaced := false; + for j := 0 to LEN(p.env) - 1 do + eq := 0; + while eq < LEN(p.env[j]) and p.env[j][eq] # '=' do INC(eq); end; + if s[0..eq + 1] = p.env[j][0..eq + 1] then replaced := true; end; + end; + if not replaced then e[k] := s; INC(k); end; + end; + end; + for j := 0 to LEN(p.env) - 1 do e[k] := cString(p.env[j]); INC(k); end; + e[k] := nil; + return e; +end; + +(* In the child, after fork: what spawn says, then the program. *) +proc child(p: Program; path: ^U8; argv, env: ^^U8); +var i, n, slave: INT; zero: [2]U64; act: [4]U64; pts: Path; pgrp: I32; +begin + if p.tty # 0 then + (* a session on the pseudo-terminal: its controlling terminal and + standard input, output and error *) + _ := SYSCALL(sysSetsid); + _ := SYSCALL(sysIoctl, p.tty, tiocgptn, ADR(n)); + pts := "/dev/pts/"; + i := 9; + if n = 0 then pts[i] := '0'; INC(i); end; + slave := n; + while slave > 0 do INC(i); slave := slave div 10; end; + slave := i; + while n > 0 do DEC(i); pts[i] := U8(n mod 10) + '0'; n := n div 10; end; + pts[slave] := 0; + slave := SYSCALL(sysOpenat, atFdCwd, ADR(pts), 2); + _ := SYSCALL(sysIoctl, slave, tiocsctty, 0); + for i := 0 to 2 do _ := SYSCALL(sysDup2, slave, i); end; + else + if p.group = -1 then _ := SYSCALL(sysSetpgid, 0, 0); + elsif p.group > 0 then _ := SYSCALL(sysSetpgid, 0, p.group); + end; + if p.foreground then + pgrp := I32(SYSCALL(sysGetpid)); + if p.group > 0 then pgrp := I32(p.group); end; + _ := SYSCALL(sysIoctl, 0, tiocspgrp, ADR(pgrp)); + end; + for i := 0 to 2 do + if p.fds[i] # 0 then _ := SYSCALL(sysDup2, p.fds[i], i); end; + end; + end; + (* every signal as it is at first, and none blocked *) + for i := 1 to 31 do + if i # 9 and i # 19 then _ := SYSCALL(sysRtSigaction, i, ADR(act), 0, 8); end; + end; + _ := SYSCALL(sysRtSigprocmask, 2, ADR(zero), 0, 8); + _ := SYSCALL(sysCloseRange, 3, 0FFFFFFFFH, 0); + if LEN(p.dir) > 0 and setWorkDir(p.dir) < 0 then _ := SYSCALL(sysExit, 127); end; + _ := SYSCALL(sysExecve, path, argv, env); + _ := SYSCALL(sysExit, 127); +end; + +(* a program started: its process id *) +proc spawn*(p: Program): INT; +var path: ^U8; argv, env: ^^U8; i, pid: INT; +begin + path := cString(p.path); + argv := ^^U8(mmap((LEN(p.args) + 1) * 8)); + if path = nil or argv = nil then return -12; end; + for i := 0 to LEN(p.args) - 1 do argv[i] := cString(p.args[i]); end; + env := environment(p); + pid := SYSCALL(sysFork); + if pid = 0 then child(p, path, argv, env); end; + (* the parent's copies given back *) + for i := 0 to LEN(p.args) - 1 do munmap(argv[i], LEN(p.args[i]) + 1); end; + munmap(^U8(argv), (LEN(p.args) + 1) * 8); + munmap(path, LEN(p.path) + 1); + return pid; +end; + +(* which program, how, and its code *) +proc wait*(pid: INT; block: BOOL): (INT, Status, INT); +var st: I32; r, options: INT; +begin + options := 2; (* WUNTRACED *) + if not block then options := options | 1; end; + repeat + r := SYSCALL(sysWait4, pid, ADR(st), options, 0); + until r # -4; + if r <= 0 then return r, running, 0; end; + if st & 7FH = 0 then return r, exited, INT((st shr 8) & 0FFH); end; + if st & 0FFH = 7FH then return r, stopped, INT((st shr 8) & 0FFH); end; + return r, killed, INT(st & 7FH); +end; + +(* pid 0 is this program; group 0 a new one pid leads *) +proc setGroup*(pid, group: INT): INT; +begin + return SYSCALL(sysSetpgid, pid, group); +end; + +(* the terminal on fd gives its keys to group *) +proc foreground*(fd, group: INT): INT; +var g: I32; +begin + g := I32(group); + return SYSCALL(sysIoctl, fd, tiocspgrp, ADR(g)); +end; + +(* the group the terminal on fd gives its keys to *) +proc foregroundOf*(fd: INT): INT; +var g: I32; r: INT; +begin + r := SYSCALL(sysIoctl, fd, tiocgpgrp, ADR(g)); + if r < 0 then return r; end; + return INT(g); +end; + +(* Signals: SBCL's run time catches them and writes each to a pipe, + whose end to read is the fd catch gives. *) + +proc catchSignal(sig: INT): INT; +code + (catch-signal sig); +end; + +proc ignoreSignal(sig: INT; yes: BOOL); +code + (ignore-signal sig yes); +end; + +(* sigs caught: an fd to wait on *) +proc catch*(sigs: []INT): INT; +var i, fd: INT; +begin + for i := 0 to LEN(sigs) - 1 do + if sigs[i] = sigKill or sigs[i] = sigStop or sigs[i] = 11 or sigs[i] = 8 + or sigs[i] < 1 or sigs[i] > 64 then + return -22; + end; + end; + fd := -22; + for i := 0 to LEN(sigs) - 1 do fd := catchSignal(sigs[i]); end; + return fd; +end; + +(* the next signal caught, or 0 if none is waiting *) +proc caught*(fd: INT): INT; +var b: [1]U8; +begin + if SYSCALL(sysRead, fd, ADR(b), 1) = 1 then return INT(b[0]); end; + return 0; +end; + +(* sig ignored; or, if not yes, back to what it does at first *) +proc ignore*(sig: INT; yes: BOOL): INT; +begin + if sig = sigKill or sig = sigStop or sig = 11 or sig = 8 or sig < 1 or sig > 64 then return -22; end; + ignoreSignal(sig, yes); + return 0; +end; + +(* Sockets. An address is a sockaddr, made in a [128]U8. *) + +type Address = [128]U8; + +(* path as a Unix socket's address, and its length; -36 if too long *) +proc unixAddress(path: []U8; var a: Address): INT; +begin + if LEN(path) > 107 then return -36; end; + a[0] := 1; (* AF_UNIX *) + COPY(a[2..2 + LEN(path)], path); + a[2 + LEN(path)] := 0; + return 2 + LEN(path) + 1; +end; + +(* the number at s[i..], hexadecimal or decimal, and where it ends *) +proc number(s: []U8; i: INT; hex: BOOL): (INT, INT, BOOL); +var v, d, start: INT; +begin + start := i; + while i < LEN(s) do + if s[i] >= '0' and s[i] <= '9' then d := INT(s[i] - '0'); + elsif hex and s[i] >= 'a' and s[i] <= 'f' then d := INT(s[i] - 'a') + 10; + elsif hex and s[i] >= 'A' and s[i] <= 'F' then d := INT(s[i] - 'A') + 10; + else return v, i, i > start; + end; + if hex then v := v * 16 + d; else v := v * 10 + d; end; + if v > 0FFFFH then return 0, i, false; end; + INC(i); + end; + return v, i, i > start; +end; + +(* addr, IPv4 or IPv6 numbers, and port as an address, and its length; -22 if addr isn't one *) +proc inetAddress(addr: []U8; port: INT; var a: Address): INT; +var i, k, v, gap, n: INT; ok: BOOL; groups: [8]INT; +begin + a[2] := U8(port shr 8); + a[3] := U8(port & 0FFH); + while i < LEN(addr) and addr[i] # ':' do INC(i); end; + if i = LEN(addr) then + i := 0; + a[0] := 2; (* AF_INET *) + for k := 0 to 3 do + v, i, ok := number(addr, i, false); + if not ok or v > 255 then return -22; end; + a[4 + k] := U8(v); + if k < 3 then + if i >= LEN(addr) or addr[i] # '.' then return -22; end; + INC(i); + end; + end; + if i # LEN(addr) then return -22; end; + return 16; + end; + a[0] := 10; (* AF_INET6 *) + gap := -1; + i := 0; + if LEN(addr) >= 2 and addr[0..2] = "::" then gap := 0; i := 2; end; + while i < LEN(addr) do + if n = 8 then return -22; end; + v, i, ok := number(addr, i, true); + if not ok then return -22; end; + groups[n] := v; + INC(n); + if i < LEN(addr) then + if addr[i] # ':' then return -22; end; + INC(i); + if i < LEN(addr) and addr[i] = ':' then + if gap >= 0 then return -22; end; + gap := n; + INC(i); + end; + end; + end; + if gap < 0 and n # 8 then return -22; end; + (* the groups after the gap move to the end *) + for k := 0 to 7 do + if gap < 0 or k < gap then v := groups[k]; + elsif k >= 8 - (n - gap) then v := groups[k - (8 - n)]; + else v := 0; + end; + a[8 + 2 * k] := U8(v shr 8); + a[9 + 2 * k] := U8(v & 0FFH); + end; + return 28; +end; + +(* a socket of type kind for address a, connected or bound and listening *) +proc socket(a: Address; n, kind: INT; serve: BOOL): INT; +var fd, r: INT; one: I32; +begin + if n < 0 then return n; end; + fd := SYSCALL(sysSocket, INT(a[0]), kind | cloexec, 0); + if fd < 0 then return fd; end; + if serve then + one := 1; + _ := SYSCALL(sysSetsockopt, fd, 1, 2, ADR(one), 4); + r := SYSCALL(sysBind, fd, ADR(a), n); + if r = 0 then r := SYSCALL(sysListen, fd, 128); end; + else + r := SYSCALL(sysConnect, fd, ADR(a), n); + end; + if r < 0 then close(fd); return r; end; + return fd; +end; + +(* a stream socket, connected to the Unix socket at path: its fd *) +proc connect*(path: []U8): INT; +var a: Address; +begin + return socket(a, unixAddress(path, a), 1, false); +end; + +(* addr an IPv4 or IPv6 address, as numbers *) +proc connectTcp*(addr: []U8; port: INT): INT; +var a: Address; +begin + return socket(a, inetAddress(addr, port, a), 1, false); +end; + +proc connectUdp*(addr: []U8; port: INT): INT; +var a: Address; +begin + return socket(a, inetAddress(addr, port, a), 2, false); +end; + +(* a Unix socket made at path, taking connections *) +proc listen*(path: []U8): INT; +var a: Address; +begin + return socket(a, unixAddress(path, a), 1, true); +end; + +proc listenTcp*(addr: []U8; port: INT): INT; +var a: Address; +begin + return socket(a, inetAddress(addr, port, a), 1, true); +end; + +(* the next connection, waiting for one *) +proc accept*(fd: INT): INT; +var r: INT; +begin + repeat r := SYSCALL(sysAccept4, fd, 0, 0, cloexec); until r # -4; + return r; +end; + +(* write, to a socket: -32 (EPIPE), not a signal, if it is closed *) +proc send*(fd: INT; s: []U8): INT; +begin + if LEN(s) = 0 then return 0; end; + return SYSCALL(sysSendto, fd, ADR(s[0]), LEN(s), 4000H, 0, 0); end; end Sys. diff --git a/sbcl/lib/Thread.raz b/sbcl/lib/Thread.raz new file mode 100644 index 0000000..6be6432 --- /dev/null +++ b/sbcl/lib/Thread.raz @@ -0,0 +1,60 @@ +(* Threads for a program without C: spawn, join, and Mutex. Here each is a + thread of SBCL's, on a raz stack of its own. *) +module Thread; +import Heap, Mem; +link static; + +const Failed*: ERROR = "can't start a thread"; + +type + Thread* = record id: INT; end; + Mutex* = record state: INT; end; (* zero is free; 1 taken; 2 taken, with waiters *) + +const + sysFutex = 202; + futexWait = 128; (* FUTEX_WAIT, private *) + futexWake = 129; + +proc start(p: proc(arg: ^U8); arg: ^U8): INT; +code + (thread-spawn p arg); +end; + +proc wait(id: INT); +code + (thread-join id); +end; + +(* p(arg) in a new thread *) +proc spawn*(p: proc(arg: ^U8); arg: ^U8): (^Thread, ERROR); +var t: ^Thread; +begin + NEW(t, Heap.heap); + if t = nil then return nil, Failed; end; + t^.id := start(p, arg); + return t, nil; +end; + +(* waits for t to end, then frees what it had *) +proc join*(t: ^Thread); +begin + wait(t^.id); + Mem.free(Heap.heap, ^U8(t)); +end; + +proc lock*(m: ^Mutex); +begin + if CAS(ADR(m^.state), 0, 1) then return; end; + while XCHG(ADR(m^.state), 2) # 0 do + _ := SYSCALL(sysFutex, ADR(m^.state), futexWait, 2, 0); + end; +end; + +proc unlock*(m: ^Mutex); +begin + if XCHG(ADR(m^.state), 0) = 2 then + _ := SYSCALL(sysFutex, ADR(m^.state), futexWake, 1); + end; +end; + +end Thread. diff --git a/sbcl/src/decl.lisp b/sbcl/src/decl.lisp index cc68289..5b2db2b 100644 --- a/sbcl/src/decl.lisp +++ b/sbcl/src/decl.lisp @@ -80,7 +80,7 @@ (defun pointer-type-rest () "A pointer type, after its ^." - (let ((vol (accept :volatile))) + (let ((vol (and (accept :volatile) t))) (if (and (listp *forward-types*) (eq (kind) :ident) (not (eq (kind 1) :|.|)) (not (lookup (tok-val (tok))))) ;; a type declared later in this section (section 4) diff --git a/sbcl/src/expr.lisp b/sbcl/src/expr.lisp index d01f4de..f04b26b 100644 --- a/sbcl/src/expr.lisp +++ b/sbcl/src/expr.lisp @@ -743,13 +743,13 @@ (let ((tk (item-tok a))) (unless (eq (item-mode a) :var) (fail-tok tk "a var parameter takes a variable")) (check-writable a tk "passed as a var argument") + (when (item-vol a) (fail-tok tk "a volatile variable isn't passed as a var argument")) (when (item-noaddr a) (fail-tok tk "a field of a packed record has no address")) (unless (same-type-p (item-type a) ty) (fail-tok tk "a var parameter of ~a takes a variable of it, not ~a" (type-name ty) (type-name (item-type a)))) (item-form a))) (defun check-writable (a tk what) - (when (item-vol a) (fail-tok tk "a volatile variable can't be ~a" what)) (case (item-ro a) (:export (fail-tok tk "another module's variable can't be ~a" what)) (:const (fail-tok tk "a constant can't be ~a" what)) @@ -893,7 +893,7 @@ (unless (eq (item-mode x) :var) (fail-tok tk "ADR takes a variable")) (check-writable x tk "given to ADR") (when (item-noaddr x) (fail-tok tk "a field of a packed record has no address")) - (val-item (make-ptr-type (item-type x) nil) (item-form x) tk))) + (val-item (make-ptr-type (item-type x) (item-vol x)) (item-form x) tk))) ((string= name "LEN") (arity args 1) (let* ((x (need-value (arg 0))) (ty (item-type x))) diff --git a/sbcl/src/rt.lisp b/sbcl/src/rt.lisp index 2dcdf13..bcc00ae 100644 --- a/sbcl/src/rt.lisp +++ b/sbcl/src/rt.lisp @@ -307,11 +307,36 @@ (sb-thread:join-thread th :default nil) (sb-thread:with-mutex (*threads-lock*) (remhash id *threads*))))) +;;; Signals, for the library's Sys.catch and Sys.ignore: SBCL's run time +;;; handles each signal caught, writing its number to a pipe. + +(sb-ext:defglobal *signal-pipe* nil "The fds of the pipe, read and write, once made.") + +(defun catch-signal (sig) + (unless *signal-pipe* + (let ((buf (c-call "malloc" sb-alien:unsigned-long sb-alien:unsigned-long 8))) + ;; pipe2(buf, O_CLOEXEC | O_NONBLOCK) + (syscall 293 buf (logior #x80000 #x800)) + (setf *signal-pipe* (cons (ld :i32 buf) (ld :i32 (+ buf 4)))))) + (let ((w (cdr *signal-pipe*))) + (sb-sys:enable-interrupt sig (lambda (&rest args) + (declare (ignore args)) + (let ((b (c-call "malloc" sb-alien:unsigned-long sb-alien:unsigned-long 1))) + (st :u8 b sig) + (syscall 1 w b 1) + (c-call "free" sb-alien:void sb-alien:unsigned-long b))))) + (car *signal-pipe*)) + +(defun ignore-signal (sig yes) + (sb-sys:enable-interrupt sig (if yes :ignore :default))) + ;;; The start. The saved program begins here: the data block mapped and ;;; filled, then the program run on the main thread's raz stack, and its ;;; status given to Rt.exit. (defun start () + ;; the signals SBCL handles for itself do what they do in any program + (dolist (sig '(1 2 3 13 15)) (sb-sys:enable-interrupt sig :default)) (let ((size (length *data-image*))) (when (> size 0) (map-memory (round-up size 4096) +data-base+) diff --git a/sbcl/src/scan.lisp b/sbcl/src/scan.lisp index 06566a0..33f693c 100644 --- a/sbcl/src/scan.lisp +++ b/sbcl/src/scan.lisp @@ -130,7 +130,10 @@ (cond ((string= text "_") (add :blank nil l c)) ((member text *reserved* :test #'string=) (add (keyword-of (string-upcase text)) nil l c) - (when (string= text "code") (code-body))) + ;; a code body follows `code` after a signature's `;` + (when (and (string= text "code") (rest toks) + (eq (tok-kind (second toks)) :|;|)) + (code-body))) (t (add :ident text l c)))))) (number (l c) ;; digits and capitals A-F; then H for hexadecimal, or a diff --git a/sbcl/src/stmt.lisp b/sbcl/src/stmt.lisp index eae4dc2..595cbf2 100644 --- a/sbcl/src/stmt.lisp +++ b/sbcl/src/stmt.lisp @@ -120,6 +120,9 @@ (case (item-mode x) (:proc (item-form (call-proc (item-obj x) nil tk))) ((:none :multi) (item-form x)) + (:builtin (if (string= (item-val x) "FENCE") + '(sb-thread:barrier (:memory)) + (fail-tok tk "~a takes arguments" (item-val x)))) (t (if (consp (item-obj x)) (item-form x) ; a call with one result (if (and (member (item-mode x) '(:var :val)) (is (item-type x) :proc))