From 7a137131f83d6e669aa07bafa65975feb6941933 Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:14:39 +0000 Subject: [PATCH] Host: the compiler's five asks of the system it runs on, in one module --- diff --git a/doc/compiler.md b/doc/compiler.md index 9ea2873..b82d744 100644 --- a/doc/compiler.md +++ b/doc/compiler.md @@ -1,6 +1,6 @@ # Reading the raz compiler -The compiler is eleven files of raz, about 12,700 lines of code (the +The compiler is twelve files of raz, about 12,700 lines of code (the budget is 14,000). It is its own compiler: a release of it, the one `BOOT` names, builds `src/`, and `make fixpoint` checks that what it makes makes itself again, byte for byte. Each release was built by the @@ -26,7 +26,8 @@ | `src/Parse.raz` | 4,816 | 4,098 | Declarations, statements, expressions, built-ins, recovery, warnings | | `src/Link.raz` | 408 | 316 | Tree shaking, layout, patching, the places | | `src/Elf.raz` | 450 | 356 | Static and dynamic ELF, symbol table, line numbers | -| `src/Raz.raz` | 419 | 334 | The command line | +| `src/Host.raz` | 103 | 52 | The system running the compiler | +| `src/Raz.raz` | 394 | 316 | The command line | Every file opens with a comment that says what it is, what it depends on and what it leaves out. Read those first; they are the map. @@ -2190,7 +2191,7 @@ `/lib64/ld-linux-x86-64.so.2` and `libc.so.6`, or musl's, `/lib/ld-musl-x86_64.so.1` and `libc.so`, which musl's loader, being the library itself, takes to mean itself (`Elf.setMusl`). `-libc` -chooses; left out, `Raz.muslHere` chooses musl where the machine has +chooses; left out, `Host.cLibrary` does: musl where the machine has its loader and not glibc's, as Alpine does. A symbol that isn't live gets no relocation, so a program runs over a C library that lacks a procedure it declares but never reaches. `sizeTables` and `putTables` lay these out in the room `Link.raz` left @@ -2201,6 +2202,48 @@ it, which `putDebug` writes. There are no types or variables in it; gdb can stop at a line and show where it is, not print a variable. +## Host.raz: the system running the compiler + +The host is the system running raz; the target is the system its +program will run on. Everything the compiler asks of its host that the +library doesn't give is in `Host.raz`, five procedures, each a real +difference between hosts. Nothing else in `src/` makes a system call, +reads `argv`, opens `/proc` or sets a file's mode; it reads, writes and +lists files, the environment and the working directory through the +library (`Sys`, `Files`), and `Files.argCount` and `Files.arg` give it +its command line. + +- `libraryDir`: the directory of the standard library. Linux's is the + `lib` beside raz, found by `/proc/self/exe` so that a link to raz + works, or, with no `/proc`, beside argument 0. +- `cLibrary`: `CLib = (none, glibc, musl)`, the C library a program that + uses C is linked against when `-libc` doesn't say. `none` says the + host can't make such a program, and `Raz` refuses one when it finds + the program uses C. Linux's is glibc, or musl where only its loader + is there. +- `writeExecutable`: the bytes `Elf` made, written as an executable. + Linux's writes the file and sets mode 755. It returns false on any + failure, which `Elf` reports. +- `prepareRun`: the path `raz run` writes to, or an error, which is the + refusal of a host that can't run a program. Linux's is a memfd, + `/proc/self/fd/N`, kept open until `execute`. +- `execute`: replaces the compiler with the program at that path, whose + arguments are the compiler's from number `first` on (so its argument 0 + is `Main.raz`), and the environment. It returns only on failure. + +**Building for another host.** Stage the sources: copy `src/` to a +directory, put that host's `Host.raz` there in place of raz's, and +build `Raz.raz` from the copy with that host's library. This is the one +way; raz knows no host but Linux. A module in the main file's +directory is found first, so `-I` alone can't replace `Host.raz`, which +is right: a module is never replaced silently. The new file keeps every +export, `CLib` too, and opens with what it is, as raz's does. +`test/host/Host.raz` is such a file (its library from the environment, +no run, no C), and `test/compiler-host.sh` builds the compiler with it +and checks the four differences. The host changes nothing of the target: +a program for another system still needs that system's `Sys` and `Rt`, +and for a kernel the options `-bare`, `-s` and `-base`. + ## Raz.raz: the command line `Raz.raz` parses the arguments, calls `Parse.compileMain`, and works out what @@ -2212,8 +2255,8 @@ for `Rt.cExit`, and, if the program has `Thread`, `pthread_create` and `pthread_join` for `Thread.cCreate` and `Thread.cJoin`. Then it has gen's `entryPoint` write the entry point, and `Link.markLive` mark what it -reaches. The program is `proc main*: INT`; where raz is, for the library -beside it, it reads from `/proc/self/exe`, and the version it prints is +reaches. The program is `proc main*: INT`; `Host` says where the library is and +which C library to use by default (below), and the version it prints is the module `Version`, which the build makes from `git describe`. On a target without reals (`HasReals`, a constant of `Parse`; x86-64 has them), a live chunk that computes with one is an error at the first @@ -2235,10 +2278,13 @@ program that uses C is refused. `raz -S` lists the code (`X64.list`) instead of writing -it. `raz run` writes the executable to a memfd, a file only in memory, and -executes it through `/proc/self/fd` in raz's own place, handing it the -rest of raz's `argv`. Nothing is left on disk, and the program's -status is the command's. +it. `raz run` writes the executable to the path `Host.prepareRun` gives +and has `Host.execute` run it in raz's own place, handing it the rest +of raz's arguments. On Linux the path is a memfd, a file only in +memory, so nothing is left on disk, and the program's status is the +command's. `prepareRun` is called as soon as the command line is read, +before any source, so a host that can't run refuses there. The +arguments are read through `Files.argCount` and `Files.arg`. Before compiling, `userLibraries` reads `RAZ_PATH` with `Sys.envAt`, which distinguishes an unset variable from an explicitly empty one. diff --git a/src/Elf.raz b/src/Elf.raz index f747135..2ac06e9 100644 --- a/src/Elf.raz +++ b/src/Elf.raz @@ -14,8 +14,8 @@ There is no PLT and no lazy binding, and the program exports nothing. Depends on: Link for the images and addresses, Chunk for the chunks, - Scan for names and memory, Diag for errors, Sys and Files to write - the file. + Scan for names and memory, Diag for errors, Sys for the working + directory, and Host to write the file. Leaves out: position independent executables, symbol versions, the rest of DWARF. @@ -25,7 +25,7 @@ Exported variables can't be set from outside, so needLib, setMusl, setMainPath and setStripped do it. *) module Elf; -import Sys, Files, Fmt, Diag, Scan, Chunk, Link; +import Sys, Host, Fmt, Diag, Scan, Chunk, Link; import SYSTEM; var @@ -440,7 +440,7 @@ shdr(".debug_info", 1, 0, 0, dbgOff[1], dbgSize[1], 0, 0, 1, 0); shdr(".debug_abbrev", 1, 0, 0, dbgOff[2], dbgSize[2], 0, 0, 1, 0); - if not Files.write(path, buf[0..len]) or (Sys.chmod(path, 1EDH) < 0) then + if not Host.writeExecutable(path, buf[0..len]) then Diag.fatal(Diag.say("can't write {}", [Fmt.str(path)])); end; end; diff --git a/src/Host.raz b/src/Host.raz new file mode 100644 index 0000000..6d5cc66 --- /dev/null +++ b/src/Host.raz @@ -0,0 +1,103 @@ +(* Host: what the compiler asks of the system it runs on, beyond the + library. The host is the system running raz; the target, the one its + program will run on. This file is Linux's. + + Another host stages its own file in its place: copy src/ to a + directory, put that host's Host.raz there instead of this one, and + build the copy with the host's library (doc/compiler.md says how). + Raz and Elf import only this module for what follows, so a host + gives these five procedures and keeps every export: + + libraryDir where the standard library is, as a directory path + cLibrary which C library a program that uses C is linked + against by default, or none if the host can't make one + writeExecutable the file at path made to hold an executable + prepareRun the path raz run writes its program to, or an error + if this host can't run it; asked first, before any + source is read, so its error is the refusal + execute replaces the compiler with the program written there + + A host that can't run programs refuses in prepareRun and gives + execute any body; one that has no C gives cLibrary the value none. + Strings it returns must live until the compiler exits. + + Depends on: Sys and Files for Linux's services, Scan for memory that + lasts until exit, Diag and Fmt for paths. Leaves out: compiling and + the ELF format, which are Parse and Elf's. *) +module Host; +import Sys, Files, Fmt, Diag, Scan; +import SYSTEM; + +type + CLib* = (none, glibc, musl); (* the C library to link against *) + +const + LoaderGlibc = "/lib64/ld-linux-x86-64.so.2"; + LoaderMusl = "/lib/ld-musl-x86_64.so.1"; + MemfdCreate = 319; (* the system calls raz run makes *) + MfdCloexec = 1; (* an ELF still executes: the kernel opens it first *) + Execve = 59; + Mode755 = 1EDH; (* rwxr-xr-x *) + CreateRun: ERROR = "can't create a memfd"; + +(* The directory of the library, ending in what the name of raz leaves, + "lib": the one beside raz as the system says (a link to raz is + followed), or, with no /proc, beside argument 0 as it was typed *) +proc libraryDir*: []const U8; +var path: []const U8; error, i: INT; +begin + path, error := Sys.readLink("/proc/self/exe"); + if error # 0 then path := Files.arg(0); end; + i := LEN(path); + while (i > 0) and (path[i - 1] # '/') do DEC(i); end; + if i = 0 then return "lib"; end; + return Diag.say("{}lib", [Fmt.str(path[0..i])]); +end; + +(* The C library a program that uses C is linked against when -libc + doesn't say: glibc, or musl only if the machine has musl's loader and + not glibc's, as Alpine has *) +proc cLibrary*: CLib; +begin + if (Sys.access(LoaderGlibc, {}) # 0) and (Sys.access(LoaderMusl, {}) = 0) then return musl; end; + return glibc; +end; + +(* The file at path made to hold data, an executable: written, then + given mode 755. False if either failed. *) +proc writeExecutable*(path, data: []const U8): BOOL; +begin + return Files.write(path, data) and (Sys.chmod(path, Mode755) >= 0); +end; + +(* s as a C string, in memory that is never freed *) +proc cstr(s: []const U8): ^U8; +var p: ^U8; +begin + p := Scan.grab(LEN(s) + 1); + if LEN(s) > 0 then COPY(p[0..LEN(s)], s); end; + p[LEN(s)] := 0; + return p; +end; + +(* The path raz run writes its program to: a memfd, a file that lives + only in memory. Its descriptor stays open until execute, whose + close-on-exec flag lets the kernel release it, or until the compiler + ends after an error. *) +proc prepareRun*: ([]const U8, ERROR); +var fd: INT; +begin + fd := SYSTEM.SYSCALL(MemfdCreate, cstr("raz"), MfdCloexec); + if fd < 0 then return "", CreateRun; end; + return Diag.say("/proc/self/fd/{}", [Fmt.int(fd)]), nil; +end; + +(* The program at path runs in the compiler's place, with the compiler's + arguments from number first on as its own, first as its argument 0, + and the environment. It returns only if that failed: minus the errno. *) +proc execute*(path: []const U8; first: INT): INT; +begin + return SYSTEM.SYSCALL(Execve, cstr(path), SYSTEM.ARGV() + first, SYSTEM.ARGV() + (Files.argCount() + 1)); +end; + +end Host. diff --git a/src/Raz.raz b/src/Raz.raz index fa86e1b..58cf884 100644 --- a/src/Raz.raz +++ b/src/Raz.raz @@ -23,20 +23,17 @@ names one. Under -bare, for the bare machine, it saves no argc and argv and runs no body of Rt (Gen.entryPoint). - Depends on: everything else, and Version, a module the build makes + Depends on: everything else, Host for what is the host system's, and Version, a module the build makes (build/src/Version.raz) from build/version.inc: what git describe says, or the make's VERSION. Leaves out: the work itself; the other units compile, link and write, and this only reads the command line and runs them in order. *) module Raz; -import Sys, Out, Version, Files, Fmt, Diag, Scan, Sym, Chunk, X64, Gen, Parse, Link, Elf; +import Sys, Out, Version, Files, Host, Fmt, Diag, Scan, Sym, Chunk, X64, Gen, Parse, Link, Elf; import SYSTEM; const Report = "2026-10.38"; (* the version of doc/raz.md it follows *) - MemfdCreate = 319; (* the system call *) - MfdCloexec = 1; (* an ELF still executes: the kernel opens it first *) - Execve = 59; var links: [4]Gen.Link; @@ -146,15 +143,6 @@ Out.flush(); end; -(* Whether a program that uses C is linked against musl when -libc - doesn't say: only if the machine has musl's loader and not glibc's, - as Alpine has *) -proc muslHere: BOOL; -begin - return (Sys.access("/lib64/ld-linux-x86-64.so.2", {}) # 0) - and (Sys.access("/lib/ld-musl-x86_64.so.1", {}) = 0); -end; - (* The module named n, or nil if the program has none *) proc moduleNamed(n: []const U8): ^Sym.Module; var m: ^Sym.Module; @@ -189,16 +177,6 @@ INC(numCLinks); end; -(* s as a C string, in memory that is never freed *) -proc cstr(s: []const U8): ^U8; -var p: ^U8; -begin - p := Scan.grab(LEN(s) + 1); - if LEN(s) > 0 then COPY(p[0..LEN(s)], s); end; - p[LEN(s)] := 0; - return p; -end; - (* User libraries are source directories, not packages to discover recursively. Read NAME=value entries so an empty RAZ_PATH differs from an unset one; Sys.env alone gives "" for both. The slices and @@ -248,8 +226,8 @@ proc main*: INT; var - path, outPath, s: []const U8; dir: []const U8; - i, first, entry, fd, last, errno, base: INT; + path, outPath, s: []const U8; + i, first, entry, last, base: INT; m, rt, thread: ^Sym.Module; mainObj: ^Sym.Obj; run, noProfile, listing, dynamic, libcSaid, ok, bare: BOOL; err: ERROR; begin @@ -259,9 +237,9 @@ bare := false; listing := false; libcSaid := false; - run := (ARGC() >= 2) and (Files.arg(1) = "run"); + run := (Files.argCount() >= 2) and (Files.arg(1) = "run"); if run then i := 2; else i := 1; end; - while i < ARGC() do + while i < Files.argCount() do s := Files.arg(i); if s = "-I" then INC(i); @@ -315,14 +293,14 @@ return 1; end; if run and (LEN(outPath) > 0) then Diag.fatal("raz run takes no -o"); end; - if not libcSaid then Elf.setMusl(muslHere()); end; - (* where raz is, as the system says, for the library beside it *) - dir, errno := Sys.readLink("/proc/self/exe"); - if errno # 0 then dir := Files.arg(0); end; - i := LEN(dir); - while (i > 0) and (dir[i - 1] # '/') do DEC(i); end; + if run then + (* asked now, before any source is read: its error is the refusal *) + outPath, err := Host.prepareRun(); + if err # nil then Diag.fatal(MSG(err)); end; + end; + if not libcSaid then Elf.setMusl(Host.cLibrary() = Host.musl); end; Parse.setVersion(Version.Text); - if i = 0 then Parse.setLibDir("lib"); else Parse.setLibDir(say1("{}lib", dir[0..i])); end; + Parse.setLibDir(Host.libraryDir()); userLibraries(); if LEN(outPath) = 0 then outPath := path; @@ -375,6 +353,7 @@ Thread, if the program has it, the calls that make and join C's threads, so that the C library knows of them *) dynamic := usesC(); + if dynamic and (Host.cLibrary() = Host.none) then Diag.fatal("this compiler host cannot make a program that uses C"); end; if dynamic and bare then Diag.fatal("-bare: the program uses C, which needs Linux and its loader"); end; numCLinks := 0; if dynamic then @@ -404,12 +383,8 @@ Elf.setMainPath(path); if run then - (* argv from Main.raz on is the program's, ending in nil as it must *) - fd := SYSTEM.SYSCALL(MemfdCreate, cstr("raz"), MfdCloexec); - if fd < 0 then Diag.fatal("can't create a memfd"); end; - outPath := Diag.say("/proc/self/fd/{}", [Fmt.int(fd)]); Elf.writeElf(outPath, entry); - _ := SYSTEM.SYSCALL(Execve, cstr(outPath), SYSTEM.ARGV() + first, SYSTEM.ARGV() + (ARGC() + 1)); + _ := Host.execute(outPath, first); (* the program's argv is ours from Main.raz on *) Diag.fatal(say1("can't run {}", path)); end; Elf.writeElf(outPath, entry); diff --git a/test/check.sh b/test/check.sh index d13a4e8..8849187 100755 --- a/test/check.sh +++ b/test/check.sh @@ -420,5 +420,8 @@ # Installed source libraries: default, explicit and isolated lookup. if test/library-path.sh "$raz"; then pass=$((pass + 1)); else fail=$((fail + 1)); fi +# The compiler built with another host (test/host/Host.raz). +if test/compiler-host.sh "$raz"; then pass=$((pass + 1)); else fail=$((fail + 1)); fi + echo "$pass passed, $fail failed" [ $fail = 0 ] diff --git a/test/compiler-host.sh b/test/compiler-host.sh new file mode 100755 index 0000000..136c17b --- /dev/null +++ b/test/compiler-host.sh @@ -0,0 +1,84 @@ +#!/bin/sh +# Builds the compiler with another host, test/host/Host.raz in place of +# src/Host.raz (the staging doc/compiler.md describes), and checks what +# that host changes: the library it names, a refused raz run, no C, and +# a refused write. +# Usage: test/compiler-host.sh path/to/raz + +raz=$(cd "$(dirname "$1")" && pwd)/$(basename "$1") +top=$(mktemp -d "${TMPDIR:-/tmp}/raz-host-XXXXXX") || exit 1 +trap 'rm -rf "$top"' EXIT +pass=0 +fail=0 +unset RAZ_PATH RAZ_PROFILE RAZ_TEST_WRITE +NO_COLOR=1 +export NO_COLOR + +# check NAME COMMAND... passes if the command succeeds. +check() { + name=$1 + shift + if "$@"; then pass=$((pass + 1)); else echo "FAIL $name"; fail=$((fail + 1)); fi +} + +# says FILE TEXT: FILE holds TEXT. +says() { grep -q -F -- "$2" "$1"; } + +# lacks FILE TEXT: FILE doesn't hold TEXT. +lacks() { ! grep -q -F -- "$2" "$1"; } + +# The staged sources and the compiler built from them. +mkdir "$top/src" "$top/work" +cp src/*.raz "$top/src" +cp test/host/Host.raz "$top/src/Host.raz" +"$raz" -Werror -I "$top/src" -I build/src -o "$top/compiler" "$top/src/Raz.raz" 2>"$top/build.err" || { + cat "$top/build.err" + echo "FAIL the compiler with the test host doesn't build" + exit 1 +} + +# A library of its own, which only this host's libraryDir finds. +cp -r lib "$top/library" +echo "module HostValue; const value* = 42; end HostValue." >"$top/library/HostValue.raz" +RAZ_TEST_LIBRARY=$top/library +export RAZ_TEST_LIBRARY + +cd "$top/work" || exit 1 +cat >Main.raz <<'END' +module Main; +import Out, HostValue; +proc main*; +begin Out.int(HostValue.value); Out.ln; end; +end Main. +END +cat >UsesC.raz <<'END' +module UsesC; +import SYSTEM; +extern proc getpid: I32; +proc main*; +begin _ := getpid(); end; +end UsesC. +END + +# the library comes from the host, and the file is written +"$top/compiler" -Werror -o program Main.raz 2>err +check "builds with the host's library" test "$(./program)" = 42 + +# raz run is refused, before the source is read +"$top/compiler" run missing.raz 2>err +check "run is refused" says err "this test host cannot run programs" +check "run is refused before the source is read" lacks err "can't open" + +# no C +"$top/compiler" -o cprogram UsesC.raz 2>err +check "C is refused" says err "cannot make a program that uses C" +check "C leaves no file" test ! -e cprogram + +# a write the host refuses +rm -f program +RAZ_TEST_WRITE=refuse "$top/compiler" -o program Main.raz 2>err +check "a refused write is an error" says err "can't write" +check "a refused write leaves no file" test ! -e program + +echo "$pass passed, $fail failed" +[ $fail = 0 ] diff --git a/test/host/Host.raz b/test/host/Host.raz new file mode 100644 index 0000000..6c1bcc3 --- /dev/null +++ b/test/host/Host.raz @@ -0,0 +1,46 @@ +(* A compiler host for test/compiler-host.sh: the library is where the + environment's RAZ_TEST_LIBRARY says, raz run is refused and a program + that uses C is not made. With RAZ_TEST_WRITE=refuse the executable + can't be written. Linux still supplies the runtime and the files. *) +module Host; +import Sys, Files; + +type + CLib* = (none, glibc, musl); (* as raz's Host.raz has it *) + +const + RunRefused: ERROR = "this test host cannot run programs"; + CannotWrite = "refuse"; (* RAZ_TEST_WRITE's value that fails the write *) + +(* The library the test sets up *) +proc libraryDir*: []const U8; +begin + return Sys.env("RAZ_TEST_LIBRARY"); +end; + +(* No C *) +proc cLibrary*: CLib; +begin + return none; +end; + +(* The file written as it is, or not at all when the test says so *) +proc writeExecutable*(path, data: []const U8): BOOL; +begin + if Sys.env("RAZ_TEST_WRITE") = CannotWrite then return false; end; + return Files.write(path, data) and (Sys.chmod(path, 1EDH) >= 0); +end; + +(* Refused *) +proc prepareRun*: ([]const U8, ERROR); +begin + return "", RunRefused; +end; + +(* Never reached, since prepareRun refuses *) +proc execute*(_path: []const U8; _first: INT): INT; +begin + return -38; +end; + +end Host.