raz / commit 7a137131

commit
7a137131f83d6e669aa07bafa65975feb6941933
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
5b0b3f89
Host: the compiler's five asks of the system it runs on, in one module

patch · log

7 files changed, +310 -53

doc/compiler.md (history) modified +55 -9

@@ -1,6 +1,6 @@
11 # Reading the raz compiler
22
3-The compiler is eleven files of raz, about 12,700 lines of code (the
3+The compiler is twelve files of raz, about 12,700 lines of code (the
44 budget is 14,000). It is its own compiler: a release of it, the one
55 `BOOT` names, builds `src/`, and `make fixpoint` checks that what it
66 makes makes itself again, byte for byte. Each release was built by the
@@ -26,7 +26,8 @@
2626 | `src/Parse.raz` | 4,816 | 4,098 | Declarations, statements, expressions, built-ins, recovery, warnings |
2727 | `src/Link.raz` | 408 | 316 | Tree shaking, layout, patching, the places |
2828 | `src/Elf.raz` | 450 | 356 | Static and dynamic ELF, symbol table, line numbers |
29-| `src/Raz.raz` | 419 | 334 | The command line |
29+| `src/Host.raz` | 103 | 52 | The system running the compiler |
30+| `src/Raz.raz` | 394 | 316 | The command line |
3031
3132 Every file opens with a comment that says what it is, what it depends
3233 on and what it leaves out. Read those first; they are the map.
@@ -2190,7 +2191,7 @@
21902191 `/lib64/ld-linux-x86-64.so.2` and `libc.so.6`, or musl's,
21912192 `/lib/ld-musl-x86_64.so.1` and `libc.so`, which musl's loader, being
21922193 the library itself, takes to mean itself (`Elf.setMusl`). `-libc`
2193-chooses; left out, `Raz.muslHere` chooses musl where the machine has
2194+chooses; left out, `Host.cLibrary` does: musl where the machine has
21942195 its loader and not glibc's, as Alpine does. A symbol that isn't live
21952196 gets no relocation, so a program runs over a C library that lacks a
21962197 procedure it declares but never reaches. `sizeTables` and `putTables` lay these out in the room `Link.raz` left
@@ -2201,6 +2202,48 @@
22012202 it, which `putDebug` writes. There are no types or variables in it;
22022203 gdb can stop at a line and show where it is, not print a variable.
22032204
2205+## Host.raz: the system running the compiler
2206+
2207+The host is the system running raz; the target is the system its
2208+program will run on. Everything the compiler asks of its host that the
2209+library doesn't give is in `Host.raz`, five procedures, each a real
2210+difference between hosts. Nothing else in `src/` makes a system call,
2211+reads `argv`, opens `/proc` or sets a file's mode; it reads, writes and
2212+lists files, the environment and the working directory through the
2213+library (`Sys`, `Files`), and `Files.argCount` and `Files.arg` give it
2214+its command line.
2215+
2216+- `libraryDir`: the directory of the standard library. Linux's is the
2217+ `lib` beside raz, found by `/proc/self/exe` so that a link to raz
2218+ works, or, with no `/proc`, beside argument 0.
2219+- `cLibrary`: `CLib = (none, glibc, musl)`, the C library a program that
2220+ uses C is linked against when `-libc` doesn't say. `none` says the
2221+ host can't make such a program, and `Raz` refuses one when it finds
2222+ the program uses C. Linux's is glibc, or musl where only its loader
2223+ is there.
2224+- `writeExecutable`: the bytes `Elf` made, written as an executable.
2225+ Linux's writes the file and sets mode 755. It returns false on any
2226+ failure, which `Elf` reports.
2227+- `prepareRun`: the path `raz run` writes to, or an error, which is the
2228+ refusal of a host that can't run a program. Linux's is a memfd,
2229+ `/proc/self/fd/N`, kept open until `execute`.
2230+- `execute`: replaces the compiler with the program at that path, whose
2231+ arguments are the compiler's from number `first` on (so its argument 0
2232+ is `Main.raz`), and the environment. It returns only on failure.
2233+
2234+**Building for another host.** Stage the sources: copy `src/` to a
2235+directory, put that host's `Host.raz` there in place of raz's, and
2236+build `Raz.raz` from the copy with that host's library. This is the one
2237+way; raz knows no host but Linux. A module in the main file's
2238+directory is found first, so `-I` alone can't replace `Host.raz`, which
2239+is right: a module is never replaced silently. The new file keeps every
2240+export, `CLib` too, and opens with what it is, as raz's does.
2241+`test/host/Host.raz` is such a file (its library from the environment,
2242+no run, no C), and `test/compiler-host.sh` builds the compiler with it
2243+and checks the four differences. The host changes nothing of the target:
2244+a program for another system still needs that system's `Sys` and `Rt`,
2245+and for a kernel the options `-bare`, `-s` and `-base`.
2246+
22042247 ## Raz.raz: the command line
22052248
22062249 `Raz.raz` parses the arguments, calls `Parse.compileMain`, and works out what
@@ -2212,8 +2255,8 @@
22122255 for `Rt.cExit`, and, if the program has `Thread`, `pthread_create` and
22132256 `pthread_join` for `Thread.cCreate` and `Thread.cJoin`. Then it has
22142257 gen's `entryPoint` write the entry point, and `Link.markLive` mark what it
2215-reaches. The program is `proc main*: INT`; where raz is, for the library
2216-beside it, it reads from `/proc/self/exe`, and the version it prints is
2258+reaches. The program is `proc main*: INT`; `Host` says where the library is and
2259+which C library to use by default (below), and the version it prints is
22172260 the module `Version`, which the build makes from `git describe`. On a target
22182261 without reals (`HasReals`, a constant of `Parse`; x86-64 has
22192262 them), a live chunk that computes with one is an error at the first
@@ -2235,10 +2278,13 @@
22352278 program that uses C is refused.
22362279
22372280 `raz -S` lists the code (`X64.list`) instead of writing
2238-it. `raz run` writes the executable to a memfd, a file only in memory, and
2239-executes it through `/proc/self/fd` in raz's own place, handing it the
2240-rest of raz's `argv`. Nothing is left on disk, and the program's
2241-status is the command's.
2281+it. `raz run` writes the executable to the path `Host.prepareRun` gives
2282+and has `Host.execute` run it in raz's own place, handing it the rest
2283+of raz's arguments. On Linux the path is a memfd, a file only in
2284+memory, so nothing is left on disk, and the program's status is the
2285+command's. `prepareRun` is called as soon as the command line is read,
2286+before any source, so a host that can't run refuses there. The
2287+arguments are read through `Files.argCount` and `Files.arg`.
22422288
22432289 Before compiling, `userLibraries` reads `RAZ_PATH` with `Sys.envAt`,
22442290 which distinguishes an unset variable from an explicitly empty one.

