From aa75591613e407537490a7a51405b560345845ee Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Mon, 12 Oct 2026 11:07:38 +0100 Subject: [PATCH] Comments: the review's gaps in src and lib src: ELF numbers named in comments, section names found in ShNames rather than hand-counted; ModRM's RBP/R13 and RSP/R12 cases and the rip operand's end; Call's alignment pad and r11, EndProc, InstancesFor's depth count, CompileFile, the for loop's layout, the two kinds of deferred in parse.pas; hash constants, TBig's size, the real fold. lib: docs for the bare exports; Out's buffer is Sys.outSize; Fmt's rules where users see them; Sys.raz's isTerminal and yield as Linux's. test/doc and compiler.md's table follow. --- diff --git a/doc/compiler.md b/doc/compiler.md index bdf3cf8..12e66b7 100644 --- a/doc/compiler.md +++ b/doc/compiler.md @@ -9,16 +9,16 @@ | File | Lines | Code | What | |---|---|---|---| | `src/diag.pas` | 296 | 218 | Messages: positions, source excerpts, colour, counts | -| `src/scan.pas` | 851 | 722 | Symbols, literals, comments, positions | -| `src/sym.pas` | 596 | 497 | Types, objects, scopes, layout | +| `src/scan.pas` | 855 | 722 | Symbols, literals, comments, positions | +| `src/sym.pas` | 602 | 497 | Types, objects, scopes, layout | | `src/chunk.pas` | 276 | 217 | The compiled program: chunks, fixups, line notes | -| `src/x64.pas` | 1,031 | 870 | The instruction encoder, jumps within a procedure, the assembler | -| `src/gen.pas` | 1,321 | 1,039 | The stack machine, for x86-64: values, operations, checks, calls, frames | -| `src/item.pas` | 1,318 | 1,100 | Items: types, constants, variables, operators, conversions, calls | -| `src/parse.pas` | 2,559 | 2,291 | Declarations, statements, expressions, built-ins, recovery, warnings | -| `src/link.pas` | 228 | 180 | Tree shaking, layout, patching, the places | -| `src/elf.pas` | 424 | 351 | Static and dynamic ELF, symbol table, line numbers | -| `src/raz.pas` | 195 | 147 | The command line | +| `src/x64.pas` | 1,039 | 870 | The instruction encoder, jumps within a procedure, the assembler | +| `src/gen.pas` | 1,332 | 1,039 | The stack machine, for x86-64: values, operations, checks, calls, frames | +| `src/item.pas` | 1,320 | 1,100 | Items: types, constants, variables, operators, conversions, calls | +| `src/parse.pas` | 2,578 | 2,291 | Declarations, statements, expressions, built-ins, recovery, warnings | +| `src/link.pas` | 234 | 180 | Tree shaking, layout, patching, the places | +| `src/elf.pas` | 435 | 352 | Static and dynamic ELF, symbol table, line numbers | +| `src/raz.pas` | 197 | 147 | 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. diff --git a/lib/Arena.raz b/lib/Arena.raz index a59803d..f16d329 100644 --- a/lib/Arena.raz +++ b/lib/Arena.raz @@ -42,6 +42,8 @@ ar^.used := 0; end; +(* Gives the arena's block back to the system; what it handed out is + gone with it. *) proc done*(ar: ^Arena); begin if ar^.buf # nil then Mem.unmap(ar^.buf, ar^.cap); end; diff --git a/lib/Buf.raz b/lib/Buf.raz index c46c54a..bceb370 100644 --- a/lib/Buf.raz +++ b/lib/Buf.raz @@ -9,6 +9,7 @@ len*, cap: INT; end; +(* An empty buffer, which takes its memory from a. *) proc init*(b: ^Buf; a: ^Mem.Allocator); begin b^ := {a: a}; @@ -31,6 +32,8 @@ return true; end; +(* Adds the byte c at the end; if room for it can't be had, it is + dropped and the buffer is as it was. *) proc add*(b: ^Buf; c: U8); begin if room(b, 1) then @@ -39,6 +42,8 @@ end; end; +(* Adds the bytes of s at the end; if room for them can't be had, none + is added. *) proc str*(b: ^Buf; s: []U8); var i: INT; begin @@ -55,11 +60,13 @@ return b^.data[0..b^.len]; end; +(* Empties the buffer, keeping its memory for what comes next. *) proc reset*(b: ^Buf); begin b^.len := 0; end; +(* Gives the buffer's memory back, leaving it empty. *) proc done*(b: ^Buf); begin if b^.data # nil then Mem.free(b^.a, b^.data); end; diff --git a/lib/Fmt.raz b/lib/Fmt.raz index 1aef8de..3e8f24f 100644 --- a/lib/Fmt.raz +++ b/lib/Fmt.raz @@ -1,18 +1,22 @@ (* Formatted output. Each {} in the format takes the next argument: Fmt.print("{} of {}\n", [Fmt.int(n), Fmt.real(x, 2)]); - {{ and }} stand for { and }. print writes to standard output, - write appends to a Buf. *) + {{ and }} stand for { and }. A {} with no argument left prints + nothing, and arguments left over are not printed. *) module Fmt; import Out, Buf, Arena, Rt; type + (* An argument, and how it is printed. A real has places digits + after the point, at most 9, rounded to the nearest, half away + from zero; from 1E15 on, it has the exponent that makes it less + than 10, as 1.50e17; nan and inf are spelled so. *) Arg* = variant - int(i: I64); - uint(u: U64); - hex(h: U64); + int(i: I64); (* in decimal *) + uint(u: U64); (* in decimal *) + hex(h: U64); (* in hexadecimal, capitals, no 0x *) str(s: []U8); - char(c: U8); - bool(b: BOOL); + char(c: U8); (* the one byte *) + bool(b: BOOL); (* true or false *) real(r: F64; places: INT); end; @@ -36,10 +40,8 @@ if b = nil then Out.str(s); else Buf.str(b, s); end; end; -(* x with places digits after the point, at most 9, rounded to the - nearest; from 1E15 on, with the exponent that makes it less than 10, - as 1.50e17. The whole part and the fraction are taken apart, so that - each fits an I64. *) +(* x as Arg's real says. The whole part and the fraction are taken + apart, so that each fits an I64: hence the exponent from 1E15. *) proc putReal(b: ^Buf.Buf; x: F64; places: INT); const zeros = "00000000"; var d: [24]U8; at, i, e: INT; scale, whole, frac: I64; @@ -115,11 +117,13 @@ put(b, f[start..LEN(f)]); end; +(* Writes f to standard output, each {} replaced by the next of args. *) proc print*(f: []U8; args: []Arg); begin format(nil, f, args); end; +(* Appends f to b, each {} replaced by the next of args. *) proc write*(b: ^Buf.Buf; f: []U8; args: []Arg); begin format(b, f, args); diff --git a/lib/Heap.raz b/lib/Heap.raz index 540569b..006d788 100644 --- a/lib/Heap.raz +++ b/lib/Heap.raz @@ -3,9 +3,9 @@ ones; a block bigger than that gets pages of its own. Every block has a 16-byte header before it: its size class, or minus the size of its pages for a big one, which start less than a page before it; - then a marker, which says the block is out, - so that freeing it twice, or freeing what the heap never gave out, - stops the program. One lock keeps it whole across threads. *) + then a marker, which says the block is out, so that freeing it + twice, or freeing what the heap never gave out, stops the program. + One lock keeps it whole across threads. *) module Heap; import Mem, Lock, Rt; @@ -26,6 +26,7 @@ left: INT; lock: Lock.Lock; std: Mem.Allocator; + (* The heap, for NEW(p, Heap.heap) and Mem's procedures. *) heap*: ^Mem.Allocator; (* The block p, with size for its header, given out. *) diff --git a/lib/List.raz b/lib/List.raz index ae188a8..7b4d694 100644 --- a/lib/List.raz +++ b/lib/List.raz @@ -13,6 +13,7 @@ a: ^Mem.Allocator; end; +(* An empty list, its nodes from a. *) proc init*(l: ^List; a: ^Mem.Allocator); begin l^ := {a: a}; @@ -59,6 +60,7 @@ l^.head := q; end; +(* Takes every value off, giving the nodes back. *) proc clear*(l: ^List); var _ok: BOOL; _v: T; begin diff --git a/lib/Lock.raz b/lib/Lock.raz index 5c97f2c..2c85f42 100644 --- a/lib/Lock.raz +++ b/lib/Lock.raz @@ -5,8 +5,10 @@ module Lock; import Sys, Rt; +(* A lock, free when zeroed. *) type Lock* = record held: INT; end; +(* Takes l, waiting while another thread holds it. *) proc take*(l: ^Lock); var tries: INT; begin @@ -17,6 +19,7 @@ end; end; +(* Gives up l, which the caller holds. *) proc give*(l: ^Lock); begin XCHG(ADR(l^.held), 0); diff --git a/lib/Map.raz b/lib/Map.raz index 85ec0ba..127b99e 100644 --- a/lib/Map.raz +++ b/lib/Map.raz @@ -17,6 +17,7 @@ len*: INT; end; +(* An empty map, its memory from a. *) proc init*(m: ^Map; a: ^Mem.Allocator); begin m^ := {a: a}; diff --git a/lib/Math.raz b/lib/Math.raz index 7bd72a6..7744d84 100644 --- a/lib/Math.raz +++ b/lib/Math.raz @@ -10,7 +10,7 @@ import Rt; const - pi* = 3.141592653589793; + pi* = 3.141592653589793; (* the F64 nearest to pi *) ln2hi = 6.93147180369123816490E-01; (* ln 2 in two parts, whose sum is more exact than one F64 *) ln2lo = 1.90821492927058770002E-10; @@ -35,6 +35,7 @@ return bits(x) shr 63 = 1; end; +(* The square root of x, exact to the last bit; NaN for x below 0. *) proc sqrt*(x: F64): F64; code sqrtsd xmm0, xmm0; @@ -230,6 +231,7 @@ return w + (((1.0 - w) - hz) + (z * r - x * y)); end; +(* The sine of x, in radians; NaN for an infinity or NaN. *) proc sin*(x: F64): F64; var n: INT; y, yy: F64; begin @@ -244,6 +246,7 @@ return -kernelCos(y, yy); end; +(* The cosine of x, in radians; NaN for an infinity or NaN. *) proc cos*(x: F64): F64; var n: INT; y, yy: F64; begin @@ -320,6 +323,7 @@ return d <= want * 4.5E-16; end; +(* The module's test. *) proc main*; var inf, nan, hard: F64; begin diff --git a/lib/Mem.raz b/lib/Mem.raz index 12d52a8..4813a7a 100644 --- a/lib/Mem.raz +++ b/lib/Mem.raz @@ -9,7 +9,9 @@ free*: proc(a: ^Allocator; p: ^U8); end; -const Page* = 4096; +const + (* The size of a page of memory, in bytes. *) + Page* = 4096; (* size bytes, rounded up to whole pages, zeroed; or nil. *) proc pages*(size: INT): ^U8; @@ -17,16 +19,21 @@ return Sys.mmap((size + Page - 1) div Page * Page); end; +(* Gives back to the system the pages that pages gave as p, given the + same size. *) proc unmap*(p: ^U8; size: INT); begin Sys.munmap(p, (size + Page - 1) div Page * Page); end; +(* a^.alloc(a, size, align): size bytes from a, at a multiple of + align; or nil. *) proc alloc*(a: ^Allocator; size, align: INT): ^U8; begin return a^.alloc(a, size, align); end; +(* a^.free(a, p): gives p back to a, which gave it. *) proc free*(a: ^Allocator; p: ^U8); begin a^.free(a, p); diff --git a/lib/Out.raz b/lib/Out.raz index 0113ade..e3119d2 100644 --- a/lib/Out.raz +++ b/lib/Out.raz @@ -1,9 +1,10 @@ (* Writing text and numbers to standard output, through a buffer of - 4 KB. The buffer is written out when it is full, at each line feed - when standard output is a terminal, by flush, and when the program - ends by Rt.exit. C's stdio keeps a buffer of its own: a program that - writes with both flushes one before writing with the other. A lock - keeps what each call writes together when threads write at once. *) + Sys.outSize bytes. The buffer is written out when it is full, at + each line feed when standard output is a terminal, by flush, and + when the program ends by Rt.exit. C's stdio keeps a buffer of its + own: a program that writes with both flushes one before writing + with the other. A lock keeps what each call writes together when + threads write at once. *) module Out; import Rt, Sys, Lock; @@ -28,6 +29,7 @@ n := 0; end; +(* Writes out what the buffer holds. *) proc flush*; begin Lock.take(ADR(lock)); @@ -35,6 +37,7 @@ Lock.give(ADR(lock)); end; +(* Writes the bytes of s. *) proc str*(s: []U8); var i: INT; begin @@ -48,6 +51,7 @@ Lock.give(ADR(lock)); end; +(* Writes the byte c. *) proc char*(c: U8); var b: [1]U8; begin @@ -55,6 +59,7 @@ str(b); end; +(* Writes a line feed. *) proc ln*; begin char('\n'); diff --git a/lib/Rt.raz b/lib/Rt.raz index ef33a6c..a240ad1 100644 --- a/lib/Rt.raz +++ b/lib/Rt.raz @@ -14,7 +14,7 @@ import Sys; const - Full*: ERROR = "too many procedures to run at exit"; + Full*: ERROR = "too many procedures to run at exit"; (* from atExit *) MaxAtExit = 32; SigFpe = 8; SigSegv = 11; diff --git a/lib/Sort.raz b/lib/Sort.raz index 76bcb2f..a20ee5c 100644 --- a/lib/Sort.raz +++ b/lib/Sort.raz @@ -21,7 +21,8 @@ end; end; -(* s made a heap, then its largest taken, in turn, to the end. *) +(* Sorts s in place, so that no element is less than the one before + it. Not stable. *) proc sort*(s: []T); var i: INT; t: T; begin diff --git a/lib/Str.raz b/lib/Str.raz index 8dfb6fe..022e252 100644 --- a/lib/Str.raz +++ b/lib/Str.raz @@ -23,6 +23,7 @@ return 0; end; +(* Whether a and b hold the same bytes: a = b, as a procedure value. *) proc eq*(a, b: []U8): BOOL; begin return a = b; @@ -49,6 +50,7 @@ return -1; end; +(* Whether s starts with p. *) proc hasPrefix*(s, p: []U8): BOOL; begin return (LEN(s) >= LEN(p)) and (s[0..LEN(p)] = p); diff --git a/lib/Sys.linux-x86_64.raz b/lib/Sys.linux-x86_64.raz index dcc2030..772cc44 100644 --- a/lib/Sys.linux-x86_64.raz +++ b/lib/Sys.linux-x86_64.raz @@ -3,9 +3,9 @@ module Sys; const - stdin* = 0; - stdout* = 1; - stderr* = 2; + stdin* = 0; (* standard input's file descriptor *) + stdout* = 1; (* standard output's *) + stderr* = 2; (* standard error's *) (* the bytes Out keeps before it writes them; a target with little memory keeps fewer *) outSize* = 4096; @@ -18,7 +18,7 @@ (* What open is asked for: reading, writing or both, and what else it does to the file. *) Access* = (reading, writing, creating, exclusive, truncating, appending); - Accesses* = set of Access; + Accesses* = set of Access; (* what open is given *) (* What info says of a file. *) Info* = record @@ -153,6 +153,7 @@ return SYSCALL(8, fd, pos, 0); (* SEEK_SET *) end; +(* Closes the file descriptor fd. *) proc close*(fd: INT); begin SYSCALL(3, fd); @@ -168,6 +169,7 @@ return ^U8(p); end; +(* Gives back to the system the size bytes at p that mmap gave. *) proc munmap*(p: ^U8; size: INT); begin SYSCALL(11, p, size); @@ -297,6 +299,7 @@ return "", false; end; +(* Closes the directory d that openDir opened. *) proc closeDir*(d: ^Dir); begin SYSCALL(3, d^.fd); diff --git a/lib/Sys.raz b/lib/Sys.raz index 01db7d5..349653a 100644 --- a/lib/Sys.raz +++ b/lib/Sys.raz @@ -12,9 +12,9 @@ import C; const - stdin* = 0; - stdout* = 1; - stderr* = 2; + stdin* = 0; (* standard input's file descriptor *) + stdout* = 1; (* standard output's *) + stderr* = 2; (* standard error's *) (* the bytes Out keeps before it writes them; a target with little memory keeps fewer *) outSize* = 4096; @@ -31,7 +31,7 @@ (* What open is asked for: reading, writing or both, and what else it does to the file. *) Access* = (reading, writing, creating, exclusive, truncating, appending); - Accesses* = set of Access; + Accesses* = set of Access; (* what open is given *) (* What info says of a file. *) Info* = record @@ -186,6 +186,7 @@ return r; end; +(* Closes the file descriptor fd. *) proc close*(fd: INT); begin C.close(I32(fd)); @@ -201,6 +202,7 @@ return p; end; +(* Gives back to the system the size bytes at p that mmap gave. *) proc munmap*(p: ^U8; size: INT); begin C.munmap(p, UINT(size)); @@ -316,6 +318,7 @@ return "", false; end; +(* Closes the directory d that openDir opened. *) proc closeDir*(d: ^Dir); begin C.closedir(d^.d); @@ -861,11 +864,13 @@ return 0; end; +(* Whether the file descriptor fd is a terminal. *) proc isTerminal*(fd: INT): BOOL; begin return C.isatty(I32(fd)) = 1; end; +(* Gives the processor to another thread. *) proc yield*; begin C.sched_yield(); diff --git a/lib/Thread.linux-x86_64.raz b/lib/Thread.linux-x86_64.raz index 0078dc3..e2e3020 100644 --- a/lib/Thread.linux-x86_64.raz +++ b/lib/Thread.linux-x86_64.raz @@ -4,8 +4,8 @@ rather than spoiling what lies below; above it, a little stack for Rt's signal handlers, so that they can say so. join waits on the thread's id, which the kernel clears, and wakes it for, when the - thread ends; a Mutex sleeps on a futex. A program with C threads uses C's, - through pthread_create, and so can't use these. *) + thread ends; a Mutex sleeps on a futex. A program with C threads + uses C's, through pthread_create, and so can't use these. *) module Thread; import Sys, Rt; link static; @@ -23,6 +23,7 @@ Private = 128; type + (* A thread, as spawn gives it, until join. *) Thread* = record tid: INT; (* the kernel's id, until the thread ends *) base: ^U8; (* its stack's mapping, the guard page first *) @@ -32,7 +33,8 @@ end; (* What sigaltstack takes *) AltStack = record sp: ^U8; flags, size: INT; end; - (* 0 free, 1 taken, 2 taken with a thread waiting *) + (* A lock whose waiters sleep, free when zeroed. Its state is 0 + free, 1 taken, 2 taken with a thread waiting. *) Mutex* = record state: INT; end; (* clone(flags, stack, tid, tid), the new thread starting with fn(arg) @@ -120,6 +122,7 @@ Sys.munmap(base, size); end; +(* Takes m, sleeping while another thread holds it. *) proc lock*(m: ^Mutex); var c: INT; begin @@ -131,6 +134,8 @@ end; end; +(* Gives up m, which the caller holds, waking a thread that waits + for it. *) proc unlock*(m: ^Mutex); begin if XADD(ADR(m^.state), -1) # 1 then diff --git a/src/elf.pas b/src/elf.pas index a82d01b..776fc3b 100644 --- a/src/elf.pas +++ b/src/elf.pas @@ -93,9 +93,17 @@ PutN(align, 8); end; -procedure Shdr(name, typ: longint; flags, adr, off, size: int64; lnk, info: longint; align, entsize: int64); +const + { the section names, in .shstrtab; a section header names its own } + ShNames = #0'.text'#0'.rodata'#0'.bss'#0'.symtab'#0'.strtab'#0'.shstrtab'#0 + + '.dynamic'#0'.dynstr'#0'.dynsym'#0'.debug_line'#0'.debug_info'#0'.debug_abbrev'#0; + +{ A section header. Its name is given as a string and stored as its + offset in ShNames: the #0 before it, counted from 1, is that offset + counted from 0; the empty name, found nowhere, is 0. } +procedure Shdr(const name: shortstring; typ: longint; flags, adr, off, size: int64; lnk, info: longint; align, entsize: int64); begin - PutN(name, 4); PutN(typ, 4); PutN(flags, 8); PutN(adr, 8); + PutN(Pos(#0 + name + #0, ShNames), 4); PutN(typ, 4); PutN(flags, 8); PutN(adr, 8); PutN(off, 8); PutN(size, 8); PutN(lnk, 4); PutN(info, 4); PutN(align, 8); PutN(entsize, 8); end; @@ -301,9 +309,6 @@ end; procedure WriteElf(const path: shortstring; entry: longint); -const - ShNames = #0'.text'#0'.rodata'#0'.bss'#0'.symtab'#0'.strtab'#0'.shstrtab'#0 + - '.dynamic'#0'.dynstr'#0'.dynsym'#0'.debug_line'#0'.debug_info'#0'.debug_abbrev'#0; var nph, nsh, c, nsyms, fd: longint; roExtra, dynSize, symOff, strOff, shstrOff, shOff, strsLen: int64; @@ -329,7 +334,8 @@ end; { ELF header } - PutN($464C457F, 4); PutN(2, 1); PutN(1, 1); PutN(1, 1); PutN(0, 9); + PutN($464C457F, 4); { #127 'ELF' } + PutN(2, 1); PutN(1, 1); PutN(1, 1); PutN(0, 9); { 64-bit, little-endian, version 1 } PutN(2, 2); { ET_EXEC } PutN(62, 2); { EM_X86_64 } PutN(1, 4); @@ -340,8 +346,9 @@ nsh := 10; if dynamic then nsh := 13; PutN(64, 2); PutN(56, 2); PutN(nph, 2); - PutN(64, 2); PutN(nsh, 2); PutN(6, 2); + PutN(64, 2); PutN(nsh, 2); PutN(6, 2); { .shstrtab is section 6 } + { flags: 4 read, 5 read and run, 6 read and write } if dynamic then Phdr(PtInterp, 4, extraAdr - Base, extraAdr, length(Interp) + 1, length(Interp) + 1, 1); { the first segment maps the headers too, so text can follow them } Phdr(PtLoad, 5, 0, Base, textOff + textSize, textOff + textSize, Page); @@ -372,7 +379,7 @@ if strsLen + length(s) + 1 > MemSize(strs) then strs := ReAllocMem(strs, strsLen * 2 + 256); Move(s[1], strs^[strsLen], length(s)); strs^[strsLen + length(s)] := 0; - case chunks^[c].sec of + case chunks^[c].sec of { the section's index in the headers below } secText: sec := 1; secRodata: sec := 2; else sec := 3; @@ -396,21 +403,25 @@ PadTo((len + 7) div 8 * 8); shOff := len; Patch(40, shOff, 8); - Shdr(0, 0, 0, 0, 0, 0, 0, 0, 0, 0); - Shdr(1, 1, 6, Base + textOff, textOff, textSize, 0, 0, 16, 0); - Shdr(7, 1, 2, Base + roOff, roOff, roSize, 0, 0, 16, 0); - Shdr(15, 8, 3, bssAdr + dynSize, roOff + roSize, bssSize - dynSize, 0, 0, 16, 0); - Shdr(20, 2, 0, 0, symOff, nsyms * 24, 5, nsyms, 8, 24); - Shdr(28, 3, 0, 0, strOff, strsLen, 0, 0, 1, 0); - Shdr(36, 3, 0, 0, shstrOff, length(ShNames), 0, 0, 1, 0); + { types: 1 PROGBITS, 2 SYMTAB, 3 STRTAB, 6 DYNAMIC, 8 NOBITS, 11 DYNSYM; + flags: 2 ALLOC, 3 WRITE+ALLOC, 6 ALLOC+EXECINSTR. A symbol table's + link is its string table's index: 5 .strtab, 8 .dynstr. The order + here is the index the code above relies on. } + Shdr('', 0, 0, 0, 0, 0, 0, 0, 0, 0); + Shdr('.text', 1, 6, Base + textOff, textOff, textSize, 0, 0, 16, 0); + Shdr('.rodata', 1, 2, Base + roOff, roOff, roSize, 0, 0, 16, 0); + Shdr('.bss', 8, 3, bssAdr + dynSize, roOff + roSize, bssSize - dynSize, 0, 0, 16, 0); + Shdr('.symtab', 2, 0, 0, symOff, nsyms * 24, 5, nsyms, 8, 24); + Shdr('.strtab', 3, 0, 0, strOff, strsLen, 0, 0, 1, 0); + Shdr('.shstrtab', 3, 0, 0, shstrOff, length(ShNames), 0, 0, 1, 0); if dynamic then begin { the loader's tables, for readelf and objdump } - Shdr(46, 6, 3, bssAdr, bssAdr - Base, dynSize, 8, 0, 8, 16); - Shdr(55, 3, 2, extraAdr + strAt, extraAdr + strAt - Base, strLen, 0, 0, 1, 0); - Shdr(63, 11, 2, extraAdr + symAt, extraAdr + symAt - Base, nsym * 24, 8, 1, 8, 24); + Shdr('.dynamic', 6, 3, bssAdr, bssAdr - Base, dynSize, 8, 0, 8, 16); + Shdr('.dynstr', 3, 2, extraAdr + strAt, extraAdr + strAt - Base, strLen, 0, 0, 1, 0); + Shdr('.dynsym', 11, 2, extraAdr + symAt, extraAdr + symAt - Base, nsym * 24, 8, 1, 8, 24); end; - Shdr(71, 1, 0, 0, dbgOff[0], dbgSize[0], 0, 0, 1, 0); - Shdr(83, 1, 0, 0, dbgOff[1], dbgSize[1], 0, 0, 1, 0); - Shdr(95, 1, 0, 0, dbgOff[2], dbgSize[2], 0, 0, 1, 0); + Shdr('.debug_line', 1, 0, 0, dbgOff[0], dbgSize[0], 0, 0, 1, 0); + 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); p := path + #0; fd := FpOpen(@p[1], O_WRONLY or O_CREAT or O_TRUNC, &755); diff --git a/src/gen.pas b/src/gen.pas index 5ee96c3..13f1930 100644 --- a/src/gen.pas +++ b/src/gen.pas @@ -10,8 +10,8 @@ is a new gen.pas, with an encoder of its own. The stack is kept in registers, as in Wirth's compilers: the value at - depth d in register d, of r8 to r11, a deeper one spilled to the frame - while its register is wanted. A constant is only noted until something + depth d in r8 to r11, register d mod 4, a deeper one's register taken + by spilling the shallower value it held to the frame. A constant is only noted until something needs it in a register, so that it can be an instruction's operand. Calls use the System V convention. Arguments are computed left to @@ -993,6 +993,9 @@ { Calls } +{ The call c, its arguments already in their frame slots: they go to + registers or the stack, the procedure is called, and its result, if + any, is pushed on the value stack. } procedure Call(var c: TCall); var res: PType; i, ni, nf, k, pad, r: longint; @@ -1014,6 +1017,8 @@ else begin onStack[i] := ni >= 6; if ni < 6 then inc(ni) end; if onStack[i] then inc(k); end; + { System V wants rsp a multiple of 16 at the call: a quadword of + padding makes the count pushed since the frame began even } pad := ord(odd(pushed + k)); if pad <> 0 then AluI(aluSub, RSP, 8); for i := c.n - 1 downto 0 do @@ -1032,6 +1037,8 @@ if c.ext then CallM(MemRip(c.chunk, 0)) else if c.chunk >= 0 then CallChunk(c.chunk) else begin + { r11 is scratch: caller-saved, carrying no argument, and free, + as the value stack was spilled above } Load(R11, Mem(RBP, c.target), 8, false); CallR(R11); end; @@ -1194,6 +1201,8 @@ Jmp(exitL); end; +{ The end of the procedure in chunk c: the code that returns, and the + frame's size, known only now, patched into its prologue. } procedure EndProc(c: longint); var n: int64; begin @@ -1218,6 +1227,8 @@ if n < 16 then n := 16; if n > high(longint) then Mark('frame too big'); Put4At(frameFix, n); + { the listing's text for the sub, which starts 3 bytes (REX.W, opcode, + ModRM) before its immediate } Restate(frameFix - 3, 'sub rsp, ' + IntStr(n)); EndChunk(c); end; diff --git a/src/item.pas b/src/item.pas index 2dc163c..631835b 100644 --- a/src/item.pas +++ b/src/item.pas @@ -1028,6 +1028,8 @@ end else if (s^.form = fReal) and (t^.form = fInt) then begin if x.mode = mConst then begin r := RealOf(x); + { NaN or out of range folds to low(int64), the "integer + indefinite" cvttsd2si gives at run time } if (r <> r) or (r >= 9.2233720368547758e18) or (r < -9.2233720368547758e18) then x.val := Cut(low(int64), t) else x.val := Cut(trunc(r), t); diff --git a/src/link.pas b/src/link.pas index cac7600..9b623c5 100644 --- a/src/link.pas +++ b/src/link.pas @@ -40,6 +40,7 @@ implementation +{ Marks live each chunk reached from entry through the fixups. } procedure MarkLive(entry: longint); var stack: PLongs; sp, c, f, t: longint; begin @@ -52,6 +53,7 @@ dec(sp); c := stack^[sp]; if chunks^[c].size < 0 then Fatal(ChunkName(c) + ' is declared but never defined'); + { only code has fixups: data holds no addresses, so it uses nothing } if chunks^[c].sec <> secText then continue; for f := chunks^[c].firstFix to chunks^[c].firstFix + chunks^[c].numFix - 1 do begin t := fixups^[f].chunk; @@ -154,6 +156,9 @@ { the pool of paths and names starts at k } k := 40 + 16 * n + 20 * np + 12 * nv; names := k; + { the paths first, at the offsets offs gave the places: Name puts + each in the pool, and also writes its offset at at, which a path + doesn't want, so at is put back for the procedures to overwrite } for f := 0 to nfiles - 1 do begin i := at; Name(ShownPath(NameOf(files^[f]))); @@ -188,7 +193,7 @@ procedure LinkAll(headerSize, roExtra, dynSize: int64); var c, f, at: longint; e, p, v: int64; begin - textOff := (headerSize + 15) div 16 * 16; + textOff := (headerSize + 15) div 16 * 16; { as each code chunk is } e := Place(secText, Base + textOff); textSize := e - (Base + textOff); if placesChunk >= 0 then MakePlaces(Base + textOff, e); @@ -202,6 +207,7 @@ bssSize := e - bssAdr; textImg := GetMem(textSize + 1); + { the gaps between code chunks are int3, a trap if ever run } FillChar(textImg^, textSize + 1, $CC); roImg := GetMem(roSize + 1); FillChar(roImg^, roSize + 1, 0); diff --git a/src/parse.pas b/src/parse.pas index f8c4291..d4fd68e 100644 --- a/src/parse.pas +++ b/src/parse.pas @@ -52,7 +52,8 @@ base: longint; { the deferred statements in force outside it } end; - { A generic module's import whose instance isn't made yet } + { A generic module's import whose instance isn't made yet (deferred, + numDeferred); not to be confused with a defer statement (defers) } TDeferred = record o: PObj; { the name it imports as } m: PModule; { the module that imports it } @@ -72,9 +73,9 @@ curProc: PObj; { the procedure being compiled, or nil } declExported: boolean; { the export mark of the declaration being read } curLoop: PLoop; { the innermost loop, or nil } - defers: array[0..63] of longint; { the deferred statements in force } + defers: array[0..63] of longint; { the defer statements in force, their code's addresses } numDefers: longint; - deferring: boolean; { compiling a deferred statement } + deferring: boolean; { compiling a defer statement's statement } directDefer: boolean; { ... as the statement itself, not in a list } deferSlot: int64; { keeps a result while deferred statements run } curResult: PType; { the result type of the procedure being compiled } @@ -84,7 +85,7 @@ declaring: array[0..63] of longint; { the names the declaration being read declares } numDeclaring: longint; skipped: boolean; { the last statement had an error and was skipped } - deferred: array[0..63] of TDeferred; + deferred: array[0..63] of TDeferred; { generic imports not yet made, not defer statements } numDeferred: longint; making: boolean; { reading an instance's arguments, at its first use } stray: boolean; { an "end" in this procedure stood left of its statement's line } @@ -1260,6 +1261,13 @@ Fix(lp.brk); end; +{ for v := a to b by s do ... end, laid out as + v := a; bslot := b + top: if v is past bslot then goto exit + the statements + if the distance from v to bslot < |s| then goto exit (ForNext) + v := v + s; goto top + exit: } procedure ForStatement(const start: TPos; ind: longint); var o: PObj; v, a, b, s: TItem; bslot, step: int64; top, exitL: longint; @@ -2229,6 +2237,11 @@ Exists := (FpStat(@p[1], st) = 0) and ((st.st_mode and S_IFMT) = S_IFREG); end; +{ Compiles module n from path, an instance if args are given, or only + reads its interface if checkOnly; returns it. An import calls this in + the middle of reading another file, so it is re-entrant: it saves the + scanner's state, the open scopes, the current module and file and + whether checks are on, and puts them back at the end. } function CompileFile(const path: shortstring; n: longint; const args: TArgs; checkOnly: boolean): PModule; var st: TScanState; saved: array[0..MaxDepth - 1] of longint; d: longint; @@ -2562,6 +2575,12 @@ i := numDeferred - 1; while (i >= 0) and (deferred[i].m <> curModule) do dec(i); if i < 0 then exit; + { The procedure ends at the "end" that closes its first "begin": d + counts the words still open that "end" or "until" closes, and begun + says that begin was met, so that a record's end in its declarations + doesn't stop it. A forward or code procedure has no raz body to + read, so it stops at that word. The body reads to the end of the + file, as wholeRest says. } SaveScan(st); d := 0; begun := false; repeat diff --git a/src/raz.pas b/src/raz.pas index 2353658..25d3b9e 100644 --- a/src/raz.pas +++ b/src/raz.pas @@ -7,10 +7,10 @@ Compiles the main module and every module it imports, writes the entry point, links what it reaches, and writes the executable: by default the main module's file without its .raz; with -S, it lists - the main module's code instead. raz run writes it - to a memfd instead, a file that lives only in memory, and executes - it in raz's place with the arguments after Main.raz, so its status - is the program's; its argv[0] is Main.raz. + the main module's code instead. raz run writes it to a memfd + instead, a file that lives only in memory, and executes it in raz's + place with the arguments after Main.raz, so its status is the + program's; its argv[0] is Main.raz. The program starts by saving argc and argv, runs every module's body (those of the modules the program imports, imported modules first), @@ -20,7 +20,9 @@ C up and calls this as C's main; first it gives Rt C's exit, which Rt.exit then ends the program with. - Depends on: everything else. } + Depends on: everything else. + Leaves out: the work itself; the other units compile, link and + write, and this only reads the command line and runs them in order. } program raz; diff --git a/src/scan.pas b/src/scan.pas index 92c6fc4..98e6964 100644 --- a/src/scan.pas +++ b/src/scan.pas @@ -562,6 +562,10 @@ n: longint; { words in use; 0 is zero } w: array[0..95] of longword; { least significant first } end; + { 96 words, 3072 bits, are plenty: a shortstring holds at most 255 + digits, so ReadReal's den is at most 10^(330 + 255), about 2^1944, + and num below 10^310; the shift that follows makes the larger one at + most 54 bits longer than den, about 2000 bits in all. } { a := a * m + add } procedure BigMul(var a: TBig; m, add: longword); diff --git a/src/sym.pas b/src/sym.pas index 6e3c5ae..4480423 100644 --- a/src/sym.pas +++ b/src/sym.pas @@ -253,11 +253,17 @@ TopScope := scopes[depth - 1]; end; +{ Where the search for name in scope s starts in the hash table: each + number is multiplied by an odd constant near 2^32 or 2^16 over the + golden ratio (Knuth's multiplicative hashing), which spreads the low + bits the mask keeps. } function Slot(s, name: longint): longint; begin Slot := longint((longword(s) * 2654435761 xor longword(name) * 40503) and longword(hashMask)); end; +{ Doubles the table, which Insert keeps at most half full so that the + linear probing stays short, and puts every entry in its new slot. } procedure Rehash; var old: PObjTab; n, i, j: longint; begin @@ -489,7 +495,7 @@ declared in each file stands for the other's. } procedure Mix(var h: qword; v: int64); begin - h := (h xor qword(v)) * 1099511628211; + h := (h xor qword(v)) * 1099511628211; { FNV-1a's 64-bit prime } end; procedure Shape(var h: qword; t: PType; top: boolean); @@ -521,7 +527,7 @@ function Fingerprint(o: PObj): qword; var h: qword; f: PObj; begin - h := 14695981039346656037; + h := 14695981039346656037; { FNV-1a's 64-bit offset basis } Mix(h, ord(o^.cls)); if o^.cls = oCase then begin Mix(h, o^.val); diff --git a/src/x64.pas b/src/x64.pas index 7194b4e..edd1829 100644 --- a/src/x64.pas +++ b/src/x64.pas @@ -193,16 +193,24 @@ reg := reg and 7; if m.base = RIP then begin Put1(reg shl 3 or 5); - { the rip-relative displacement counts from the end of the - instruction, which these instructions end with } + { mod 00 with r/m 101 is rip + disp32. The displacement counts + from the end of the instruction, and the fixup takes it to end + with these four bytes: no rip operand has an immediate after it, + since only the compiler's loads, stores, lea and call make one + (the assembler can't name a chunk). } AddFixup(pc, m.chunk, m.disp); Put4(0); exit; end; b := m.base and 7; + { mod 00 takes no displacement, but with r/m 101 (RBP or R13) it means + rip-relative, or disp32 under a SIB byte, so those bases take a + zero disp8 } if (m.disp = 0) and (b <> RBP) then md := 0 else if (m.disp >= -128) and (m.disp <= 127) then md := 1 else md := 2; + { r/m 100 (RSP or R12) means a SIB byte follows, so those bases need + one, with index 100 meaning none } if (m.index <> NoIndex) or (b = RSP) then begin Put1(md shl 6 or reg shl 3 or 4); case m.scale of 1: sc := 0; 2: sc := 1; 4: sc := 2; else sc := 3; end; diff --git a/test/doc/Str.expect b/test/doc/Str.expect index ad54ec8..dabc054 100644 --- a/test/doc/Str.expect +++ b/test/doc/Str.expect @@ -7,6 +7,7 @@ -1, 0 or 1 as a sorts before, with or after b, byte by byte. proc eq*(a, b: []U8): BOOL; + Whether a and b hold the same bytes: a = b, as a procedure value. proc hash*(s: []U8): U64; FNV-1a, 64 bits. @@ -15,6 +16,7 @@ Where sub first starts in s, or -1. proc hasPrefix*(s, p: []U8): BOOL; + Whether s starts with p. proc encode*(c: I32): ([4]U8, INT); c in UTF-8: its bytes, and how many. A number that isn't a diff --git a/test/doc/Thread.expect b/test/doc/Thread.expect index fdae2cb..b6449b6 100644 --- a/test/doc/Thread.expect +++ b/test/doc/Thread.expect @@ -5,8 +5,8 @@ rather than spoiling what lies below; above it, a little stack for Rt's signal handlers, so that they can say so. join waits on the thread's id, which the kernel clears, and wakes it for, when the - thread ends; a Mutex sleeps on a futex. A program with C threads uses C's, - through pthread_create, and so can't use these. + thread ends; a Mutex sleeps on a futex. A program with C threads + uses C's, through pthread_create, and so can't use these. const Failed*: ERROR = "can't start a thread"; @@ -17,9 +17,11 @@ fn: proc(arg: ^U8); (* what it runs, and with what *) arg: ^U8; end; + A thread, as spawn gives it, until join. type Mutex* = record state: INT; end; - 0 free, 1 taken, 2 taken with a thread waiting + A lock whose waiters sleep, free when zeroed. Its state is 0 + free, 1 taken, 2 taken with a thread waiting. proc spawn*(p: proc(arg: ^U8); arg: ^U8): (^Thread, ERROR); Starts p(arg) in a new thread. @@ -28,7 +30,10 @@ Waits for t to end, then frees its stack. proc lock*(m: ^Mutex); + Takes m, sleeping while another thread holds it. proc unlock*(m: ^Mutex); + Gives up m, which the caller holds, waking a thread that waits + for it. proc main*; diff --git a/test/run/ThreadOverflow.stderr b/test/run/ThreadOverflow.stderr index 0cd7fb1..c3884f5 100644 --- a/test/run/ThreadOverflow.stderr +++ b/test/run/ThreadOverflow.stderr @@ -3,4 +3,4 @@ in ThreadOverflow.down at test/run/ThreadOverflow.raz:10:5: n = 1926 and 1926 more the same in ThreadOverflow.work at test/run/ThreadOverflow.raz:15:5: _arg = nil - in Thread.run at lib/Thread.linux-x86_64.raz:78:5: arg = 0x?, t = 0x? + in Thread.run at lib/Thread.linux-x86_64.raz:80:5: arg = 0x?, t = 0x?