From 1e15c9a29ed69d208f8d23d00c78a88d91e92f13 Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Sat, 10 Oct 2026 11:04:50 +0000 Subject: [PATCH] Step 11: extern proc and var, link, dynamic ELF; Rt.exit, Rt.atExit, buffered Out A program that uses C is linked dynamically and starts through __libc_start_main; each C symbol is a quadword the loader fills in. Rt.exit runs what Rt.atExit registered, then ends through C's exit in a C program. Out buffers 4 KB. lib/C.jed declares the C library's parts that lib/Sys.jed, Sys over C, uses; test/libc runs on it. Examples: printf beside Out, and an X11 window. --- diff --git a/CLAUDE.md b/CLAUDE.md index 1d85306..b287937 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -37,12 +37,14 @@ ## Where things stand -Stages 1 and 2 are done (steps 1-10). Next is stage 3 (steps 11-14), -waiting for a go-ahead. Its first task is to write into the report, for -review: `F32` and untyped real literals, `extern var`, `link static`, -`Rt.exit` and `Rt.atExit`, and how to mix `Out` with C's `stdio` (flush -one before using the other). Unions are not added: the report shows -reading a C union as an array of words through pointer conversions. +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 step 11 is done. +Next is step 12, `F32`, which also makes an `F32` given to `...` an +error. + +`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 +compiled (`examples/Window.jed` needs a display). ## Readings of the report already taken @@ -67,6 +69,15 @@ and sliced. - A deferred statement's frame slots stay reserved for the rest of its procedure. +- A program uses C if a module it uses (not one read only for an + interface check) has an `extern` or a `link` of a library. `static` + in `link static;` is not a reserved word. +- C symbols are reached through quadwords the loader fills in + (GLOB_DAT), with no PLT; the executable exports nothing. In a C + program the entry point stores C's `exit` in `Rt.cExit`, found by + name like `Rt.exit`, before any module body runs. +- Past an extern's parameters, a string goes as a C string and an + integer constant as an `I64`. - Every failed check says "index out of range"; some errors point at the symbol after the offending expression. Error messages are to be improved later, all together. diff --git a/PLAN.md b/PLAN.md index 1040301..e030e23 100644 --- a/PLAN.md +++ b/PLAN.md @@ -101,7 +101,7 @@ Stage 3: calling C, and what comes with it -- [ ] 11. `extern proc`, `extern var` and `link`; dynamic ELF, start +- [x] 11. `extern proc`, `extern var` and `link`; dynamic ELF, start through `__libc_start_main`. A plain `lib/Sys.jed` over the C library, the default for targets with no file of their own. Examples with `printf` to `stdout`, and an X11 window, reading diff --git a/doc/jed.md b/doc/jed.md index d2c6fb9..2e959e0 100644 --- a/doc/jed.md +++ b/doc/jed.md @@ -814,6 +814,7 @@ | `Rt` | ending the program, `exit` and `atExit`; what the compiler's checks call when they fail; string comparison | | `Sys` | system calls: `write`, `mmap`, `munmap`, `exit`; one file per target, and `Sys.jed` over the C library for the others | | `Out` | writing text and numbers to standard output, buffered | +| `C` | the parts of the C library the others use, and `printf`, `fflush`, `stdout`; a program that imports it uses C | | `Mem` | `Allocator`, the interface of every allocator, and pages from the system | | `Heap` | a general allocator, `Heap.heap` | | `Arena` | an allocator that frees everything at once; `ADR(arena.base)` is its allocator | diff --git a/examples/Printf.expect b/examples/Printf.expect new file mode 100644 index 0000000..68d4068 --- /dev/null +++ b/examples/Printf.expect @@ -0,0 +1,6 @@ +jed says 1 +C says 1, squared +jed says 2 +C says 4, squared +jed says 3 +C says 9, squared diff --git a/examples/Printf.jed b/examples/Printf.jed new file mode 100644 index 0000000..5a4193f --- /dev/null +++ b/examples/Printf.jed @@ -0,0 +1,17 @@ +(* Out and C's printf, writing to the same standard output. Each keeps + a buffer of its own, so each is flushed before the other writes. *) +module Printf; +import Out, C; + +proc main*; +var i: I64; +begin + for i := 1 to 3 do + Out.str("jed says "); Out.int(i); Out.ln; + Out.flush; + C.printf("C says %d, %s\n", I32(i * i), "squared"); + C.fflush(C.stdout); + end; +end; + +end Printf. diff --git a/examples/Window.jed b/examples/Window.jed new file mode 100644 index 0000000..99c5079 --- /dev/null +++ b/examples/Window.jed @@ -0,0 +1,70 @@ +(* An X11 window that says hello, and closes at a key press. An XEvent + is a C union: it is read as an array of words, and the member its + type says it holds through a pointer conversion. Compiled by make + check, not run: it needs a display. *) +module Window; +import Out; +link "libX11.so.6"; + +const + KeyPress = 2; + Expose = 12; + KeyPressMask = 1; + ExposureMask = 8000H; + +type + (* XKeyEvent, laid out as C lays it out *) + KeyEvent = record + typ: I32; + serial: U64; + sendEvent: I32; + display: ^U8; + window, root, subwindow, time: U64; + x, y, xRoot, yRoot: I32; + state, keycode: U32; + sameScreen: I32; + end; + +extern proc XOpenDisplay(name: ^U8): ^U8; +extern proc XDefaultScreen(d: ^U8): I32; +extern proc XRootWindow(d: ^U8; screen: I32): U64; +extern proc XBlackPixel(d: ^U8; screen: I32): U64; +extern proc XWhitePixel(d: ^U8; screen: I32): U64; +extern proc XDefaultGC(d: ^U8; screen: I32): ^U8; +extern proc XCreateSimpleWindow(d: ^U8; parent: U64; x, y: I32; + width, height, border: U32; borderColor, background: U64): U64; +extern proc XStoreName(d: ^U8; w: U64; name: ^U8): I32; +extern proc XSelectInput(d: ^U8; w: U64; mask: I64): I32; +extern proc XMapWindow(d: ^U8; w: U64): I32; +extern proc XNextEvent(d: ^U8; ev: ^U8): I32; +extern proc XDrawString(d: ^U8; w: U64; gc: ^U8; x, y: I32; s: ^U8; n: I32): I32; +extern proc XCloseDisplay(d: ^U8): I32; + +proc main*: I64; +const text = "hello, world: press a key"; +var + d: ^U8; s: I32; w: U64; + ev: [24]I64; (* XEvent: 192 bytes *) + key: ^KeyEvent; +begin + d := XOpenDisplay(nil); + if d = nil then Out.str("no display\n"); return 1; end; + s := XDefaultScreen(d); + w := XCreateSimpleWindow(d, XRootWindow(d, s), 0, 0, 320, 80, 1, + XBlackPixel(d, s), XWhitePixel(d, s)); + XStoreName(d, w, "jed"); + XSelectInput(d, w, ExposureMask + KeyPressMask); + XMapWindow(d, w); + repeat + XNextEvent(d, ^U8(ADR(ev))); + if I32(ev[0]) = Expose then + XDrawString(d, w, XDefaultGC(d, s), 20, 45, text, I32(LEN(text))); + end; + until I32(ev[0]) = KeyPress; + key := ^KeyEvent(ADR(ev)); + Out.str("key "); Out.int(I64(key^.keycode)); Out.ln; + XCloseDisplay(d); + return 0; +end; + +end Window. diff --git a/lib/C.jed b/lib/C.jed new file mode 100644 index 0000000..23a1a2a --- /dev/null +++ b/lib/C.jed @@ -0,0 +1,18 @@ +(* The C library: what jed's own library calls in it, and what most + programs reach for. A program that imports C uses C, and so is + linked dynamically and starts through the C library. *) +module C; + +extern proc write*(fd: I32; buf: ^U8; n: U64): I64; +extern proc mmap*(addr: ^U8; n: U64; prot, flags, fd: I32; off: I64): ^U8; +extern proc munmap*(addr: ^U8; n: U64): I32; +extern proc isatty*(fd: I32): I32; +extern proc exit*(status: I32); +extern proc _exit*(status: I32); +extern proc __errno_location*: ^I32; (* errno is this thread's: through here *) +extern proc printf*(format: ^U8; ...): I32; +extern proc fflush*(f: ^U8): I32; +extern var stdout*: ^U8; (* FILE * *) +extern var stderr*: ^U8; + +end C. diff --git a/lib/Out.jed b/lib/Out.jed index ef6a43f..392e1fd 100644 --- a/lib/Out.jed +++ b/lib/Out.jed @@ -1,23 +1,47 @@ -(* Writing text and numbers to standard output. Nothing is buffered: - each call is one write. *) +(* 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. *) module Out; -import Sys; +import Rt, Sys; + +var + buf: [4096]U8; + n: I64; (* bytes in buf *) + tty: BOOL; (* standard output is a terminal *) -proc str*(s: []U8); +(* Writes out the buffer. What can't be written is dropped. *) +proc flush*; +var i, k: I64; begin - Sys.write(Sys.stdout, s); + i := 0; + while i < n do + k := Sys.write(Sys.stdout, buf[i..n]); + if k > 0 then i := i + k; + elsif k # -4 then break; (* -EINTR: try again *) + end; + end; + n := 0; end; proc char*(c: U8); -var b: [1]U8; begin - b[0] := c; - Sys.write(Sys.stdout, b); + if n = LEN(buf) then flush; end; + buf[n] := c; + INC(n); + if (c = '\n') and tty then flush; end; end; +proc str*(s: []U8); +var i: I64; +begin + for i := 0 to LEN(s) - 1 do char(s[i]); end; +end; + proc ln*; begin - str("\n"); + char('\n'); end; (* n in decimal *) @@ -54,4 +78,7 @@ str(buf[i..16]); end; +begin + tty := Sys.isTerminal(Sys.stdout); + Rt.atExit(flush); end Out. diff --git a/lib/Rt.jed b/lib/Rt.jed index 232b411..24bbe79 100644 --- a/lib/Rt.jed +++ b/lib/Rt.jed @@ -1,9 +1,45 @@ -(* What the compiler's code calls: fail when a check fails, eq when = - or # compares two strings. The compiler finds them by these names. *) +(* The run time: ending the program, and what the compiler's code + calls: fail when a check fails, eq when = or # compares two strings. + The compiler finds fail, eq, exit and cExit by these names. *) module Rt; import Sys; -(* A check failed at line of file: says so on standard error and stops +const + Full*: ERROR = "too many procedures to run at exit"; + MaxAtExit = 32; + +var + atExits: [MaxAtExit]proc; + numAtExit: I64; + cExit: proc(status: I32); (* C's exit, set first thing in a program that uses C *) + +(* Registers p to run when the program ends by exit. *) +proc atExit*(p: proc): ERROR; +begin + if numAtExit = MaxAtExit then return Full; end; + atExits[numAtExit] := p; + INC(numAtExit); + return nil; +end; + +(* Runs the procedures registered with atExit, the last first, then + ends the program with status: through C's exit in a program that + uses C, so that C flushes its buffers too. Each procedure is taken + off the list before it runs, so it runs once even if it fails or + calls exit itself. *) +proc exit*(status: I64); +var p: proc; +begin + while numAtExit > 0 do + DEC(numAtExit); + p := atExits[numAtExit]; + p(); + end; + if cExit # nil then cExit(I32(status)); end; + Sys.exit(status); +end; + +(* A check failed at line of file: says so on standard error and ends the program with status 2. *) proc fail*(file: ^U8; line: I64); var buf: [20]U8; i, n: I64; @@ -21,7 +57,7 @@ buf[i] := ':'; Sys.write(Sys.stderr, buf[i..20]); Sys.write(Sys.stderr, ": index out of range\n"); - Sys.exit(2); + exit(2); end; proc eq*(a, b: []U8): BOOL; diff --git a/lib/Sys.jed b/lib/Sys.jed new file mode 100644 index 0000000..8b6cc70 --- /dev/null +++ b/lib/Sys.jed @@ -0,0 +1,57 @@ +(* System calls through the C library: Sys for the targets that have no + file of their own, with the same exports. A program that imports it + uses C. *) +module Sys; +import C; + +const + stdin* = 0; + stdout* = 1; + stderr* = 2; + +(* minus errno, as a system call returns it *) +proc failed: I64; +var e: ^I32; +begin + e := C.__errno_location(); + return -I64(e^); +end; + +(* Writes s to the file descriptor fd; the number of bytes written, or + minus an errno. *) +proc write*(fd: I64; s: []U8): I64; +var r: I64; +begin + if LEN(s) = 0 then return 0; end; + r := C.write(I32(fd), ADR(s[0]), U64(LEN(s))); + if r < 0 then return failed(); end; + return r; +end; + +(* size bytes of fresh, zeroed memory from the system, a multiple of + pages, or nil. *) +proc mmap*(size: I64): ^U8; +var p: ^U8; +begin + p := C.mmap(nil, U64(size), 3, 22H, -1, 0); (* read, write; private, anonymous *) + if I64(p) = -1 then return nil; end; + return p; +end; + +proc munmap*(p: ^U8; size: I64); +begin + C.munmap(p, U64(size)); +end; + +proc isTerminal*(fd: I64): BOOL; +begin + return C.isatty(I32(fd)) = 1; +end; + +(* Ends the program, at once, with status. *) +proc exit*(status: I64); +begin + C._exit(I32(status)); +end; + +end Sys. diff --git a/lib/Sys.linux-x86_64.jed b/lib/Sys.linux-x86_64.jed index 591acbb..12321c9 100644 --- a/lib/Sys.linux-x86_64.jed +++ b/lib/Sys.linux-x86_64.jed @@ -30,6 +30,14 @@ SYSCALL(11, p, size); end; +(* Whether the file descriptor fd is a terminal: whether it has a + terminal's settings to read (ioctl TCGETS). *) +proc isTerminal*(fd: I64): BOOL; +var t: [8]I64; (* struct termios: 60 bytes *) +begin + return SYSCALL(16, fd, 5401H, ADR(t)) = 0; +end; + (* Ends the program, at once, with status. *) proc exit*(status: I64); begin diff --git a/src/elf.pas b/src/elf.pas index f71d108..eff6c8f 100644 --- a/src/elf.pas +++ b/src/elf.pas @@ -1,13 +1,19 @@ { elf.pas: the executable file. - Writes a static ELF64 executable for x86-64 Linux: the ELF header, - one program header per section that has anything in it, the linked - text and rodata, and section headers with a symbol table, so that - objdump and gdb can name each procedure and variable. + 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. + 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 + it uses is a quadword the loader fills in with the symbol's address + (a GLOB_DAT relocation), which the code calls or reads through. + There is no PLT and no lazy binding, and the program exports nothing. + Depends on: link for the images and addresses, x64 for the chunks, scan for names and errors, BaseUnix to write the file. - Leaves out: dynamic linking, for now. } + Leaves out: position independent executables, symbol versions. } unit elf; @@ -17,8 +23,9 @@ uses scan, x64, link; -const - HeaderSize = 64 + 3 * 56; { the ELF header and up to three program headers } +var + needed: array[0..31] of longint; { the libraries to load, names interned } + numNeeded: longint; { none: a static program } procedure WriteElf(const path: shortstring; entry: longint); @@ -70,16 +77,16 @@ end; end; -procedure Phdr(flags: longint; off, adr, filesz, memsz: int64); +procedure Phdr(typ, flags: longint; off, adr, filesz, memsz, align: int64); begin - PutN(1, 4); { PT_LOAD } + PutN(typ, 4); PutN(flags, 4); PutN(off, 8); PutN(adr, 8); PutN(adr, 8); PutN(filesz, 8); PutN(memsz, 8); - PutN(Page, 8); + PutN(align, 8); end; procedure Shdr(name, typ: longint; flags, adr, off, size: int64; lnk, info: longint; align, entsize: int64); @@ -89,22 +96,126 @@ PutN(align, 8); PutN(entsize, 8); end; +procedure PutStr(const s: shortstring); +begin + PutBytes(@s[1], length(s)); + PutN(0, 1); +end; + +const + Interp = '/lib64/ld-linux-x86-64.so.2'; + { program header types } + PtLoad = 1; PtDynamic = 2; PtInterp = 3; PtGnuStack = $6474E551; + +var + { in the room at the end of rodata: where each of the loader's + tables starts, from extraAdr } + symAt, relaAt, hashAt, strAt: int64; + nsym, strLen: longint; + +{ The sizes of the loader's tables: what LinkAll must leave room for. } +procedure SizeTables(var roExtra, dynSize: int64); +var c, i: longint; +begin + nsym := 1; + strLen := 1; + for i := 0 to numNeeded - 1 do strLen := strLen + length(NameOf(needed[i])) + 1; + for c := 0 to numChunks - 1 do + if chunks^[c].live and chunks^[c].ext then begin + inc(nsym); + strLen := strLen + length(NameOf(chunks^[c].name)) + 1; + end; + symAt := (length(Interp) + 1 + 7) div 8 * 8; + relaAt := symAt + nsym * 24; + hashAt := relaAt + (nsym - 1) * 24; + strAt := hashAt + 4 * (3 + nsym); + roExtra := strAt + strLen; + dynSize := (numNeeded + 10) * 16; +end; + +{ The loader's tables in the room at the end of rodata, which the + buffer already holds as zeros: the loader's name; the symbols, one + for each C symbol used; a GLOB_DAT relocation for each, at its + quadword; a hash table of one bucket; and their names. } +procedure PutTables; +var c, k, i, at, name: longint; +begin + len := extraAdr - Base; + PutStr(Interp); + PadTo(extraAdr - Base + symAt); + PutN(0, 24); + name := strLen; + for c := numChunks - 1 downto 0 do { names go last in the string table } + if chunks^[c].live and chunks^[c].ext then name := name - length(NameOf(chunks^[c].name)) - 1; + for c := 0 to numChunks - 1 do + if chunks^[c].live and chunks^[c].ext then begin + PutN(name, 4); PutN($10, 1); PutN(0, 1); PutN(0, 2); { global, undefined } + PutN(0, 8); PutN(0, 8); + name := name + length(NameOf(chunks^[c].name)) + 1; + end; + k := 1; + for c := 0 to numChunks - 1 do + if chunks^[c].live and chunks^[c].ext then begin + PutN(chunks^[c].adr, 8); + PutN(qword(k) shl 32 or 6, 8); { R_X86_64_GLOB_DAT } + PutN(0, 8); + inc(k); + end; + PutN(1, 4); PutN(nsym, 4); PutN(nsym - 1, 4); { the bucket chains every symbol } + PutN(0, 4); + for i := 1 to nsym - 1 do PutN(i - 1, 4); + PutN(0, 1); + for i := 0 to numNeeded - 1 do PutStr(NameOf(needed[i])); + for c := 0 to numChunks - 1 do + if chunks^[c].live and chunks^[c].ext then PutStr(NameOf(chunks^[c].name)); + len := roOff + roSize; + + { the dynamic table, at the start of the writable segment } + PadTo(bssAdr - Base); + at := 1; + for i := 0 to numNeeded - 1 do begin + PutN(1, 8); PutN(at, 8); { DT_NEEDED } + at := at + length(NameOf(needed[i])) + 1; + end; + PutN(4, 8); PutN(extraAdr + hashAt, 8); { DT_HASH } + PutN(5, 8); PutN(extraAdr + strAt, 8); { DT_STRTAB } + PutN(6, 8); PutN(extraAdr + symAt, 8); { DT_SYMTAB } + PutN(10, 8); PutN(strLen, 8); { DT_STRSZ } + PutN(11, 8); PutN(24, 8); { DT_SYMENT } + PutN(7, 8); PutN(extraAdr + relaAt, 8); { DT_RELA } + PutN(8, 8); PutN((nsym - 1) * 24, 8); { DT_RELASZ } + PutN(9, 8); PutN(24, 8); { DT_RELAENT } + PutN(21, 8); PutN(0, 8); { DT_DEBUG, for gdb } + PutN(0, 16); { DT_NULL } +end; + procedure WriteElf(const path: shortstring; entry: longint); const - ShNames = #0'.text'#0'.rodata'#0'.bss'#0'.symtab'#0'.strtab'#0'.shstrtab'#0; + ShNames = #0'.text'#0'.rodata'#0'.bss'#0'.symtab'#0'.strtab'#0'.shstrtab'#0 + + '.dynamic'#0'.dynstr'#0'.dynsym'#0; var - nph, c, nsym, fd: longint; - symOff, strOff, shstrOff, shOff, strLen: int64; + nph, nsh, c, nsyms, fd: longint; + roExtra, dynSize, symOff, strOff, shstrOff, shOff, strsLen: int64; strs: PBytes; s, p: shortstring; sec: longint; + dynamic: boolean; begin cap := 1 shl 16; buf := GetMem(cap); len := 0; - nph := 1; - if roSize > 0 then inc(nph); - if bssSize > 0 then inc(nph); + MarkLive(entry); + dynamic := numNeeded > 0; + roExtra := 0; dynSize := 0; + if dynamic then SizeTables(roExtra, dynSize); + { room for the most program headers either kind of program has } + LinkAll(64 + 6 * 56, roExtra, dynSize); + if dynamic then nph := 6 + else begin + nph := 2; + if roSize > 0 then inc(nph); + if bssSize > 0 then inc(nph); + end; { ELF header } PutN($464C457F, 4); PutN(2, 1); PutN(1, 1); PutN(1, 1); PutN(0, 9); @@ -115,49 +226,57 @@ PutN(64, 8); { program headers follow } PutN(0, 8); { section headers: patched below } PutN(0, 4); + nsh := 7; + if dynamic then nsh := 10; PutN(64, 2); PutN(56, 2); PutN(nph, 2); - PutN(64, 2); PutN(7, 2); PutN(6, 2); + PutN(64, 2); PutN(nsh, 2); PutN(6, 2); + 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(5, 0, Base, textOff + textSize, textOff + textSize); - if roSize > 0 then Phdr(4, roOff, Base + roOff, roSize, roSize); - if bssSize > 0 then Phdr(6, 0, bssAdr, 0, bssSize); + Phdr(PtLoad, 5, 0, Base, textOff + textSize, textOff + textSize, Page); + if roSize > 0 then Phdr(PtLoad, 4, roOff, Base + roOff, roSize, roSize, Page); + if dynamic then begin + Phdr(PtLoad, 6, bssAdr - Base, bssAdr, dynSize, bssSize, Page); + Phdr(PtDynamic, 6, bssAdr - Base, bssAdr, dynSize, dynSize, 8); + end else if bssSize > 0 then Phdr(PtLoad, 6, 0, bssAdr, 0, bssSize, Page); + Phdr(PtGnuStack, 6, 0, 0, 0, 0, 16); { a stack that can't run code } PadTo(textOff); PutBytes(textImg, textSize); PadTo(roOff); { even when empty, so that every section lies in the file } PutBytes(roImg, roSize); + if dynamic then PutTables; { the symbol table: one local symbol for each named live chunk } PadTo((len + 7) div 8 * 8); symOff := len; strs := GetMem(1 shl 16); - strLen := 1; + strsLen := 1; strs^[0] := 0; PutN(0, 24); - nsym := 1; + nsyms := 1; for c := 0 to numChunks - 1 do - if chunks^[c].live and (chunks^[c].name >= 0) then begin + if chunks^[c].live and (chunks^[c].name >= 0) and not chunks^[c].ext then begin s := ChunkName(c); - if strLen + length(s) + 1 > MemSize(strs) then strs := ReAllocMem(strs, strLen * 2 + 256); - Move(s[1], strs^[strLen], length(s)); - strs^[strLen + length(s)] := 0; + 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 secText: sec := 1; secRodata: sec := 2; else sec := 3; end; - PutN(strLen, 4); + PutN(strsLen, 4); if sec = 1 then PutN(2, 1) else PutN(1, 1); { STT_FUNC, STT_OBJECT } PutN(0, 1); PutN(sec, 2); PutN(chunks^[c].adr, 8); PutN(chunks^[c].size, 8); - strLen := strLen + length(s) + 1; - inc(nsym); + strsLen := strsLen + length(s) + 1; + inc(nsyms); end; strOff := len; - PutBytes(strs, strLen); + PutBytes(strs, strsLen); shstrOff := len; s := ShNames; PutBytes(@s[1], length(s)); @@ -168,10 +287,15 @@ 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, roOff + roSize, bssSize, 0, 0, 16, 0); - Shdr(20, 2, 0, 0, symOff, nsym * 24, 5, nsym, 8, 24); - Shdr(28, 3, 0, 0, strOff, strLen, 0, 0, 1, 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); + 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); + end; 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 09bc2b5..43aa669 100644 --- a/src/gen.pas +++ b/src/gen.pas @@ -54,6 +54,8 @@ target: int64; { the frame slot of a procedure value, if any } chunk: longint; { else the procedure's chunk } code: boolean; { a code procedure: two results come in rax and rdx } + ext: boolean; { C's: called through the chunk holding its address } + isF: array[0..63] of boolean; { each argument: goes in an xmm register } end; var @@ -191,7 +193,10 @@ oVar: begin x.mode := mVar; x.isVar := true; - if o^.lev = 0 then begin + if o^.ext then begin + Load(RAX, MemRip(o^.chunk, 0), 8, false); + x.base := bReg; x.reg := RAX; + end else if o^.lev = 0 then begin x.base := bGlobal; x.chunk := o^.chunk end else if o^.ind then begin Load(RAX, Mem(RBP, o^.val), 8, false); @@ -290,7 +295,8 @@ mProc: begin if x.obj^.isCode and (x.obj^.typ^.base <> nil) and x.obj^.typ^.base^.tuple then Mark('a code procedure with two results can only be called'); - Lea(RAX, MemRip(x.obj^.chunk, 0)); + if x.obj^.ext then Load(RAX, MemRip(x.obj^.chunk, 0), 8, false) + else Lea(RAX, MemRip(x.obj^.chunk, 0)); end; else Mark('not a value'); end; @@ -976,9 +982,9 @@ begin if x.mode = mProc then begin c.sig := x.obj^.typ; c.chunk := x.obj^.chunk; c.target := 0; - c.code := x.obj^.isCode; + c.code := x.obj^.isCode; c.ext := x.obj^.ext; end else begin - c.code := false; + c.code := false; c.ext := false; if x.typ^.form <> fProc then Mark('not a procedure'); c.sig := x.typ; c.chunk := -1; c.target := ToSlot(x); @@ -991,8 +997,20 @@ var p: PObj; s: int64; begin p := c.param; - if p = nil then Mark('too many arguments'); if c.n > High(c.slots) then Mark('too many arguments'); + if p = nil then begin + { past the parameters of a C procedure that ends in ...: a string + goes as a C string, an integer constant as an I64 } + if not c.sig^.variadic then Mark('too many arguments'); + if a.mode = mStr then Coerce(a, tPtrU8) + else if a.typ^.form = fConst then Coerce(a, tI64) + else if not IsScalar(a.typ) then Mark('only a single value goes to ...'); + c.isF[c.n] := a.typ^.form = fReal; + c.slots[c.n] := ToSlot(a); + inc(c.n); + exit; + end; + c.isF[c.n] := (p^.typ^.form = fReal) and not p^.isVar; if p^.isVar then begin if (a.mode <> mVar) or not a.isVar then Mark('a var parameter needs a variable'); if not Same(a.typ, p^.typ) then Mark('a var parameter needs exactly ' + TypeName(p^.typ)); @@ -1017,8 +1035,8 @@ procedure EndCall(var c: TCall; var x: TItem); var - p: PObj; res: PType; i, ni, nf, k, pad: longint; ret: int64; - isF: array[0..63] of boolean; onStack: array[0..63] of boolean; + res: PType; i, ni, nf, k, pad: longint; ret: int64; + onStack: array[0..63] of boolean; begin if c.param <> nil then Mark('too few arguments'); res := c.sig^.base; @@ -1030,14 +1048,11 @@ end; { the System V classes: each argument in the next free register of its kind, or else on the stack } - p := c.sig^.fields; k := 0; for i := 0 to c.n - 1 do begin - isF[i] := (p^.typ^.form = fReal) and not p^.isVar; - if isF[i] then begin onStack[i] := nf >= 8; if nf < 8 then inc(nf) end + if c.isF[i] then begin onStack[i] := nf >= 8; if nf < 8 then inc(nf) end else begin onStack[i] := ni >= 6; if ni < 6 then inc(ni) end; if onStack[i] then inc(k); - p := p^.next; end; pad := ord(odd(depth + k)); if pad <> 0 then AluI(aluSub, RSP, 8); @@ -1050,9 +1065,12 @@ if (ret <> 0) and not c.code then begin Lea(RDI, Mem(RBP, ret)); ni := 1 end; for i := 0 to c.n - 1 do if not onStack[i] then - if isF[i] then begin MovsdXM(nf, Mem(RBP, c.slots[i])); inc(nf) end + if c.isF[i] then begin MovsdXM(nf, Mem(RBP, c.slots[i])); inc(nf) end else begin Load(IntRegs[ni], Mem(RBP, c.slots[i]), 8, false); inc(ni) end; - if c.chunk >= 0 then CallChunk(c.chunk) + { a procedure taking ... is told in al how many xmm registers it got } + if c.sig^.variadic then MovRI(RAX, nf); + if c.ext then CallM(MemRip(c.chunk, 0)) + else if c.chunk >= 0 then CallChunk(c.chunk) else begin Load(R11, Mem(RBP, c.target), 8, false); CallR(R11); diff --git a/src/jed.pas b/src/jed.pas index ad6e3c7..93f07f6 100644 --- a/src/jed.pas +++ b/src/jed.pas @@ -6,9 +6,13 @@ entry point, links what it reaches, and writes the executable: by default the main module's file without its .jed. - The entry point saves argc and argv, runs every module's body (those - of the modules the program imports, imported modules first), then - the main module's main, and exits with its status. + The program starts by saving argc and argv, runs every module's body + (those of the modules the program imports, imported modules first), + then the main module's main, and ends with Rt.exit and main's + status. A static program does this from its entry point. One that + uses C starts through the C library, __libc_start_main, which sets + 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. } @@ -32,12 +36,51 @@ end; end; +{ Whether the program uses C: if so, the libraries it needs go to + elf.pas, the C library first. } +function UsesC: boolean; +var m, st, c: PModule; l: PLib; i: longint; seen: boolean; +begin + st := nil; c := nil; + numNeeded := 1; + needed[0] := Intern(PChar('libc.so.6'), 9); + m := firstModule; + while m <> nil do begin + if m^.used and m^.linkStatic then st := m; + if m^.used and m^.usesC then c := m; + l := m^.libs; + while m^.used and (l <> nil) do begin + seen := false; + for i := 0 to numNeeded - 1 do seen := seen or (needed[i] = l^.name); + if not seen then begin + if numNeeded > High(needed) then Fatal('too many libraries'); + needed[numNeeded] := l^.name; + inc(numNeeded); + end; + l := l^.next; + end; + m := m^.next; + end; + if (st <> nil) and (c <> nil) then + Fatal(NameOf(st^.name) + ' says link static, but ' + NameOf(c^.name) + ' uses C'); + if c = nil then numNeeded := 0; + UsesC := c <> nil; +end; + +function RtObj(rt: PModule; const n: shortstring): PObj; +var o: PObj; +begin + o := Find(rt^.scope, Intern(@n[1], length(n))); + if o = nil then Fatal('Rt has no ' + n); + RtObj := o; +end; + var path, outPath, dir, s: shortstring; - i, entry: longint; + i, entry, start: longint; m, rt: PModule; main: PObj; - hasResult: boolean; + hasResult, dynamic: boolean; begin { constants fold as the machine computes: NaN and infinities, no traps } @@ -89,12 +132,41 @@ hasResult := main^.typ^.base <> nil; end; + if rt = nil then Fatal('can''t find module Rt'); + dynamic := UsesC; entry := NewChunk(secText, -1, Intern('_start', 6)); - BeginChunk(entry); - Load(RAX, Mem(RSP, 0), 8, false); - Store(MemRip(argcChunk, 0), RAX, 8); - Lea(RAX, Mem(RSP, 8)); - Store(MemRip(argvChunk, 0), RAX, 8); + if dynamic then begin + { _start as C's crt1 does it: __libc_start_main(main, argc, argv, + nil, nil, rtld_fini, stack_end), with rsp aligned } + start := NewChunk(secText, -1, Intern('main', 4)); + BeginChunk(entry); + MovRI(RBP, 0); + MovRR(R9, RDX); + Pop(RSI); + MovRR(RDX, RSP); + AluI(aluAnd, RSP, -16); + Push(RAX); + Push(RSP); + MovRI(R8, 0); + MovRI(RCX, 0); + Lea(RDI, MemRip(start, 0)); + CallM(MemRip(ExternChunk(Intern('__libc_start_main', 17)), 0)); + Ud2; + EndChunk(entry); + BeginChunk(start); + Push(RBP); { aligns the stack again } + Store(MemRip(argcChunk, 0), RDI, 8); + Store(MemRip(argvChunk, 0), RSI, 8); + Load(RAX, MemRip(ExternChunk(Intern('exit', 4)), 0), 8, false); + Store(MemRip(RtObj(rt, 'cExit')^.chunk, 0), RAX, 8); + end else begin + start := entry; + BeginChunk(entry); + Load(RAX, Mem(RSP, 0), 8, false); + Store(MemRip(argcChunk, 0), RAX, 8); + Lea(RAX, Mem(RSP, 8)); + Store(MemRip(argvChunk, 0), RAX, 8); + end; m := firstModule; while m <> nil do begin if m^.used and (m^.body >= 0) then CallChunk(m^.body); @@ -102,10 +174,9 @@ end; if main <> nil then CallChunk(main^.chunk); if hasResult then MovRR(RDI, RAX) else MovRI(RDI, 0); - MovRI(RAX, 231); { exit_group } - Syscall; - EndChunk(entry); + CallChunk(RtObj(rt, 'exit')^.chunk); + Ud2; + EndChunk(start); - LinkAll(entry, HeaderSize); WriteElf(outPath, entry); end. diff --git a/src/link.pas b/src/link.pas index 6e8cb46..d3c55ff 100644 --- a/src/link.pas +++ b/src/link.pas @@ -6,8 +6,11 @@ every fixup patched. The file is laid out so that each section can be mapped as it lies: - text right after the headers, rodata on the next page, bss after - that, in memory only. + text right after the headers, rodata on the next page, then a + writable page that starts with the table the dynamic loader reads + (none in a static program) and goes on as bss, in memory only. The + loader's other tables come at the end of rodata; elf.pas writes them + in the room left there. Depends on: x64 for chunks and fixups, scan for names and errors. Leaves out: the file format; that is elf.pas. } @@ -26,11 +29,13 @@ var textOff, textSize: int64; { file offset and size of text } - roOff, roSize: int64; - bssAdr, bssSize: int64; + roOff, roSize: int64; { rodata, the room for the loader's tables included } + extraAdr: int64; { that room } + bssAdr, bssSize: int64; { the writable segment, the loader's table first } textImg, roImg: PBytes; -procedure LinkAll(entry: longint; headerSize: longint); +procedure MarkLive(entry: longint); +procedure LinkAll(headerSize, roExtra, dynSize: int64); function ChunkName(c: longint): shortstring; implementation @@ -82,18 +87,21 @@ Place := a; end; -procedure LinkAll(entry: longint; headerSize: longint); +{ Places the live chunks, leaving roExtra bytes at the end of rodata + and dynSize at the start of the writable segment. } +procedure LinkAll(headerSize, roExtra, dynSize: int64); var c, f, at: longint; e, p, v: int64; begin - MarkLive(entry); textOff := (headerSize + 15) div 16 * 16; e := Place(secText, Base + textOff); textSize := e - (Base + textOff); roOff := (textOff + textSize + Page - 1) div Page * Page; e := Place(secRodata, Base + roOff); + extraAdr := (e + 7) div 8 * 8; + if roExtra > 0 then e := extraAdr + roExtra; roSize := e - (Base + roOff); bssAdr := (Base + roOff + roSize + Page - 1) div Page * Page; - e := Place(secBss, bssAdr); + e := Place(secBss, bssAdr + dynSize); bssSize := e - bssAdr; textImg := GetMem(textSize + 1); diff --git a/src/parse.pas b/src/parse.pas index 4663e75..a2b4fb1 100644 --- a/src/parse.pas +++ b/src/parse.pas @@ -12,7 +12,8 @@ interface. Depends on: scan, sym, x64, gen. - Leaves out (for stage 3): extern and link. } + Leaves out: linking; a module only records the libraries it names, + and whether it uses C or says link static. } unit parse; @@ -60,8 +61,9 @@ 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 } + inExtern: boolean; { reading an extern's signature: ... allowed } tArgv, tBodySig: PType; - nameRt, nameFail, nameEq, nameMain, nameBody: longint; + nameRt, nameFail, nameEq, nameMain, nameBody, nameStatic: longint; procedure Expression(var x: TItem; want: PType); forward; function ParseType: PType; forward; @@ -284,6 +286,7 @@ if tok <> sRparen then repeat if tok = sEllipsis then begin + if not inExtern then Mark('... is only for extern procedures'); Next; t^.variadic := true; break end; isVar := tok = sVar; @@ -1343,6 +1346,43 @@ end; end; +{ An extern procedure or variable: C's, reached through the quadword + that holds its address. } +procedure ExternDecl; +var n: longint; exp: boolean; o, q: PObj; t: PType; +begin + Next; + curModule^.usesC := true; + if tok = sProc then begin + Next; + IdentDef(n, exp); + inExtern := true; + t := Signature; + inExtern := false; + q := t^.fields; + while q <> nil do begin + if q^.isVar or not IsScalar(q^.typ) then + Mark('C takes integers, BOOL, F64, pointers and procedures'); + q := q^.next; + end; + if (t^.base <> nil) and not IsScalar(t^.base) then Mark('C returns a single value'); + o := NewObj(oProc, n, t); + end else begin + if tok <> sVar then Mark('proc or var expected'); + Next; + IdentDef(n, exp); + Expect(sColon, ':'); + declExported := exp; + t := ParseType; + declExported := false; + o := NewObj(oVar, n, t); + end; + o^.exported := exp; + o^.ext := true; + o^.chunk := ExternChunk(n); + Declare(o); +end; + procedure Declarations(top: boolean); var n, i, k: longint; exp: boolean; x: TItem; o: PObj; t: PType; @@ -1434,7 +1474,11 @@ ProcDecl; Expect(sSemicolon, ';'); end; - sExtern: Mark('extern comes in stage 3'); + sExtern: begin + if not top then Mark('extern only at the top of a module'); + ExternDecl; + Expect(sSemicolon, ';'); + end; else exit; end; until false; @@ -1512,7 +1556,7 @@ a := m^.args.o[i]; if (a = nil) or not Same(a^.typ, sig) then Mark('needs a procedure with the signature of ' + NameOf(o^.name)); - o^.typ := a^.typ; o^.chunk := a^.chunk; o^.isCode := a^.isCode; + o^.typ := a^.typ; o^.chunk := a^.chunk; o^.isCode := a^.isCode; o^.ext := a^.ext; Declare(o); s := s + NameOf(a^.module^.name) + '.' + NameOf(a^.name) + ','; inc(i); @@ -1539,7 +1583,7 @@ var st: TScanState; saved: array[0..MaxDepth - 1] of longint; d: longint; oldMod: PModule; oldFile: longint; oldCheck: boolean; m, im: PModule; - imp: PImport; alias, mname: longint; o: PObj; body: longint; iargs: TArgs; + imp: PImport; lib: PLib; alias, mname: longint; o: PObj; body: longint; iargs: TArgs; begin SaveScan(st); SaveScopes(d, saved); @@ -1598,7 +1642,19 @@ until false; Expect(sSemicolon, ';'); end; - if tok = sLink then Mark('link comes in stage 3'); + while tok = sLink do begin + Next; + if (tok = sIdent) and (id = nameStatic) then m^.linkStatic := true + else if tok = sString then begin + New(lib); + lib^.name := Intern(@sbuf, slen); + lib^.next := m^.libs; + m^.libs := lib; + m^.usesC := true; + end else Mark('a library or static expected'); + Next; + Expect(sSemicolon, ';'); + end; Declarations(true); if tok = sBegin then begin if checkMode then SkipBody @@ -1738,6 +1794,7 @@ nameEq := Name('eq'); nameMain := Name('main'); nameBody := Name('body'); + nameStatic := Name('static'); rtFail := NewChunk(secText, nameRt, nameFail); rtEq := NewChunk(secText, nameRt, nameEq); argcChunk := NewChunk(secBss, -1, Name('argc')); diff --git a/src/sym.pas b/src/sym.pas index 41f35ea..7a7bf9c 100644 --- a/src/sym.pas +++ b/src/sym.pas @@ -31,6 +31,7 @@ PObj = ^TObj; PModule = ^TModule; PImport = ^TImport; + PLib = ^TLib; TType = record form: TForm; @@ -65,6 +66,8 @@ isVar: boolean; { a var parameter } fwd: boolean; { oProc: declared forward, no body yet } isCode: boolean; { oProc: a code procedure } + ext: boolean; { oProc, oVar: C's, reached through its chunk, which + holds its address } fields: PObj; { oCase: its fields } module: PModule; { oModule: the module; others: where declared } link: PObj; { the next top-level declaration of its module } @@ -83,6 +86,12 @@ next: PImport; end; + { A library a module links, by its name, as interned } + TLib = record + name: longint; + next: PLib; + end; + TModule = record name: longint; sname: longint; { the name of its symbols: List(I64) for an instance } @@ -95,6 +104,9 @@ done: boolean; { compiled to the end } checkOnly: boolean; { read only to check another file's interface } used: boolean; { imported, through others, by the main module } + usesC: boolean; { has an extern, or links a library } + linkStatic: boolean; { says link static } + libs: PLib; { the libraries it links } next: PModule; { modules in the order they were finished } end; diff --git a/src/x64.pas b/src/x64.pas index ec64b76..58d008a 100644 --- a/src/x64.pas +++ b/src/x64.pas @@ -58,6 +58,7 @@ module, name: longint; { for the symbol table; -1 if none } adr: int64; { its address, set by the linker } live: boolean; { reached from the entry point } + ext: boolean; { bss: the address of a C symbol, its name } end; TFixup = record @@ -86,6 +87,7 @@ procedure EndChunk(c: longint); procedure SetData(c: longint; p: PBytes; n, align: longint); procedure SetBss(c: longint; size, align: longint); +function ExternChunk(name: longint): longint; procedure Put1(b: longint); procedure Put4(v: longint); @@ -118,6 +120,7 @@ procedure CallChunk(c: longint); procedure CallBack(target: longint); procedure CallR(r: longint); +procedure CallM(const m: TMem); procedure Ret; procedure Leave; procedure Syscall; @@ -240,6 +243,19 @@ chunks^[c].align := align; 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; +var c: longint; +begin + for c := 0 to numChunks - 1 do + if chunks^[c].ext and (chunks^[c].name = name) then exit(c); + c := NewChunk(secBss, -1, name); + SetBss(c, 8, 8); + chunks^[c].ext := true; + ExternChunk := c; +end; + procedure AddFixup(at, chunk, addend: longint); begin if numFixups = fixCap then begin @@ -486,6 +502,11 @@ procedure CallR(r: longint); begin OpR(0, false, $FF, 2, r); +end; + +procedure CallM(const m: TMem); +begin + OpM(0, false, $FF, 2, m); end; procedure Ret; begin Put1($C3) end; diff --git a/test/check.sh b/test/check.sh index 4a90396..9f12869 100755 --- a/test/check.sh +++ b/test/check.sh @@ -5,6 +5,8 @@ # X.expect its standard output # X.args its arguments, one per line (optional) # X.status its exit status (optional; 0 if missing) +# A program without X.expect is compiled, not run. test/libc puts +# lib/Sys.jed, over the C library, before the system call one. # Programs in test/err must not compile, and must print X.err. jed=./jed @@ -19,6 +21,7 @@ echo "FAIL $dir/$name: doesn't compile: $(cat $out/$name.cerr)" fail=$((fail + 1)); return fi + if [ ! -f $dir/$name.expect ]; then pass=$((pass + 1)); return; fi set -- if [ -f $dir/$name.args ]; then while IFS= read -r a; do set -- "$@" "$a"; done < $dir/$name.args @@ -39,7 +42,7 @@ fi } -for f in examples/*.jed test/run/*.jed; do +for f in examples/*.jed test/run/*.jed test/libc/*.jed; do run $(dirname $f) $(basename $f .jed) done for f in test/err/*.jed; do diff --git a/test/enctest.pas b/test/enctest.pas index 0831667..1945c43 100644 --- a/test/enctest.pas +++ b/test/enctest.pas @@ -21,12 +21,11 @@ Unary(2, RAX); Unary(3, RAX); Unary(6, RCX); Unary(7, RCX); Cqo; Extend(RAX, 1, true); Extend(RAX, 1, false); Extend(RAX, 2, true); Extend(RAX, 2, false); Extend(RAX, 4, true); Extend(RAX, 4, false); SetCC(ccL, RAX); SetCC(ccA, RCX); TestRR(RAX, RAX); - Push(RAX); Push(12); Pop(RCX); Pop(R11); CallR(R11); Ret; Leave; Syscall; Mfence; Ud2; RepMovsb; RepStosb; + Push(RAX); Push(12); Pop(RCX); Pop(R11); CallR(R11); CallM(Mem(RCX, 8)); Ret; Leave; Syscall; Mfence; Ud2; RepMovsb; RepStosb; LockCmpxchg(Mem(RCX, 0), RDX); Xchg(Mem(RCX, 0), RAX); LockXadd(Mem(RCX, 0), RAX); MovqXR(0, RAX); MovqXR(1, RCX); MovqRX(RAX, 0); MovsdXM(2, Mem(RBP, -8)); MovsdMX(Mem(RBP, -8), 7); Sse($58, 0, 1); Sse($5E, 0, 1); Ucomisd(0, 1); Cvtsi2sd(0, RAX); Cvttsd2si(RAX, 0); Btc(RAX, 63); L := NoLabel; Jcc(ccE, L); Jmp(L); FixLink(L); JmpBack(chunks^[e].start); JccBack(ccNE, chunks^[e].start); EndChunk(e); - LinkAll(e, HeaderSize); WriteElf(ParamStr(1), e); end. diff --git a/test/err/ExternRec.err b/test/err/ExternRec.err new file mode 100644 index 0000000..817cd5b --- /dev/null +++ b/test/err/ExternRec.err @@ -0,0 +1 @@ +C takes integers, BOOL, F64, pointers and procedures diff --git a/test/err/ExternRec.jed b/test/err/ExternRec.jed new file mode 100644 index 0000000..6c90f96 --- /dev/null +++ b/test/err/ExternRec.jed @@ -0,0 +1,7 @@ +module ExternRec; + +type R = record a, b: I64; end; + +extern proc f(r: R); + +end ExternRec. diff --git a/test/err/Static.err b/test/err/Static.err new file mode 100644 index 0000000..c97362b --- /dev/null +++ b/test/err/Static.err @@ -0,0 +1 @@ +Bare says link static, but diff --git a/test/err/Static.jed b/test/err/Static.jed new file mode 100644 index 0000000..7d4272b --- /dev/null +++ b/test/err/Static.jed @@ -0,0 +1,9 @@ +module Static; +import Bare, C; + +proc main*; +begin + C.printf("%d\n", Bare.f()); +end; + +end Static. diff --git a/test/err/Variadic.err b/test/err/Variadic.err new file mode 100644 index 0000000..531ee7b --- /dev/null +++ b/test/err/Variadic.err @@ -0,0 +1 @@ +... is only for extern procedures diff --git a/test/err/Variadic.jed b/test/err/Variadic.jed new file mode 100644 index 0000000..a3e39d2 --- /dev/null +++ b/test/err/Variadic.jed @@ -0,0 +1,7 @@ +module Variadic; + +proc f(a: I64; ...); +begin +end; + +end Variadic. diff --git a/test/err/mods/Bare.jed b/test/err/mods/Bare.jed new file mode 100644 index 0000000..98c6b81 --- /dev/null +++ b/test/err/mods/Bare.jed @@ -0,0 +1,10 @@ +(* A module that needs a program without C. *) +module Bare; +link static; + +proc f*: I64; +begin + return 1; +end; + +end Bare. diff --git a/test/handtest.pas b/test/handtest.pas index c2c43f8..509808a 100644 --- a/test/handtest.pas +++ b/test/handtest.pas @@ -41,6 +41,5 @@ Syscall; EndChunk(entry); - LinkAll(entry, HeaderSize); WriteElf(ParamStr(1), entry); end. diff --git a/test/libc/Through.expect b/test/libc/Through.expect new file mode 100644 index 0000000..93dba85 --- /dev/null +++ b/test/libc/Through.expect @@ -0,0 +1,2 @@ +through C +500500 diff --git a/test/libc/Through.jed b/test/libc/Through.jed new file mode 100644 index 0000000..28345e7 --- /dev/null +++ b/test/libc/Through.jed @@ -0,0 +1,33 @@ +(* The library over C's Sys, lib/Sys.jed, which this directory puts + first: output, memory from the heap, and a failed check that still + writes out what Out holds. *) +module Through; +import Out, Heap, Mem; + +type Node = record next: ^Node; n: I64; end; + +proc main*; +var p, list: ^Node; i, sum: I64; a: [3]I64; +begin + Out.str("through C\n"); + list := nil; + for i := 1 to 1000 do + NEW(p, Heap.heap); + p^.n := i; + p^.next := list; + list := p; + end; + sum := 0; + while list # nil do + sum := sum + list^.n; + p := list; + list := list^.next; + Mem.free(Heap.heap, ^U8(p)); + end; + Out.int(sum); Out.ln; + i := 3; + a[i] := 1; + Out.str("not reached\n"); +end; + +end Through. diff --git a/test/libc/Through.status b/test/libc/Through.status new file mode 100644 index 0000000..0cfbf08 --- /dev/null +++ b/test/libc/Through.status @@ -0,0 +1 @@ +2 diff --git a/test/libc/mods/Sys.jed b/test/libc/mods/Sys.jed new file mode 120000 index 0000000..7979ce3 --- /dev/null +++ b/test/libc/mods/Sys.jed @@ -0,0 +1 @@ +../../../lib/Sys.jed \ No newline at end of file diff --git a/test/run/AtExit.expect b/test/run/AtExit.expect new file mode 100644 index 0000000..592b7e0 --- /dev/null +++ b/test/run/AtExit.expect @@ -0,0 +1,5 @@ +12 refused +main ends +third +second, which exits again +first diff --git a/test/run/AtExit.jed b/test/run/AtExit.jed new file mode 100644 index 0000000..7abbb41 --- /dev/null +++ b/test/run/AtExit.jed @@ -0,0 +1,41 @@ +(* Rt.exit runs what Rt.atExit registered, the last first, each once, + then ends the program with main's status. *) +module AtExit; +import Out, Rt; + +proc first; +begin + Out.str("first\n"); +end; + +proc second; +begin + Out.str("second, which exits again\n"); + Rt.exit(5); (* the rest still run, once each; the status is now 5 *) +end; + +proc third; +begin + Out.str("third\n"); +end; + +proc nothing; +begin +end; + +proc main*: I64; +var i, full: I64; +begin + Rt.atExit(first); + Rt.atExit(second); + Rt.atExit(third); + full := 0; + for i := 1 to 40 do + if Rt.atExit(nothing) = Rt.Full then INC(full); end; + end; + Out.int(full); Out.str(" refused\n"); + Out.str("main ends\n"); + return 3; +end; + +end AtExit. diff --git a/test/run/AtExit.status b/test/run/AtExit.status new file mode 100644 index 0000000..7ed6ff8 --- /dev/null +++ b/test/run/AtExit.status @@ -0,0 +1 @@ +5 diff --git a/test/run/Extern.expect b/test/run/Extern.expect new file mode 100644 index 0000000..19dd2d4 --- /dev/null +++ b/test/run/Extern.expect @@ -0,0 +1,13 @@ +5 +8 +42 +1414 +-3 0 1 5 9 12 +cmp called +1 2 3 4 5 6 7 eight|3.142 0.5 +3 +environ has entries +1 +5 +printf -42 too 2.5 +done diff --git a/test/run/Extern.jed b/test/run/Extern.jed new file mode 100644 index 0000000..e8d56ba --- /dev/null +++ b/test/run/Extern.jed @@ -0,0 +1,65 @@ +(* Calling C: arguments in registers and on the stack, reals, ..., + C variables, jed procedures as C's callbacks. *) +module Extern; +import Out, C; +link "libm.so.6"; + +extern proc strlen(s: ^U8): U64; +extern proc qsort(base: ^U8; n, size: U64; cmp: proc(a, b: ^I64): I32); +extern proc snprintf(buf: ^U8; n: U64; format: ^U8; ...): I32; +extern proc atoi(s: ^U8): I32; +extern proc abs(n: I32): I32; +extern proc sqrt(x: F64): F64; +extern proc getenv(name: ^U8): ^U8; +extern proc setenv(name, value: ^U8; overwrite: I32): I32; +extern var environ: ^^U8; +extern var optind: I32; + +var calls: I64; + +proc cmp(a, b: ^I64): I32; +begin + INC(calls); + if a^ < b^ then return -1; elsif a^ > b^ then return 1; end; + return 0; +end; + +proc main*; +var + a: [6]I64; i: I64; buf: [64]U8; n: I32; + len: proc(s: ^U8): U64; e: ^^U8; +begin + Out.int(I64(strlen("hello"))); Out.ln; + len := strlen; + Out.int(I64(len("hi there"))); Out.ln; + Out.int(I64(abs(-7)) + I64(atoi("35"))); Out.ln; + Out.int(I64(sqrt(2.0) * 1000.0)); Out.ln; + + a := [5, -3, 9, 0, 12, 1]; + qsort(^U8(ADR(a)), 6, 8, cmp); + for i := 0 to 5 do Out.int(a[i]); Out.char(' '); end; + Out.ln; + if calls > 0 then Out.str("cmp called\n"); end; + + (* nine arguments after the format: some go on the stack *) + n := snprintf(ADR(buf[0]), 64, "%d %d %d %d %d %d %d %s|%.3f %g", + 1, 2, 3, 4, 5, 6, 7, "eight", 3.14159, 0.5); + Out.str(buf[0..I64(n)]); Out.ln; + + setenv("JED_TEST", "yes", 1); + Out.int(I64(strlen(getenv("JED_TEST")))); Out.ln; + e := environ; + i := 0; + while e^ # nil do INC(i); e := e + 1; end; + if i > 0 then Out.str("environ has entries\n"); end; + Out.int(I64(optind)); Out.ln; + optind := 5; + Out.int(I64(optind)); Out.ln; + + Out.flush; + C.printf("printf %d %s %.1f\n", -42, "too", 2.5); + C.fflush(C.stdout); + Out.str("done\n"); +end; + +end Extern.