src/Elf.raz modified +4 -4

@@ -14,8 +14,8 @@
1414 There is no PLT and no lazy binding, and the program exports nothing.
1515
1616 Depends on: Link for the images and addresses, Chunk for the chunks,
17- Scan for names and memory, Diag for errors, Sys and Files to write
18- the file.
17+ Scan for names and memory, Diag for errors, Sys for the working
18+ directory, and Host to write the file.
1919 Leaves out: position independent executables, symbol versions, the
2020 rest of DWARF.
2121
@@ -25,7 +25,7 @@
2525 Exported variables can't be set from outside, so needLib, setMusl,
2626 setMainPath and setStripped do it. *)
2727 module Elf;
28-import Sys, Files, Fmt, Diag, Scan, Chunk, Link;
28+import Sys, Host, Fmt, Diag, Scan, Chunk, Link;
2929 import SYSTEM;
3030
3131 var
@@ -440,7 +440,7 @@
440440 shdr(".debug_info", 1, 0, 0, dbgOff[1], dbgSize[1], 0, 0, 1, 0);
441441 shdr(".debug_abbrev", 1, 0, 0, dbgOff[2], dbgSize[2], 0, 0, 1, 0);
442442
443- if not Files.write(path, buf[0..len]) or (Sys.chmod(path, 1EDH) < 0) then
443+ if not Host.writeExecutable(path, buf[0..len]) then
444444 Diag.fatal(Diag.say("can't write {}", [Fmt.str(path)]));
445445 end;
446446 end;

src/Host.raz added +103 -0

