From 88b789e53c77e62703574eca885270552f2f3ca1 Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Sat, 10 Oct 2026 11:13:44 +0000 Subject: [PATCH] Step 14: line numbers for gdb The compiler notes the line of each statement, and of each procedure's first line and end, as it writes the code. The executable carries a DWARF 4 line table, one sequence per live procedure, and the one compile unit gdb needs to find it. make gdb checks that gdb stops at a line and names each caller's line. Stage 3 done: the plan records its lines. --- diff --git a/CLAUDE.md b/CLAUDE.md index d959d3e..b150ff7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -12,6 +12,7 @@ make bench # must report at least 400,000 lines a second make loc # lines of the compiler; the code column is the budget make tests # the small Pascal tests of scan, x64, link and elf + make gdb # gdb stops at a line of a test and names it `make check` must pass before every commit. Tests: `test/run/X.jed` with `X.expect` (stdout), optional `X.status` and `X.args`; modules they @@ -37,9 +38,8 @@ ## Where things stand -Stages 1 and 2 are done (steps 1-10). Stage 3 (steps 11-14) is under -way: its report changes are written and approved, and steps 11 to 13 -are done. Next is step 14, line numbers for gdb. +Stages 1 to 3 are done (steps 1-14), waiting for review. Next is step +15, `tools/Doc.jed` and the checked examples, on the owner's go-ahead. `test/libc` runs its programs over `lib/Sys.jed`, the C one, through a link in its `mods`. A test or example without `.expect` is only diff --git a/Makefile b/Makefile index 89d168d..8f8b30a 100644 --- a/Makefile +++ b/Makefile @@ -27,6 +27,10 @@ check: jed test/check.sh +# line numbers: gdb stops at a line and names it +gdb: jed + test/gdb.sh + # the compiler's speed, on a generated program of about 350,000 lines, # the best of three runs; fails below 400,000 lines a second bench: jed | build @@ -44,4 +48,4 @@ loc: @python3 test/loc.py src/*.pas -.PHONY: units tests check bench loc clean +.PHONY: units tests check gdb bench loc clean diff --git a/PLAN.md b/PLAN.md index 7c83de7..1da580a 100644 --- a/PLAN.md +++ b/PLAN.md @@ -55,20 +55,20 @@ ## The compiler, in reading order -Lines after stage 2, all of them and those of code (neither blank nor +Lines after stage 3, all of them and those of code (neither blank nor only comment), as `make loc` counts them: | File | Lines | Code | What | |---|---|---|---| | `src/scan.pas` | 548 | 471 | Symbols, literals, comments, error messages | -| `src/sym.pas` | 492 | 410 | Types, objects, scopes, layout | -| `src/x64.pas` | 620 | 497 | Code buffer, chunks, fixups, instruction encoder | -| `src/gen.pas` | 1,354 | 1,193 | Items: loading, storing, copying, frames, calls | -| `src/parse.pas` | 1,754 | 1,626 | Declarations, statements, expressions, built-ins | -| `src/link.pas` | 123 | 92 | Tree shaking, layout, patching | -| `src/elf.pas` | 185 | 147 | Static ELF, symbol table | -| `src/jed.pas` | 111 | 83 | The command line, the entry point | -| total | 5,187 | 4,519 | | +| `src/sym.pas` | 508 | 422 | Types, objects, scopes, layout | +| `src/x64.pas` | 680 | 546 | Code buffer, chunks, fixups, line notes, instruction encoder | +| `src/gen.pas` | 1,414 | 1,240 | Items: loading, storing, copying, frames, calls | +| `src/parse.pas` | 1,816 | 1,685 | Declarations, statements, expressions, built-ins | +| `src/link.pas` | 131 | 95 | Tree shaking, layout, patching | +| `src/elf.pas` | 424 | 350 | Static and dynamic ELF, symbol table, line numbers | +| `src/jed.pas` | 183 | 145 | The command line, the entry points | +| total | 5,704 | 4,954 | | ## Steps @@ -124,7 +124,7 @@ and a `Mutex` through `futex`. `link static;` marks a module that needs a program without C; the compiler refuses a program that uses both. -- [ ] 14. Line numbers for gdb: `.debug_line`, with the least of +- [x] 14. Line numbers for gdb: `.debug_line`, with the least of `.debug_info` and `.debug_abbrev` that gdb needs. Tools diff --git a/doc/jed.md b/doc/jed.md index 80b399c..f2ffb6d 100644 --- a/doc/jed.md +++ b/doc/jed.md @@ -796,6 +796,8 @@ Only what can be reached from `main` and the module bodies goes into the executable: unused procedures, variables and strings are left out. +The executable names its procedures and carries line numbers, so that +gdb can stop at a line of the source and show where it is. **Defined behaviour.** Every variable starts at zero, integers wrap, and indexing arrays and slices is checked, so a program's behaviour is diff --git a/src/elf.pas b/src/elf.pas index eff6c8f..b1ca65d 100644 --- a/src/elf.pas +++ b/src/elf.pas @@ -3,7 +3,9 @@ Writes an ELF64 executable for x86-64 Linux: the ELF header, the program headers, the linked text and rodata, and section headers with a symbol table, so that objdump and gdb can name each procedure - and variable. + and variable. For gdb's line numbers there is DWARF 4: a line table + (.debug_line), and the one compile unit that points to it + (.debug_info, .debug_abbrev). There are no types or variables. A program that uses C is linked dynamically, in the least way the loader accepts: it names its loader and libraries, and each C symbol @@ -13,7 +15,8 @@ Depends on: link for the images and addresses, x64 for the chunks, scan for names and errors, BaseUnix to write the file. - Leaves out: position independent executables, symbol versions. } + Leaves out: position independent executables, symbol versions, the + rest of DWARF. } unit elf; @@ -26,6 +29,7 @@ var needed: array[0..31] of longint; { the libraries to load, names interned } numNeeded: longint; { none: a static program } + mainPath: shortstring; { the main module's file, for gdb } procedure WriteElf(const path: shortstring; entry: longint); @@ -102,6 +106,112 @@ PutN(0, 1); end; +{ LEB128, unsigned and signed } +procedure PutU(v: qword); +begin + while v >= $80 do begin + PutN(v and $7F or $80, 1); + v := v shr 7; + end; + PutN(v, 1); +end; + +procedure PutS(v: int64); +begin + while (v < -64) or (v >= 64) do begin + PutN(v and $7F or $80, 1); + v := SarInt64(v, 7); + end; + PutN(v and $7F, 1); +end; + +{ The line table: one sequence for each live procedure with lines, + rows made only with the standard opcodes, no special ones. Then the + compile unit, which names the table, and its abbreviation. Section + offsets go in off, sizes in size: line, info, abbrev. } +procedure PutDebug(var off, size: array of int64); +var + files: array[0..255] of longint; nfiles, i, f, c, cf, cl: longint; + at: int64; cwd: array[0..255] of char; +begin + nfiles := 0; + for i := 0 to numLines - 1 do + if chunks^[lines^[i].chunk].live then begin + f := 0; + while (f < nfiles) and (files[f] <> lines^[i].path) do inc(f); + if (f = nfiles) and (nfiles <= High(files)) then begin + files[f] := lines^[i].path; + inc(nfiles); + end; + end; + + off[0] := len; + PutN(0, 4); { unit_length, patched below } + PutN(4, 2); { version } + PutN(0, 4); { header_length, patched below } + PutN(1, 1); PutN(1, 1); { minimum_instruction_length, maximum_operations } + PutN(1, 1); { default_is_stmt } + PutN(-5 and $FF, 1); PutN(14, 1); PutN(13, 1); { line_base, line_range, opcode_base } + for i := 1 to 12 do PutN(ord(i in [2, 3, 4, 5, 9, 12]), 1); { their operands } + PutN(0, 1); { no include directories } + for f := 0 to nfiles - 1 do begin + PutStr(NameOf(files[f])); + PutN(0, 3); { directory, time, length } + end; + PutN(0, 1); + Patch(off[0] + 6, len - off[0] - 10, 4); + i := 0; + while i < numLines do begin + c := lines^[i].chunk; + if not chunks^[c].live then begin inc(i); continue end; + PutN(0, 1); PutU(9); PutN(2, 1); { DW_LNE_set_address } + PutN(chunks^[c].adr + lines^[i].at - chunks^[c].start, 8); + at := lines^[i].at; cf := 1; cl := 1; + while (i < numLines) and (lines^[i].chunk = c) do begin + if lines^[i].at > at then begin + PutN(2, 1); PutU(lines^[i].at - at); { DW_LNS_advance_pc } + at := lines^[i].at; + end; + f := 1; + while (f <= nfiles) and (files[f - 1] <> lines^[i].path) do inc(f); + if f <> cf then begin PutN(4, 1); PutU(f); cf := f end; { DW_LNS_set_file } + if lines^[i].line <> cl then begin { DW_LNS_advance_line } + PutN(3, 1); PutS(lines^[i].line - cl); + cl := lines^[i].line; + end; + PutN(1, 1); { DW_LNS_copy: a row } + inc(i); + end; + PutN(2, 1); PutU(chunks^[c].start + chunks^[c].size - at); + PutN(0, 1); PutU(1); PutN(1, 1); { DW_LNE_end_sequence } + end; + Patch(off[0], len - off[0] - 4, 4); + size[0] := len - off[0]; + + off[1] := len; + PutN(0, 4); PutN(4, 2); PutN(0, 4); PutN(8, 1); { length, version, abbrev, address size } + PutU(1); + PutStr(mainPath); + if FpGetcwd(@cwd, SizeOf(cwd)) = nil then cwd[0] := #0; + PutStr(PChar(@cwd)); + PutStr('jed'); + PutN(0, 4); { the line table, at 0 } + PutN(Base + textOff, 8); PutN(textSize, 8); { the code, all of it } + Patch(off[1], len - off[1] - 4, 4); + size[1] := len - off[1]; + + off[2] := len; + PutU(1); PutU($11); PutN(0, 1); { 1: a compile unit, no children } + PutU($03); PutU($08); { name, a string } + PutU($1B); PutU($08); { comp_dir, a string } + PutU($25); PutU($08); { producer, a string } + PutU($10); PutU($17); { stmt_list, a section offset } + PutU($11); PutU($01); { low_pc, an address } + PutU($12); PutU($07); { high_pc, a length in 8 bytes } + PutN(0, 2); PutN(0, 1); + size[2] := len - off[2]; +end; + const Interp = '/lib64/ld-linux-x86-64.so.2'; { program header types } @@ -192,10 +302,11 @@ 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; + '.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; + dbgOff, dbgSize: array[0..2] of int64; strs: PBytes; s, p: shortstring; sec: longint; @@ -226,8 +337,8 @@ PutN(64, 8); { program headers follow } PutN(0, 8); { section headers: patched below } PutN(0, 4); - nsh := 7; - if dynamic then nsh := 10; + 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); @@ -280,6 +391,7 @@ shstrOff := len; s := ShNames; PutBytes(@s[1], length(s)); + PutDebug(dbgOff, dbgSize); PadTo((len + 7) div 8 * 8); shOff := len; @@ -296,6 +408,9 @@ 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); 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); 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 1acf0e7..9df19f7 100644 --- a/src/gen.pas +++ b/src/gen.pas @@ -113,7 +113,7 @@ procedure KeepTemps; procedure BeginProc(sig: PType; params: PObj); -procedure EnterBody(c: longint); +procedure EnterBody(c, line: longint); procedure ReturnValue(var x: TItem); procedure ReturnField(f: PObj; var x: TItem); procedure ReturnJump; @@ -1258,10 +1258,12 @@ end; end; -procedure EnterBody(c: longint); +{ The prologue, which is for the procedure's first line. } +procedure EnterBody(c, line: longint); var i, top: longint; begin BeginChunk(c); + NoteLine(line); Push(RBP); MovRR(RBP, RSP); Put1($48); Put1($81); Put1($EC); { sub rsp, imm32 } diff --git a/src/jed.pas b/src/jed.pas index 93f07f6..8c274b0 100644 --- a/src/jed.pas +++ b/src/jed.pas @@ -178,5 +178,6 @@ Ud2; EndChunk(start); + mainPath := path; WriteElf(outPath, entry); end. diff --git a/src/parse.pas b/src/parse.pas index 5238608..32194cd 100644 --- a/src/parse.pas +++ b/src/parse.pas @@ -1145,6 +1145,7 @@ procedure Statement; var x, y: TItem; called: boolean; m: int64; c: TCall; begin + NoteLine(CurLine); m := TempMark; case tok of sIdent: begin @@ -1242,7 +1243,7 @@ procedure Declarations(top: boolean); forward; -procedure Body(p: PObj; sig: PType); +procedure Body(p: PObj; sig: PType; line: longint); var q, params, last, o: PObj; old: PType; begin OpenScope(NewScope); @@ -1268,8 +1269,9 @@ Expect(sBegin, 'begin'); old := curResult; curResult := sig^.base; - EnterBody(p^.chunk); + EnterBody(p^.chunk, line); Statements; + NoteLine(CurLine); Expect(sEnd, 'end'); EndProc(p^.chunk); curResult := old; @@ -1308,8 +1310,9 @@ end; procedure ProcDecl; -var n: longint; exp: boolean; sig: PType; p: PObj; +var n, line: longint; exp: boolean; sig: PType; p: PObj; begin + line := CurLine; Next; IdentDef(n, exp); sig := Signature; @@ -1339,7 +1342,7 @@ CodeBody(p, sig); exit; end; - if checkMode then SkipBody else Body(p, sig); + if checkMode then SkipBody else Body(p, sig, line); if tok = sIdent then begin if id <> n then Mark('the procedure is ' + NameOf(n)); Next; @@ -1583,11 +1586,12 @@ var st: TScanState; saved: array[0..MaxDepth - 1] of longint; d: longint; oldMod: PModule; oldFile: longint; oldCheck: boolean; m, im: PModule; - imp: PImport; lib: PLib; alias, mname: longint; o: PObj; body: longint; iargs: TArgs; + imp: PImport; lib: PLib; alias, mname, line, oldPath: longint; o: PObj; body: longint; iargs: TArgs; begin SaveScan(st); SaveScopes(d, saved); - oldMod := curModule; oldFile := fileChunk; oldCheck := checkMode; + oldMod := curModule; oldFile := fileChunk; oldCheck := checkMode; oldPath := curFile; + curFile := Name(path); if not Open(path) then Fatal('can''t read ' + path); New(m); FillChar(m^, SizeOf(TModule), 0); @@ -1659,14 +1663,16 @@ if tok = sBegin then begin if checkMode then SkipBody else begin + line := CurLine; Next; body := NewChunk(secText, m^.sname, nameBody); m^.body := body; BeginProc(tBodySig, nil); deferSlot := 0; curResult := nil; - EnterBody(body); + EnterBody(body, line); Statements; + NoteLine(CurLine); Expect(sEnd, 'end'); EndProc(body); end; @@ -1686,7 +1692,7 @@ if lastModule = nil then firstModule := m else lastModule^.next := m; lastModule := m; end; - curModule := oldMod; fileChunk := oldFile; checkMode := oldCheck; + curModule := oldMod; fileChunk := oldFile; checkMode := oldCheck; curFile := oldPath; RestoreScopes(d, saved); RestoreScan(st); CompileFile := m; diff --git a/src/x64.pas b/src/x64.pas index 8f06ee8..83964ef 100644 --- a/src/x64.pas +++ b/src/x64.pas @@ -61,6 +61,12 @@ ext: boolean; { bss: the address of a C symbol, its name } end; + { A source line whose code starts at a place in text, for gdb } + TLine = record + at, chunk: longint; { the place in text, and its chunk } + path, line: longint; { the file's path, interned, and the line } + end; + TFixup = record at: longint; { the rel32 field, as an offset in text } chunk: longint; { the chunk it refers to } @@ -69,6 +75,8 @@ PChunks = ^TChunkArray; TChunkArray = array[0..MaxInt div SizeOf(TChunk) - 1] of TChunk; + PLines = ^TLineArray; + TLineArray = array[0..MaxInt div SizeOf(TLine) - 1] of TLine; PFixups = ^TFixupArray; TFixupArray = array[0..MaxInt div SizeOf(TFixup) - 1] of TFixup; @@ -81,6 +89,9 @@ numChunks: longint; fixups: PFixups; numFixups: longint; + lines: PLines; + numLines: longint; + curFile: longint; { the file being compiled, for NoteLine } function NewChunk(sec: TSection; module, name: longint): longint; procedure BeginChunk(c: longint); @@ -88,6 +99,7 @@ procedure SetData(c: longint; p: PBytes; n, align: longint); procedure SetBss(c: longint; size, align: longint); function ExternChunk(name: longint): longint; +procedure NoteLine(line: longint); procedure Put1(b: longint); procedure Put4(v: longint); @@ -152,7 +164,8 @@ implementation var - codeCap, roCap, chunkCap, fixCap: longint; + codeCap, roCap, chunkCap, fixCap, lineCap: longint; + curChunk: longint; { Buffers and chunks } @@ -214,6 +227,7 @@ begin { code is aligned to 16 bytes, padded with int3 } while pc and 15 <> 0 do Put1($CC); + curChunk := c; chunks^[c].start := pc; chunks^[c].align := 16; chunks^[c].firstFix := numFixups; @@ -244,6 +258,24 @@ chunks^[c].align := align; end; +{ The code from here on is for line of the current file. A line with + no code of its own gives way to the next. } +procedure NoteLine(line: longint); +begin + if (numLines > 0) and (lines^[numLines - 1].at = pc) then dec(numLines); + if (numLines > 0) and (lines^[numLines - 1].chunk = curChunk) + and (lines^[numLines - 1].line = line) and (lines^[numLines - 1].path = curFile) then exit; + if numLines = lineCap then begin + lineCap := lineCap * 2; + lines := ReAllocMem(lines, lineCap * SizeOf(TLine)); + end; + lines^[numLines].at := pc; + lines^[numLines].chunk := curChunk; + lines^[numLines].path := curFile; + lines^[numLines].line := line; + inc(numLines); +end; + { The quadword that holds the address of C's symbol name, filled in when the program starts; one for each name. } function ExternChunk(name: longint): longint; @@ -642,4 +674,7 @@ fixCap := 1 shl 12; fixups := GetMem(fixCap * SizeOf(TFixup)); numFixups := 0; + lineCap := 1 shl 12; + lines := GetMem(lineCap * SizeOf(TLine)); + numLines := 0; end. diff --git a/test/gdb.sh b/test/gdb.sh new file mode 100755 index 0000000..30ec5d7 --- /dev/null +++ b/test/gdb.sh @@ -0,0 +1,16 @@ +#!/bin/sh +# Line numbers for gdb: stops a test program at a line of its source, +# by file and line, and checks that gdb names it, and the line of each +# caller. +out=build/check +mkdir -p $out +./jed -I test/run/mods -o $out/Procs test/run/Procs.jed || exit 1 +gdb -batch -ex 'break test/run/Procs.jed:13' -ex run -ex bt $out/Procs > $out/gdb.out 2>&1 +for want in 'Breakpoint 1, Procs.odd () at test/run/Procs.jed:13' \ + 'in Procs.even () at test/run/Procs.jed:20' \ + 'in Procs.main () at test/run/Procs.jed:'; do + if ! grep -qF "$want" $out/gdb.out; then + echo "FAIL gdb: no \"$want\""; cat $out/gdb.out; exit 1 + fi +done +echo "gdb finds the lines"