@@ -0,0 +1,103 @@
1+(* Host: what the compiler asks of the system it runs on, beyond the
2+ library. The host is the system running raz; the target, the one its
3+ program will run on. This file is Linux's.
4+
5+ Another host stages its own file in its place: copy src/ to a
6+ directory, put that host's Host.raz there instead of this one, and
7+ build the copy with the host's library (doc/compiler.md says how).
8+ Raz and Elf import only this module for what follows, so a host
9+ gives these five procedures and keeps every export:
10+
11+ libraryDir where the standard library is, as a directory path
12+ cLibrary which C library a program that uses C is linked
13+ against by default, or none if the host can't make one
14+ writeExecutable the file at path made to hold an executable
15+ prepareRun the path raz run writes its program to, or an error
16+ if this host can't run it; asked first, before any
17+ source is read, so its error is the refusal
18+ execute replaces the compiler with the program written there
19+
20+ A host that can't run programs refuses in prepareRun and gives
21+ execute any body; one that has no C gives cLibrary the value none.
22+ Strings it returns must live until the compiler exits.
23+
24+ Depends on: Sys and Files for Linux's services, Scan for memory that
25+ lasts until exit, Diag and Fmt for paths. Leaves out: compiling and
26+ the ELF format, which are Parse and Elf's. *)
27+module Host;
28+import Sys, Files, Fmt, Diag, Scan;
29+import SYSTEM;
30+
31+type
32+ CLib* = (none, glibc, musl); (* the C library to link against *)
33+
34+const
35+ LoaderGlibc = "/lib64/ld-linux-x86-64.so.2";
36+ LoaderMusl = "/lib/ld-musl-x86_64.so.1";
37+ MemfdCreate = 319; (* the system calls raz run makes *)
38+ MfdCloexec = 1; (* an ELF still executes: the kernel opens it first *)
39+ Execve = 59;
40+ Mode755 = 1EDH; (* rwxr-xr-x *)
41+ CreateRun: ERROR = "can't create a memfd";
42+
43+(* The directory of the library, ending in what the name of raz leaves,
44+ "lib": the one beside raz as the system says (a link to raz is
45+ followed), or, with no /proc, beside argument 0 as it was typed *)
46+proc libraryDir*: []const U8;
47+var path: []const U8; error, i: INT;
48+begin
49+ path, error := Sys.readLink("/proc/self/exe");
50+ if error # 0 then path := Files.arg(0); end;
51+ i := LEN(path);
52+ while (i > 0) and (path[i - 1] # '/') do DEC(i); end;
53+ if i = 0 then return "lib"; end;
54+ return Diag.say("{}lib", [Fmt.str(path[0..i])]);
55+end;
56+
57+(* The C library a program that uses C is linked against when -libc
58+ doesn't say: glibc, or musl only if the machine has musl's loader and
59+ not glibc's, as Alpine has *)
60+proc cLibrary*: CLib;
61+begin
62+ if (Sys.access(LoaderGlibc, {}) # 0) and (Sys.access(LoaderMusl, {}) = 0) then return musl; end;
63+ return glibc;
64+end;
65+
66+(* The file at path made to hold data, an executable: written, then
67+ given mode 755. False if either failed. *)
68+proc writeExecutable*(path, data: []const U8): BOOL;
69+begin
70+ return Files.write(path, data) and (Sys.chmod(path, Mode755) >= 0);
71+end;
72+
73+(* s as a C string, in memory that is never freed *)
74+proc cstr(s: []const U8): ^U8;
75+var p: ^U8;
76+begin
77+ p := Scan.grab(LEN(s) + 1);
78+ if LEN(s) > 0 then COPY(p[0..LEN(s)], s); end;
79+ p[LEN(s)] := 0;
80+ return p;
81+end;
82+
83+(* The path raz run writes its program to: a memfd, a file that lives
84+ only in memory. Its descriptor stays open until execute, whose
85+ close-on-exec flag lets the kernel release it, or until the compiler
86+ ends after an error. *)
87+proc prepareRun*: ([]const U8, ERROR);
88+var fd: INT;
89+begin
90+ fd := SYSTEM.SYSCALL(MemfdCreate, cstr("raz"), MfdCloexec);
91+ if fd < 0 then return "", CreateRun; end;
92+ return Diag.say("/proc/self/fd/{}", [Fmt.int(fd)]), nil;
93+end;
94+
95+(* The program at path runs in the compiler's place, with the compiler's
96+ arguments from number first on as its own, first as its argument 0,
97+ and the environment. It returns only if that failed: minus the errno. *)
98+proc execute*(path: []const U8; first: INT): INT;
99+begin
100+ return SYSTEM.SYSCALL(Execve, cstr(path), SYSTEM.ARGV() + first, SYSTEM.ARGV() + (Files.argCount() + 1));
101+end;
102+
103+end Host.

src/Raz.raz (history) modified +15 -40

@@ -23,20 +23,17 @@
2323 names one. Under -bare, for the bare machine, it saves no argc and
2424 argv and runs no body of Rt (Gen.entryPoint).
2525
26- Depends on: everything else, and Version, a module the build makes
26+ Depends on: everything else, Host for what is the host system's, and Version, a module the build makes
2727 (build/src/Version.raz) from build/version.inc: what git describe
2828 says, or the make's VERSION.
2929 Leaves out: the work itself; the other units compile, link and
3030 write, and this only reads the command line and runs them in order. *)
3131 module Raz;
32-import Sys, Out, Version, Files, Fmt, Diag, Scan, Sym, Chunk, X64, Gen, Parse, Link, Elf;
32+import Sys, Out, Version, Files, Host, Fmt, Diag, Scan, Sym, Chunk, X64, Gen, Parse, Link, Elf;
3333 import SYSTEM;
3434
3535 const
3636 Report = "2026-10.38"; (* the version of doc/raz.md it follows *)
37- MemfdCreate = 319; (* the system call *)
38- MfdCloexec = 1; (* an ELF still executes: the kernel opens it first *)
39- Execve = 59;
4037
4138 var
4239 links: [4]Gen.Link;
@@ -146,15 +143,6 @@
146143 Out.flush();
147144 end;
148145
149-(* Whether a program that uses C is linked against musl when -libc
150- doesn't say: only if the machine has musl's loader and not glibc's,
151- as Alpine has *)
152-proc muslHere: BOOL;
153-begin
154- return (Sys.access("/lib64/ld-linux-x86-64.so.2", {}) # 0)
155- and (Sys.access("/lib/ld-musl-x86_64.so.1", {}) = 0);
156-end;
157-
158146 (* The module named n, or nil if the program has none *)
159147 proc moduleNamed(n: []const U8): ^Sym.Module;
160148 var m: ^Sym.Module;
@@ -189,16 +177,6 @@
189177 INC(numCLinks);
190178 end;
191179
192-(* s as a C string, in memory that is never freed *)
193-proc cstr(s: []const U8): ^U8;
194-var p: ^U8;
195-begin
196- p := Scan.grab(LEN(s) + 1);
197- if LEN(s) > 0 then COPY(p[0..LEN(s)], s); end;
198- p[LEN(s)] := 0;
199- return p;
200-end;
201-
202180 (* User libraries are source directories, not packages to discover
203181 recursively. Read NAME=value entries so an empty RAZ_PATH differs
204182 from an unset one; Sys.env alone gives "" for both. The slices and
@@ -248,8 +226,8 @@
248226
249227 proc main*: INT;
250228 var
251- path, outPath, s: []const U8; dir: []const U8;
252- i, first, entry, fd, last, errno, base: INT;
229+ path, outPath, s: []const U8;
230+ i, first, entry, last, base: INT;
253231 m, rt, thread: ^Sym.Module; mainObj: ^Sym.Obj;
254232 run, noProfile, listing, dynamic, libcSaid, ok, bare: BOOL; err: ERROR;
255233 begin
@@ -259,9 +237,9 @@
259237 bare := false;
260238 listing := false;
261239 libcSaid := false;
262- run := (ARGC() >= 2) and (Files.arg(1) = "run");
240+ run := (Files.argCount() >= 2) and (Files.arg(1) = "run");
263241 if run then i := 2; else i := 1; end;
264- while i < ARGC() do
242+ while i < Files.argCount() do
265243 s := Files.arg(i);
266244 if s = "-I" then
267245 INC(i);
@@ -315,14 +293,14 @@
315293 return 1;
316294 end;
317295 if run and (LEN(outPath) > 0) then Diag.fatal("raz run takes no -o"); end;
318- if not libcSaid then Elf.setMusl(muslHere()); end;
319- (* where raz is, as the system says, for the library beside it *)
320- dir, errno := Sys.readLink("/proc/self/exe");
321- if errno # 0 then dir := Files.arg(0); end;
322- i := LEN(dir);
323- while (i > 0) and (dir[i - 1] # '/') do DEC(i); end;
296+ if run then
297+ (* asked now, before any source is read: its error is the refusal *)
298+ outPath, err := Host.prepareRun();
299+ if err # nil then Diag.fatal(MSG(err)); end;
300+ end;
301+ if not libcSaid then Elf.setMusl(Host.cLibrary() = Host.musl); end;
324302 Parse.setVersion(Version.Text);
325- if i = 0 then Parse.setLibDir("lib"); else Parse.setLibDir(say1("{}lib", dir[0..i])); end;
303+ Parse.setLibDir(Host.libraryDir());
326304 userLibraries();
327305 if LEN(outPath) = 0 then
328306 outPath := path;
@@ -375,6 +353,7 @@
375353 Thread, if the program has it, the calls that make and join C's
376354 threads, so that the C library knows of them *)
377355 dynamic := usesC();
356+ if dynamic and (Host.cLibrary() = Host.none) then Diag.fatal("this compiler host cannot make a program that uses C"); end;
378357 if dynamic and bare then Diag.fatal("-bare: the program uses C, which needs Linux and its loader"); end;
379358 numCLinks := 0;
380359 if dynamic then
@@ -404,12 +383,8 @@
404383
405384 Elf.setMainPath(path);
406385 if run then
407- (* argv from Main.raz on is the program's, ending in nil as it must *)
408- fd := SYSTEM.SYSCALL(MemfdCreate, cstr("raz"), MfdCloexec);
409- if fd < 0 then Diag.fatal("can't create a memfd"); end;
410- outPath := Diag.say("/proc/self/fd/{}", [Fmt.int(fd)]);
411386 Elf.writeElf(outPath, entry);
412- _ := SYSTEM.SYSCALL(Execve, cstr(outPath), SYSTEM.ARGV() + first, SYSTEM.ARGV() + (ARGC() + 1));
387+ _ := Host.execute(outPath, first); (* the program's argv is ours from Main.raz on *)
413388 Diag.fatal(say1("can't run {}", path));
414389 end;
415390 Elf.writeElf(outPath, entry);

test/check.sh (history) modified +3 -0

@@ -420,5 +420,8 @@
420420 # Installed source libraries: default, explicit and isolated lookup.
421421 if test/library-path.sh "$raz"; then pass=$((pass + 1)); else fail=$((fail + 1)); fi
422422
423+# The compiler built with another host (test/host/Host.raz).
424+if test/compiler-host.sh "$raz"; then pass=$((pass + 1)); else fail=$((fail + 1)); fi
425+
423426 echo "$pass passed, $fail failed"
424427 [ $fail = 0 ]

test/compiler-host.sh (history) added (executable) +84 -0

@@ -0,0 +1,84 @@
1+#!/bin/sh
2+# Builds the compiler with another host, test/host/Host.raz in place of
3+# src/Host.raz (the staging doc/compiler.md describes), and checks what
4+# that host changes: the library it names, a refused raz run, no C, and
5+# a refused write.
6+# Usage: test/compiler-host.sh path/to/raz
7+
8+raz=$(cd "$(dirname "$1")" && pwd)/$(basename "$1")
9+top=$(mktemp -d "${TMPDIR:-/tmp}/raz-host-XXXXXX") || exit 1
10+trap 'rm -rf "$top"' EXIT
11+pass=0
12+fail=0
13+unset RAZ_PATH RAZ_PROFILE RAZ_TEST_WRITE
14+NO_COLOR=1
15+export NO_COLOR
16+
17+# check NAME COMMAND... passes if the command succeeds.
18+check() {
19+ name=$1
20+ shift
21+ if "$@"; then pass=$((pass + 1)); else echo "FAIL $name"; fail=$((fail + 1)); fi
22+}
23+
24+# says FILE TEXT: FILE holds TEXT.
25+says() { grep -q -F -- "$2" "$1"; }
26+
27+# lacks FILE TEXT: FILE doesn't hold TEXT.
28+lacks() { ! grep -q -F -- "$2" "$1"; }
29+
30+# The staged sources and the compiler built from them.
31+mkdir "$top/src" "$top/work"
32+cp src/*.raz "$top/src"
33+cp test/host/Host.raz "$top/src/Host.raz"
34+"$raz" -Werror -I "$top/src" -I build/src -o "$top/compiler" "$top/src/Raz.raz" 2>"$top/build.err" || {
35+ cat "$top/build.err"
36+ echo "FAIL the compiler with the test host doesn't build"
37+ exit 1
38+}
39+
40+# A library of its own, which only this host's libraryDir finds.
41+cp -r lib "$top/library"
42+echo "module HostValue; const value* = 42; end HostValue." >"$top/library/HostValue.raz"
43+RAZ_TEST_LIBRARY=$top/library
44+export RAZ_TEST_LIBRARY
45+
46+cd "$top/work" || exit 1
47+cat >Main.raz <<'END'
48+module Main;
49+import Out, HostValue;
50+proc main*;
51+begin Out.int(HostValue.value); Out.ln; end;
52+end Main.
53+END
54+cat >UsesC.raz <<'END'
55+module UsesC;
56+import SYSTEM;
57+extern proc getpid: I32;
58+proc main*;
59+begin _ := getpid(); end;
60+end UsesC.
61+END
62+
63+# the library comes from the host, and the file is written
64+"$top/compiler" -Werror -o program Main.raz 2>err
65+check "builds with the host's library" test "$(./program)" = 42
66+
67+# raz run is refused, before the source is read
68+"$top/compiler" run missing.raz 2>err
69+check "run is refused" says err "this test host cannot run programs"
70+check "run is refused before the source is read" lacks err "can't open"
71+
72+# no C
73+"$top/compiler" -o cprogram UsesC.raz 2>err
74+check "C is refused" says err "cannot make a program that uses C"
75+check "C leaves no file" test ! -e cprogram
76+
77+# a write the host refuses
78+rm -f program
79+RAZ_TEST_WRITE=refuse "$top/compiler" -o program Main.raz 2>err
80+check "a refused write is an error" says err "can't write"
81+check "a refused write leaves no file" test ! -e program
82+
83+echo "$pass passed, $fail failed"
84+[ $fail = 0 ]

test/host/Host.raz (history) added +46 -0

@@ -0,0 +1,46 @@
1+(* A compiler host for test/compiler-host.sh: the library is where the
2+ environment's RAZ_TEST_LIBRARY says, raz run is refused and a program
3+ that uses C is not made. With RAZ_TEST_WRITE=refuse the executable
4+ can't be written. Linux still supplies the runtime and the files. *)
5+module Host;
6+import Sys, Files;
7+
8+type
9+ CLib* = (none, glibc, musl); (* as raz's Host.raz has it *)
10+
11+const
12+ RunRefused: ERROR = "this test host cannot run programs";
13+ CannotWrite = "refuse"; (* RAZ_TEST_WRITE's value that fails the write *)
14+
15+(* The library the test sets up *)
16+proc libraryDir*: []const U8;
17+begin
18+ return Sys.env("RAZ_TEST_LIBRARY");
19+end;
20+
21+(* No C *)
22+proc cLibrary*: CLib;
23+begin
24+ return none;
25+end;
26+
27+(* The file written as it is, or not at all when the test says so *)
28+proc writeExecutable*(path, data: []const U8): BOOL;
29+begin
30+ if Sys.env("RAZ_TEST_WRITE") = CannotWrite then return false; end;
31+ return Files.write(path, data) and (Sys.chmod(path, 1EDH) >= 0);
32+end;
33+
34+(* Refused *)
35+proc prepareRun*: ([]const U8, ERROR);
36+begin
37+ return "", RunRefused;
38+end;
39+
40+(* Never reached, since prepareRun refuses *)
41+proc execute*(_path: []const U8; _first: INT): INT;
42+begin
43+ return -38;
44+end;
45+
46+end Host.