raz / commit 1e15c9a2

commit
1e15c9a29ed69d208f8d23d00c78a88d91e92f13
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
dfc1eb72
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.

patch · log

37 files changed, +859 -98

CLAUDE.md modified +17 -6

@@ -37,12 +37,14 @@
3737
3838 ## Where things stand
3939
40-Stages 1 and 2 are done (steps 1-10). Next is stage 3 (steps 11-14),
41-waiting for a go-ahead. Its first task is to write into the report, for
42-review: `F32` and untyped real literals, `extern var`, `link static`,
43-`Rt.exit` and `Rt.atExit`, and how to mix `Out` with C's `stdio` (flush
44-one before using the other). Unions are not added: the report shows
45-reading a C union as an array of words through pointer conversions.
40+Stages 1 and 2 are done (steps 1-10). Stage 3 (steps 11-14) is under
41+way: its report changes are written and approved, and step 11 is done.
42+Next is step 12, `F32`, which also makes an `F32` given to `...` an
43+error.
44+
45+`test/libc` runs its programs over `lib/Sys.jed`, the C one, through
46+a link in its `mods`. A test or example without `.expect` is only
47+compiled (`examples/Window.jed` needs a display).
4648
4749 ## Readings of the report already taken
4850
@@ -67,6 +69,15 @@
6769 and sliced.
6870 - A deferred statement's frame slots stay reserved for the rest of its
6971 procedure.
72+- A program uses C if a module it uses (not one read only for an
73+ interface check) has an `extern` or a `link` of a library. `static`
74+ in `link static;` is not a reserved word.
75+- C symbols are reached through quadwords the loader fills in
76+ (GLOB_DAT), with no PLT; the executable exports nothing. In a C
77+ program the entry point stores C's `exit` in `Rt.cExit`, found by
78+ name like `Rt.exit`, before any module body runs.
79+- Past an extern's parameters, a string goes as a C string and an
80+ integer constant as an `I64`.
7081 - Every failed check says "index out of range"; some errors point at
7182 the symbol after the offending expression. Error messages are to be
7283 improved later, all together.

PLAN.md (history) modified +1 -1

@@ -101,7 +101,7 @@
101101
102102 Stage 3: calling C, and what comes with it
103103
104-- [ ] 11. `extern proc`, `extern var` and `link`; dynamic ELF, start
104+- [x] 11. `extern proc`, `extern var` and `link`; dynamic ELF, start
105105 through `__libc_start_main`. A plain `lib/Sys.jed` over the C
106106 library, the default for targets with no file of their own.
107107 Examples with `printf` to `stdout`, and an X11 window, reading

doc/jed.md modified +1 -0

@@ -814,6 +814,7 @@
814814 | `Rt` | ending the program, `exit` and `atExit`; what the compiler's checks call when they fail; string comparison |
815815 | `Sys` | system calls: `write`, `mmap`, `munmap`, `exit`; one file per target, and `Sys.jed` over the C library for the others |
816816 | `Out` | writing text and numbers to standard output, buffered |
817+| `C` | the parts of the C library the others use, and `printf`, `fflush`, `stdout`; a program that imports it uses C |
817818 | `Mem` | `Allocator`, the interface of every allocator, and pages from the system |
818819 | `Heap` | a general allocator, `Heap.heap` |
819820 | `Arena` | an allocator that frees everything at once; `ADR(arena.base)` is its allocator |

examples/Printf.expect (history) added +6 -0

@@ -0,0 +1,6 @@
1+jed says 1
2+C says 1, squared
3+jed says 2
4+C says 4, squared
5+jed says 3
6+C says 9, squared

examples/Printf.jed added +17 -0

@@ -0,0 +1,17 @@
1+(* Out and C's printf, writing to the same standard output. Each keeps
2+ a buffer of its own, so each is flushed before the other writes. *)
3+module Printf;
4+import Out, C;
5+
6+proc main*;
7+var i: I64;
8+begin
9+ for i := 1 to 3 do
10+ Out.str("jed says "); Out.int(i); Out.ln;
11+ Out.flush;
12+ C.printf("C says %d, %s\n", I32(i * i), "squared");
13+ C.fflush(C.stdout);
14+ end;
15+end;
16+
17+end Printf.

examples/Window.jed added +70 -0

@@ -0,0 +1,70 @@
1+(* An X11 window that says hello, and closes at a key press. An XEvent
2+ is a C union: it is read as an array of words, and the member its
3+ type says it holds through a pointer conversion. Compiled by make
4+ check, not run: it needs a display. *)
5+module Window;
6+import Out;
7+link "libX11.so.6";
8+
9+const
10+ KeyPress = 2;
11+ Expose = 12;
12+ KeyPressMask = 1;
13+ ExposureMask = 8000H;
14+
15+type
16+ (* XKeyEvent, laid out as C lays it out *)
17+ KeyEvent = record
18+ typ: I32;
19+ serial: U64;
20+ sendEvent: I32;
21+ display: ^U8;
22+ window, root, subwindow, time: U64;
23+ x, y, xRoot, yRoot: I32;
24+ state, keycode: U32;
25+ sameScreen: I32;
26+ end;
27+
28+extern proc XOpenDisplay(name: ^U8): ^U8;
29+extern proc XDefaultScreen(d: ^U8): I32;
30+extern proc XRootWindow(d: ^U8; screen: I32): U64;
31+extern proc XBlackPixel(d: ^U8; screen: I32): U64;
32+extern proc XWhitePixel(d: ^U8; screen: I32): U64;
33+extern proc XDefaultGC(d: ^U8; screen: I32): ^U8;
34+extern proc XCreateSimpleWindow(d: ^U8; parent: U64; x, y: I32;
35+ width, height, border: U32; borderColor, background: U64): U64;
36+extern proc XStoreName(d: ^U8; w: U64; name: ^U8): I32;
37+extern proc XSelectInput(d: ^U8; w: U64; mask: I64): I32;
38+extern proc XMapWindow(d: ^U8; w: U64): I32;
39+extern proc XNextEvent(d: ^U8; ev: ^U8): I32;
40+extern proc XDrawString(d: ^U8; w: U64; gc: ^U8; x, y: I32; s: ^U8; n: I32): I32;
41+extern proc XCloseDisplay(d: ^U8): I32;
42+
43+proc main*: I64;
44+const text = "hello, world: press a key";
45+var
46+ d: ^U8; s: I32; w: U64;
47+ ev: [24]I64; (* XEvent: 192 bytes *)
48+ key: ^KeyEvent;
49+begin
50+ d := XOpenDisplay(nil);
51+ if d = nil then Out.str("no display\n"); return 1; end;
52+ s := XDefaultScreen(d);
53+ w := XCreateSimpleWindow(d, XRootWindow(d, s), 0, 0, 320, 80, 1,
54+ XBlackPixel(d, s), XWhitePixel(d, s));
55+ XStoreName(d, w, "jed");
56+ XSelectInput(d, w, ExposureMask + KeyPressMask);
57+ XMapWindow(d, w);
58+ repeat
59+ XNextEvent(d, ^U8(ADR(ev)));
60+ if I32(ev[0]) = Expose then
61+ XDrawString(d, w, XDefaultGC(d, s), 20, 45, text, I32(LEN(text)));
62+ end;
63+ until I32(ev[0]) = KeyPress;
64+ key := ^KeyEvent(ADR(ev));
65+ Out.str("key "); Out.int(I64(key^.keycode)); Out.ln;
66+ XCloseDisplay(d);
67+ return 0;
68+end;
69+
70+end Window.

lib/C.jed added +18 -0

@@ -0,0 +1,18 @@
1+(* The C library: what jed's own library calls in it, and what most
2+ programs reach for. A program that imports C uses C, and so is
3+ linked dynamically and starts through the C library. *)
4+module C;
5+
6+extern proc write*(fd: I32; buf: ^U8; n: U64): I64;
7+extern proc mmap*(addr: ^U8; n: U64; prot, flags, fd: I32; off: I64): ^U8;
8+extern proc munmap*(addr: ^U8; n: U64): I32;
9+extern proc isatty*(fd: I32): I32;
10+extern proc exit*(status: I32);
11+extern proc _exit*(status: I32);
12+extern proc __errno_location*: ^I32; (* errno is this thread's: through here *)
13+extern proc printf*(format: ^U8; ...): I32;
14+extern proc fflush*(f: ^U8): I32;
15+extern var stdout*: ^U8; (* FILE * *)
16+extern var stderr*: ^U8;
17+
18+end C.

lib/Out.jed modified +36 -9

@@ -1,23 +1,47 @@
1-(* Writing text and numbers to standard output. Nothing is buffered:
2- each call is one write. *)
1+(* Writing text and numbers to standard output, through a buffer of
2+ 4 KB. The buffer is written out when it is full, at each line feed
3+ when standard output is a terminal, by flush, and when the program
4+ ends by Rt.exit. C's stdio keeps a buffer of its own: a program that
5+ writes with both flushes one before writing with the other. *)
36 module Out;
4-import Sys;
7+import Rt, Sys;
8+
9+var
10+ buf: [4096]U8;
11+ n: I64; (* bytes in buf *)
12+ tty: BOOL; (* standard output is a terminal *)
513
6-proc str*(s: []U8);
14+(* Writes out the buffer. What can't be written is dropped. *)
15+proc flush*;
16+var i, k: I64;
717 begin
8- Sys.write(Sys.stdout, s);
18+ i := 0;
19+ while i < n do
20+ k := Sys.write(Sys.stdout, buf[i..n]);
21+ if k > 0 then i := i + k;
22+ elsif k # -4 then break; (* -EINTR: try again *)
23+ end;
24+ end;
25+ n := 0;
926 end;
1027
1128 proc char*(c: U8);
12-var b: [1]U8;
1329 begin
14- b[0] := c;
15- Sys.write(Sys.stdout, b);
30+ if n = LEN(buf) then flush; end;
31+ buf[n] := c;
32+ INC(n);
33+ if (c = '\n') and tty then flush; end;
1634 end;
1735
36+proc str*(s: []U8);
37+var i: I64;
38+begin
39+ for i := 0 to LEN(s) - 1 do char(s[i]); end;
40+end;
41+
1842 proc ln*;
1943 begin
20- str("\n");
44+ char('\n');
2145 end;
2246
2347 (* n in decimal *)
@@ -54,4 +78,7 @@
5478 str(buf[i..16]);
5579 end;
5680
81+begin
82+ tty := Sys.isTerminal(Sys.stdout);
83+ Rt.atExit(flush);
5784 end Out.

lib/Rt.jed modified +40 -4

@@ -1,9 +1,45 @@
1-(* What the compiler's code calls: fail when a check fails, eq when =
2- or # compares two strings. The compiler finds them by these names. *)
1+(* The run time: ending the program, and what the compiler's code
2+ calls: fail when a check fails, eq when = or # compares two strings.
3+ The compiler finds fail, eq, exit and cExit by these names. *)
34 module Rt;
45 import Sys;
56
6-(* A check failed at line of file: says so on standard error and stops
7+const
8+ Full*: ERROR = "too many procedures to run at exit";
9+ MaxAtExit = 32;
10+
11+var
12+ atExits: [MaxAtExit]proc;
13+ numAtExit: I64;
14+ cExit: proc(status: I32); (* C's exit, set first thing in a program that uses C *)
15+
16+(* Registers p to run when the program ends by exit. *)
17+proc atExit*(p: proc): ERROR;
18+begin
19+ if numAtExit = MaxAtExit then return Full; end;
20+ atExits[numAtExit] := p;
21+ INC(numAtExit);
22+ return nil;
23+end;
24+
25+(* Runs the procedures registered with atExit, the last first, then
26+ ends the program with status: through C's exit in a program that
27+ uses C, so that C flushes its buffers too. Each procedure is taken
28+ off the list before it runs, so it runs once even if it fails or
29+ calls exit itself. *)
30+proc exit*(status: I64);
31+var p: proc;
32+begin
33+ while numAtExit > 0 do
34+ DEC(numAtExit);
35+ p := atExits[numAtExit];
36+ p();
37+ end;
38+ if cExit # nil then cExit(I32(status)); end;
39+ Sys.exit(status);
40+end;
41+
42+(* A check failed at line of file: says so on standard error and ends
743 the program with status 2. *)
844 proc fail*(file: ^U8; line: I64);
945 var buf: [20]U8; i, n: I64;
@@ -21,7 +57,7 @@
2157 buf[i] := ':';
2258 Sys.write(Sys.stderr, buf[i..20]);
2359 Sys.write(Sys.stderr, ": index out of range\n");
24- Sys.exit(2);
60+ exit(2);
2561 end;
2662
2763 proc eq*(a, b: []U8): BOOL;

lib/Sys.jed added +57 -0

@@ -0,0 +1,57 @@
1+(* System calls through the C library: Sys for the targets that have no
2+ file of their own, with the same exports. A program that imports it
3+ uses C. *)
4+module Sys;
5+import C;
6+
7+const
8+ stdin* = 0;
9+ stdout* = 1;
10+ stderr* = 2;
11+
12+(* minus errno, as a system call returns it *)
13+proc failed: I64;
14+var e: ^I32;
15+begin
16+ e := C.__errno_location();
17+ return -I64(e^);
18+end;
19+
20+(* Writes s to the file descriptor fd; the number of bytes written, or
21+ minus an errno. *)
22+proc write*(fd: I64; s: []U8): I64;
23+var r: I64;
24+begin
25+ if LEN(s) = 0 then return 0; end;
26+ r := C.write(I32(fd), ADR(s[0]), U64(LEN(s)));
27+ if r < 0 then return failed(); end;
28+ return r;
29+end;
30+
31+(* size bytes of fresh, zeroed memory from the system, a multiple of
32+ pages, or nil. *)
33+proc mmap*(size: I64): ^U8;
34+var p: ^U8;
35+begin
36+ p := C.mmap(nil, U64(size), 3, 22H, -1, 0); (* read, write; private, anonymous *)
37+ if I64(p) = -1 then return nil; end;
38+ return p;
39+end;
40+
41+proc munmap*(p: ^U8; size: I64);
42+begin
43+ C.munmap(p, U64(size));
44+end;
45+
46+proc isTerminal*(fd: I64): BOOL;
47+begin
48+ return C.isatty(I32(fd)) = 1;
49+end;
50+
51+(* Ends the program, at once, with status. *)
52+proc exit*(status: I64);
53+begin
54+ C._exit(I32(status));
55+end;
56+
57+end Sys.

lib/Sys.linux-x86_64.jed modified +8 -0

@@ -30,6 +30,14 @@
3030 SYSCALL(11, p, size);
3131 end;
3232
33+(* Whether the file descriptor fd is a terminal: whether it has a
34+ terminal's settings to read (ioctl TCGETS). *)
35+proc isTerminal*(fd: I64): BOOL;
36+var t: [8]I64; (* struct termios: 60 bytes *)
37+begin
38+ return SYSCALL(16, fd, 5401H, ADR(t)) = 0;
39+end;
40+
3341 (* Ends the program, at once, with status. *)
3442 proc exit*(status: I64);
3543 begin

src/elf.pas modified +157 -33

@@ -1,13 +1,19 @@
11 { elf.pas: the executable file.
22
3- Writes a static ELF64 executable for x86-64 Linux: the ELF header,
4- one program header per section that has anything in it, the linked
5- text and rodata, and section headers with a symbol table, so that
6- objdump and gdb can name each procedure and variable.
3+ Writes an ELF64 executable for x86-64 Linux: the ELF header, the
4+ program headers, the linked text and rodata, and section headers
5+ with a symbol table, so that objdump and gdb can name each procedure
6+ and variable.
77
8+ A program that uses C is linked dynamically, in the least way the
9+ loader accepts: it names its loader and libraries, and each C symbol
10+ it uses is a quadword the loader fills in with the symbol's address
11+ (a GLOB_DAT relocation), which the code calls or reads through.
12+ There is no PLT and no lazy binding, and the program exports nothing.
13+
814 Depends on: link for the images and addresses, x64 for the chunks,
915 scan for names and errors, BaseUnix to write the file.
10- Leaves out: dynamic linking, for now. }
16+ Leaves out: position independent executables, symbol versions. }
1117
1218 unit elf;
1319
@@ -17,8 +23,9 @@
1723
1824 uses scan, x64, link;
1925
20-const
21- HeaderSize = 64 + 3 * 56; { the ELF header and up to three program headers }
26+var
27+ needed: array[0..31] of longint; { the libraries to load, names interned }
28+ numNeeded: longint; { none: a static program }
2229
2330 procedure WriteElf(const path: shortstring; entry: longint);
2431
@@ -70,16 +77,16 @@
7077 end;
7178 end;
7279
73-procedure Phdr(flags: longint; off, adr, filesz, memsz: int64);
80+procedure Phdr(typ, flags: longint; off, adr, filesz, memsz, align: int64);
7481 begin
75- PutN(1, 4); { PT_LOAD }
82+ PutN(typ, 4);
7683 PutN(flags, 4);
7784 PutN(off, 8);
7885 PutN(adr, 8);
7986 PutN(adr, 8);
8087 PutN(filesz, 8);
8188 PutN(memsz, 8);
82- PutN(Page, 8);
89+ PutN(align, 8);
8390 end;
8491
8592 procedure Shdr(name, typ: longint; flags, adr, off, size: int64; lnk, info: longint; align, entsize: int64);
@@ -89,22 +96,126 @@
8996 PutN(align, 8); PutN(entsize, 8);
9097 end;
9198
99+procedure PutStr(const s: shortstring);
100+begin
101+ PutBytes(@s[1], length(s));
102+ PutN(0, 1);
103+end;
104+
105+const
106+ Interp = '/lib64/ld-linux-x86-64.so.2';
107+ { program header types }
108+ PtLoad = 1; PtDynamic = 2; PtInterp = 3; PtGnuStack = $6474E551;
109+
110+var
111+ { in the room at the end of rodata: where each of the loader's
112+ tables starts, from extraAdr }
113+ symAt, relaAt, hashAt, strAt: int64;
114+ nsym, strLen: longint;
115+
116+{ The sizes of the loader's tables: what LinkAll must leave room for. }
117+procedure SizeTables(var roExtra, dynSize: int64);
118+var c, i: longint;
119+begin
120+ nsym := 1;
121+ strLen := 1;
122+ for i := 0 to numNeeded - 1 do strLen := strLen + length(NameOf(needed[i])) + 1;
123+ for c := 0 to numChunks - 1 do
124+ if chunks^[c].live and chunks^[c].ext then begin
125+ inc(nsym);
126+ strLen := strLen + length(NameOf(chunks^[c].name)) + 1;
127+ end;
128+ symAt := (length(Interp) + 1 + 7) div 8 * 8;
129+ relaAt := symAt + nsym * 24;
130+ hashAt := relaAt + (nsym - 1) * 24;
131+ strAt := hashAt + 4 * (3 + nsym);
132+ roExtra := strAt + strLen;
133+ dynSize := (numNeeded + 10) * 16;
134+end;
135+
136+{ The loader's tables in the room at the end of rodata, which the
137+ buffer already holds as zeros: the loader's name; the symbols, one
138+ for each C symbol used; a GLOB_DAT relocation for each, at its
139+ quadword; a hash table of one bucket; and their names. }
140+procedure PutTables;
141+var c, k, i, at, name: longint;
142+begin
143+ len := extraAdr - Base;
144+ PutStr(Interp);
145+ PadTo(extraAdr - Base + symAt);
146+ PutN(0, 24);
147+ name := strLen;
148+ for c := numChunks - 1 downto 0 do { names go last in the string table }
149+ if chunks^[c].live and chunks^[c].ext then name := name - length(NameOf(chunks^[c].name)) - 1;
150+ for c := 0 to numChunks - 1 do
151+ if chunks^[c].live and chunks^[c].ext then begin
152+ PutN(name, 4); PutN($10, 1); PutN(0, 1); PutN(0, 2); { global, undefined }
153+ PutN(0, 8); PutN(0, 8);
154+ name := name + length(NameOf(chunks^[c].name)) + 1;
155+ end;
156+ k := 1;
157+ for c := 0 to numChunks - 1 do
158+ if chunks^[c].live and chunks^[c].ext then begin
159+ PutN(chunks^[c].adr, 8);
160+ PutN(qword(k) shl 32 or 6, 8); { R_X86_64_GLOB_DAT }
161+ PutN(0, 8);
162+ inc(k);
163+ end;
164+ PutN(1, 4); PutN(nsym, 4); PutN(nsym - 1, 4); { the bucket chains every symbol }
165+ PutN(0, 4);
166+ for i := 1 to nsym - 1 do PutN(i - 1, 4);
167+ PutN(0, 1);
168+ for i := 0 to numNeeded - 1 do PutStr(NameOf(needed[i]));
169+ for c := 0 to numChunks - 1 do
170+ if chunks^[c].live and chunks^[c].ext then PutStr(NameOf(chunks^[c].name));
171+ len := roOff + roSize;
172+
173+ { the dynamic table, at the start of the writable segment }
174+ PadTo(bssAdr - Base);
175+ at := 1;
176+ for i := 0 to numNeeded - 1 do begin
177+ PutN(1, 8); PutN(at, 8); { DT_NEEDED }
178+ at := at + length(NameOf(needed[i])) + 1;
179+ end;
180+ PutN(4, 8); PutN(extraAdr + hashAt, 8); { DT_HASH }
181+ PutN(5, 8); PutN(extraAdr + strAt, 8); { DT_STRTAB }
182+ PutN(6, 8); PutN(extraAdr + symAt, 8); { DT_SYMTAB }
183+ PutN(10, 8); PutN(strLen, 8); { DT_STRSZ }
184+ PutN(11, 8); PutN(24, 8); { DT_SYMENT }
185+ PutN(7, 8); PutN(extraAdr + relaAt, 8); { DT_RELA }
186+ PutN(8, 8); PutN((nsym - 1) * 24, 8); { DT_RELASZ }
187+ PutN(9, 8); PutN(24, 8); { DT_RELAENT }
188+ PutN(21, 8); PutN(0, 8); { DT_DEBUG, for gdb }
189+ PutN(0, 16); { DT_NULL }
190+end;
191+
92192 procedure WriteElf(const path: shortstring; entry: longint);
93193 const
94- ShNames = #0'.text'#0'.rodata'#0'.bss'#0'.symtab'#0'.strtab'#0'.shstrtab'#0;
194+ ShNames = #0'.text'#0'.rodata'#0'.bss'#0'.symtab'#0'.strtab'#0'.shstrtab'#0 +
195+ '.dynamic'#0'.dynstr'#0'.dynsym'#0;
95196 var
96- nph, c, nsym, fd: longint;
97- symOff, strOff, shstrOff, shOff, strLen: int64;
197+ nph, nsh, c, nsyms, fd: longint;
198+ roExtra, dynSize, symOff, strOff, shstrOff, shOff, strsLen: int64;
98199 strs: PBytes;
99200 s, p: shortstring;
100201 sec: longint;
202+ dynamic: boolean;
101203 begin
102204 cap := 1 shl 16;
103205 buf := GetMem(cap);
104206 len := 0;
105- nph := 1;
106- if roSize > 0 then inc(nph);
107- if bssSize > 0 then inc(nph);
207+ MarkLive(entry);
208+ dynamic := numNeeded > 0;
209+ roExtra := 0; dynSize := 0;
210+ if dynamic then SizeTables(roExtra, dynSize);
211+ { room for the most program headers either kind of program has }
212+ LinkAll(64 + 6 * 56, roExtra, dynSize);
213+ if dynamic then nph := 6
214+ else begin
215+ nph := 2;
216+ if roSize > 0 then inc(nph);
217+ if bssSize > 0 then inc(nph);
218+ end;
108219
109220 { ELF header }
110221 PutN($464C457F, 4); PutN(2, 1); PutN(1, 1); PutN(1, 1); PutN(0, 9);
@@ -115,49 +226,57 @@
115226 PutN(64, 8); { program headers follow }
116227 PutN(0, 8); { section headers: patched below }
117228 PutN(0, 4);
229+ nsh := 7;
230+ if dynamic then nsh := 10;
118231 PutN(64, 2); PutN(56, 2); PutN(nph, 2);
119- PutN(64, 2); PutN(7, 2); PutN(6, 2);
232+ PutN(64, 2); PutN(nsh, 2); PutN(6, 2);
120233
234+ if dynamic then Phdr(PtInterp, 4, extraAdr - Base, extraAdr, length(Interp) + 1, length(Interp) + 1, 1);
121235 { the first segment maps the headers too, so text can follow them }
122- Phdr(5, 0, Base, textOff + textSize, textOff + textSize);
123- if roSize > 0 then Phdr(4, roOff, Base + roOff, roSize, roSize);
124- if bssSize > 0 then Phdr(6, 0, bssAdr, 0, bssSize);
236+ Phdr(PtLoad, 5, 0, Base, textOff + textSize, textOff + textSize, Page);
237+ if roSize > 0 then Phdr(PtLoad, 4, roOff, Base + roOff, roSize, roSize, Page);
238+ if dynamic then begin
239+ Phdr(PtLoad, 6, bssAdr - Base, bssAdr, dynSize, bssSize, Page);
240+ Phdr(PtDynamic, 6, bssAdr - Base, bssAdr, dynSize, dynSize, 8);
241+ end else if bssSize > 0 then Phdr(PtLoad, 6, 0, bssAdr, 0, bssSize, Page);
242+ Phdr(PtGnuStack, 6, 0, 0, 0, 0, 16); { a stack that can't run code }
125243
126244 PadTo(textOff);
127245 PutBytes(textImg, textSize);
128246 PadTo(roOff); { even when empty, so that every section lies in the file }
129247 PutBytes(roImg, roSize);
248+ if dynamic then PutTables;
130249
131250 { the symbol table: one local symbol for each named live chunk }
132251 PadTo((len + 7) div 8 * 8);
133252 symOff := len;
134253 strs := GetMem(1 shl 16);
135- strLen := 1;
254+ strsLen := 1;
136255 strs^[0] := 0;
137256 PutN(0, 24);
138- nsym := 1;
257+ nsyms := 1;
139258 for c := 0 to numChunks - 1 do
140- if chunks^[c].live and (chunks^[c].name >= 0) then begin
259+ if chunks^[c].live and (chunks^[c].name >= 0) and not chunks^[c].ext then begin
141260 s := ChunkName(c);
142- if strLen + length(s) + 1 > MemSize(strs) then strs := ReAllocMem(strs, strLen * 2 + 256);
143- Move(s[1], strs^[strLen], length(s));
144- strs^[strLen + length(s)] := 0;
261+ if strsLen + length(s) + 1 > MemSize(strs) then strs := ReAllocMem(strs, strsLen * 2 + 256);
262+ Move(s[1], strs^[strsLen], length(s));
263+ strs^[strsLen + length(s)] := 0;
145264 case chunks^[c].sec of
146265 secText: sec := 1;
147266 secRodata: sec := 2;
148267 else sec := 3;
149268 end;
150- PutN(strLen, 4);
269+ PutN(strsLen, 4);
151270 if sec = 1 then PutN(2, 1) else PutN(1, 1); { STT_FUNC, STT_OBJECT }
152271 PutN(0, 1);
153272 PutN(sec, 2);
154273 PutN(chunks^[c].adr, 8);
155274 PutN(chunks^[c].size, 8);
156- strLen := strLen + length(s) + 1;
157- inc(nsym);
275+ strsLen := strsLen + length(s) + 1;
276+ inc(nsyms);
158277 end;
159278 strOff := len;
160- PutBytes(strs, strLen);
279+ PutBytes(strs, strsLen);
161280 shstrOff := len;
162281 s := ShNames;
163282 PutBytes(@s[1], length(s));
@@ -168,10 +287,15 @@
168287 Shdr(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
169288 Shdr(1, 1, 6, Base + textOff, textOff, textSize, 0, 0, 16, 0);
170289 Shdr(7, 1, 2, Base + roOff, roOff, roSize, 0, 0, 16, 0);
171- Shdr(15, 8, 3, bssAdr, roOff + roSize, bssSize, 0, 0, 16, 0);
172- Shdr(20, 2, 0, 0, symOff, nsym * 24, 5, nsym, 8, 24);
173- Shdr(28, 3, 0, 0, strOff, strLen, 0, 0, 1, 0);
290+ Shdr(15, 8, 3, bssAdr + dynSize, roOff + roSize, bssSize - dynSize, 0, 0, 16, 0);
291+ Shdr(20, 2, 0, 0, symOff, nsyms * 24, 5, nsyms, 8, 24);
292+ Shdr(28, 3, 0, 0, strOff, strsLen, 0, 0, 1, 0);
174293 Shdr(36, 3, 0, 0, shstrOff, length(ShNames), 0, 0, 1, 0);
294+ if dynamic then begin { the loader's tables, for readelf and objdump }
295+ Shdr(46, 6, 3, bssAdr, bssAdr - Base, dynSize, 8, 0, 8, 16);
296+ Shdr(55, 3, 2, extraAdr + strAt, extraAdr + strAt - Base, strLen, 0, 0, 1, 0);
297+ Shdr(63, 11, 2, extraAdr + symAt, extraAdr + symAt - Base, nsym * 24, 8, 1, 8, 24);
298+ end;
175299
176300 p := path + #0;
177301 fd := FpOpen(@p[1], O_WRONLY or O_CREAT or O_TRUNC, &755);

src/gen.pas modified +31 -13

@@ -54,6 +54,8 @@
5454 target: int64; { the frame slot of a procedure value, if any }
5555 chunk: longint; { else the procedure's chunk }
5656 code: boolean; { a code procedure: two results come in rax and rdx }
57+ ext: boolean; { C's: called through the chunk holding its address }
58+ isF: array[0..63] of boolean; { each argument: goes in an xmm register }
5759 end;
5860
5961 var
@@ -191,7 +193,10 @@
191193 oVar: begin
192194 x.mode := mVar;
193195 x.isVar := true;
194- if o^.lev = 0 then begin
196+ if o^.ext then begin
197+ Load(RAX, MemRip(o^.chunk, 0), 8, false);
198+ x.base := bReg; x.reg := RAX;
199+ end else if o^.lev = 0 then begin
195200 x.base := bGlobal; x.chunk := o^.chunk
196201 end else if o^.ind then begin
197202 Load(RAX, Mem(RBP, o^.val), 8, false);
@@ -290,7 +295,8 @@
290295 mProc: begin
291296 if x.obj^.isCode and (x.obj^.typ^.base <> nil) and x.obj^.typ^.base^.tuple then
292297 Mark('a code procedure with two results can only be called');
293- Lea(RAX, MemRip(x.obj^.chunk, 0));
298+ if x.obj^.ext then Load(RAX, MemRip(x.obj^.chunk, 0), 8, false)
299+ else Lea(RAX, MemRip(x.obj^.chunk, 0));
294300 end;
295301 else Mark('not a value');
296302 end;
@@ -976,9 +982,9 @@
976982 begin
977983 if x.mode = mProc then begin
978984 c.sig := x.obj^.typ; c.chunk := x.obj^.chunk; c.target := 0;
979- c.code := x.obj^.isCode;
985+ c.code := x.obj^.isCode; c.ext := x.obj^.ext;
980986 end else begin
981- c.code := false;
987+ c.code := false; c.ext := false;
982988 if x.typ^.form <> fProc then Mark('not a procedure');
983989 c.sig := x.typ; c.chunk := -1;
984990 c.target := ToSlot(x);
@@ -991,8 +997,20 @@
991997 var p: PObj; s: int64;
992998 begin
993999 p := c.param;
994- if p = nil then Mark('too many arguments');
9951000 if c.n > High(c.slots) then Mark('too many arguments');
1001+ if p = nil then begin
1002+ { past the parameters of a C procedure that ends in ...: a string
1003+ goes as a C string, an integer constant as an I64 }
1004+ if not c.sig^.variadic then Mark('too many arguments');
1005+ if a.mode = mStr then Coerce(a, tPtrU8)
1006+ else if a.typ^.form = fConst then Coerce(a, tI64)
1007+ else if not IsScalar(a.typ) then Mark('only a single value goes to ...');
1008+ c.isF[c.n] := a.typ^.form = fReal;
1009+ c.slots[c.n] := ToSlot(a);
1010+ inc(c.n);
1011+ exit;
1012+ end;
1013+ c.isF[c.n] := (p^.typ^.form = fReal) and not p^.isVar;
9961014 if p^.isVar then begin
9971015 if (a.mode <> mVar) or not a.isVar then Mark('a var parameter needs a variable');
9981016 if not Same(a.typ, p^.typ) then Mark('a var parameter needs exactly ' + TypeName(p^.typ));
@@ -1017,8 +1035,8 @@
10171035
10181036 procedure EndCall(var c: TCall; var x: TItem);
10191037 var
1020- p: PObj; res: PType; i, ni, nf, k, pad: longint; ret: int64;
1021- isF: array[0..63] of boolean; onStack: array[0..63] of boolean;
1038+ res: PType; i, ni, nf, k, pad: longint; ret: int64;
1039+ onStack: array[0..63] of boolean;
10221040 begin
10231041 if c.param <> nil then Mark('too few arguments');
10241042 res := c.sig^.base;
@@ -1030,14 +1048,11 @@
10301048 end;
10311049 { the System V classes: each argument in the next free register of
10321050 its kind, or else on the stack }
1033- p := c.sig^.fields;
10341051 k := 0;
10351052 for i := 0 to c.n - 1 do begin
1036- isF[i] := (p^.typ^.form = fReal) and not p^.isVar;
1037- if isF[i] then begin onStack[i] := nf >= 8; if nf < 8 then inc(nf) end
1053+ if c.isF[i] then begin onStack[i] := nf >= 8; if nf < 8 then inc(nf) end
10381054 else begin onStack[i] := ni >= 6; if ni < 6 then inc(ni) end;
10391055 if onStack[i] then inc(k);
1040- p := p^.next;
10411056 end;
10421057 pad := ord(odd(depth + k));
10431058 if pad <> 0 then AluI(aluSub, RSP, 8);
@@ -1050,9 +1065,12 @@
10501065 if (ret <> 0) and not c.code then begin Lea(RDI, Mem(RBP, ret)); ni := 1 end;
10511066 for i := 0 to c.n - 1 do
10521067 if not onStack[i] then
1053- if isF[i] then begin MovsdXM(nf, Mem(RBP, c.slots[i])); inc(nf) end
1068+ if c.isF[i] then begin MovsdXM(nf, Mem(RBP, c.slots[i])); inc(nf) end
10541069 else begin Load(IntRegs[ni], Mem(RBP, c.slots[i]), 8, false); inc(ni) end;
1055- if c.chunk >= 0 then CallChunk(c.chunk)
1070+ { a procedure taking ... is told in al how many xmm registers it got }
1071+ if c.sig^.variadic then MovRI(RAX, nf);
1072+ if c.ext then CallM(MemRip(c.chunk, 0))
1073+ else if c.chunk >= 0 then CallChunk(c.chunk)
10561074 else begin
10571075 Load(R11, Mem(RBP, c.target), 8, false);
10581076 CallR(R11);

src/jed.pas modified +85 -14

@@ -6,9 +6,13 @@
66 entry point, links what it reaches, and writes the executable: by
77 default the main module's file without its .jed.
88
9- The entry point saves argc and argv, runs every module's body (those
10- of the modules the program imports, imported modules first), then
11- the main module's main, and exits with its status.
9+ The program starts by saving argc and argv, runs every module's body
10+ (those of the modules the program imports, imported modules first),
11+ then the main module's main, and ends with Rt.exit and main's
12+ status. A static program does this from its entry point. One that
13+ uses C starts through the C library, __libc_start_main, which sets
14+ C up and calls this as C's main; first it gives Rt C's exit, which
15+ Rt.exit then ends the program with.
1216
1317 Depends on: everything else. }
1418
@@ -32,12 +36,51 @@
3236 end;
3337 end;
3438
39+{ Whether the program uses C: if so, the libraries it needs go to
40+ elf.pas, the C library first. }
41+function UsesC: boolean;
42+var m, st, c: PModule; l: PLib; i: longint; seen: boolean;
43+begin
44+ st := nil; c := nil;
45+ numNeeded := 1;
46+ needed[0] := Intern(PChar('libc.so.6'), 9);
47+ m := firstModule;
48+ while m <> nil do begin
49+ if m^.used and m^.linkStatic then st := m;
50+ if m^.used and m^.usesC then c := m;
51+ l := m^.libs;
52+ while m^.used and (l <> nil) do begin
53+ seen := false;
54+ for i := 0 to numNeeded - 1 do seen := seen or (needed[i] = l^.name);
55+ if not seen then begin
56+ if numNeeded > High(needed) then Fatal('too many libraries');
57+ needed[numNeeded] := l^.name;
58+ inc(numNeeded);
59+ end;
60+ l := l^.next;
61+ end;
62+ m := m^.next;
63+ end;
64+ if (st <> nil) and (c <> nil) then
65+ Fatal(NameOf(st^.name) + ' says link static, but ' + NameOf(c^.name) + ' uses C');
66+ if c = nil then numNeeded := 0;
67+ UsesC := c <> nil;
68+end;
69+
70+function RtObj(rt: PModule; const n: shortstring): PObj;
71+var o: PObj;
72+begin
73+ o := Find(rt^.scope, Intern(@n[1], length(n)));
74+ if o = nil then Fatal('Rt has no ' + n);
75+ RtObj := o;
76+end;
77+
3578 var
3679 path, outPath, dir, s: shortstring;
37- i, entry: longint;
80+ i, entry, start: longint;
3881 m, rt: PModule;
3982 main: PObj;
40- hasResult: boolean;
83+ hasResult, dynamic: boolean;
4184
4285 begin
4386 { constants fold as the machine computes: NaN and infinities, no traps }
@@ -89,12 +132,41 @@
89132 hasResult := main^.typ^.base <> nil;
90133 end;
91134
135+ if rt = nil then Fatal('can''t find module Rt');
136+ dynamic := UsesC;
92137 entry := NewChunk(secText, -1, Intern('_start', 6));
93- BeginChunk(entry);
94- Load(RAX, Mem(RSP, 0), 8, false);
95- Store(MemRip(argcChunk, 0), RAX, 8);
96- Lea(RAX, Mem(RSP, 8));
97- Store(MemRip(argvChunk, 0), RAX, 8);
138+ if dynamic then begin
139+ { _start as C's crt1 does it: __libc_start_main(main, argc, argv,
140+ nil, nil, rtld_fini, stack_end), with rsp aligned }
141+ start := NewChunk(secText, -1, Intern('main', 4));
142+ BeginChunk(entry);
143+ MovRI(RBP, 0);
144+ MovRR(R9, RDX);
145+ Pop(RSI);
146+ MovRR(RDX, RSP);
147+ AluI(aluAnd, RSP, -16);
148+ Push(RAX);
149+ Push(RSP);
150+ MovRI(R8, 0);
151+ MovRI(RCX, 0);
152+ Lea(RDI, MemRip(start, 0));
153+ CallM(MemRip(ExternChunk(Intern('__libc_start_main', 17)), 0));
154+ Ud2;
155+ EndChunk(entry);
156+ BeginChunk(start);
157+ Push(RBP); { aligns the stack again }
158+ Store(MemRip(argcChunk, 0), RDI, 8);
159+ Store(MemRip(argvChunk, 0), RSI, 8);
160+ Load(RAX, MemRip(ExternChunk(Intern('exit', 4)), 0), 8, false);
161+ Store(MemRip(RtObj(rt, 'cExit')^.chunk, 0), RAX, 8);
162+ end else begin
163+ start := entry;
164+ BeginChunk(entry);
165+ Load(RAX, Mem(RSP, 0), 8, false);
166+ Store(MemRip(argcChunk, 0), RAX, 8);
167+ Lea(RAX, Mem(RSP, 8));
168+ Store(MemRip(argvChunk, 0), RAX, 8);
169+ end;
98170 m := firstModule;
99171 while m <> nil do begin
100172 if m^.used and (m^.body >= 0) then CallChunk(m^.body);
@@ -102,10 +174,9 @@
102174 end;
103175 if main <> nil then CallChunk(main^.chunk);
104176 if hasResult then MovRR(RDI, RAX) else MovRI(RDI, 0);
105- MovRI(RAX, 231); { exit_group }
106- Syscall;
107- EndChunk(entry);
177+ CallChunk(RtObj(rt, 'exit')^.chunk);
178+ Ud2;
179+ EndChunk(start);
108180
109- LinkAll(entry, HeaderSize);
110181 WriteElf(outPath, entry);
111182 end.

src/link.pas modified +16 -8

@@ -6,8 +6,11 @@
66 every fixup patched.
77
88 The file is laid out so that each section can be mapped as it lies:
9- text right after the headers, rodata on the next page, bss after
10- that, in memory only.
9+ text right after the headers, rodata on the next page, then a
10+ writable page that starts with the table the dynamic loader reads
11+ (none in a static program) and goes on as bss, in memory only. The
12+ loader's other tables come at the end of rodata; elf.pas writes them
13+ in the room left there.
1114
1215 Depends on: x64 for chunks and fixups, scan for names and errors.
1316 Leaves out: the file format; that is elf.pas. }
@@ -26,11 +29,13 @@
2629
2730 var
2831 textOff, textSize: int64; { file offset and size of text }
29- roOff, roSize: int64;
30- bssAdr, bssSize: int64;
32+ roOff, roSize: int64; { rodata, the room for the loader's tables included }
33+ extraAdr: int64; { that room }
34+ bssAdr, bssSize: int64; { the writable segment, the loader's table first }
3135 textImg, roImg: PBytes;
3236
33-procedure LinkAll(entry: longint; headerSize: longint);
37+procedure MarkLive(entry: longint);
38+procedure LinkAll(headerSize, roExtra, dynSize: int64);
3439 function ChunkName(c: longint): shortstring;
3540
3641 implementation
@@ -82,18 +87,21 @@
8287 Place := a;
8388 end;
8489
85-procedure LinkAll(entry: longint; headerSize: longint);
90+{ Places the live chunks, leaving roExtra bytes at the end of rodata
91+ and dynSize at the start of the writable segment. }
92+procedure LinkAll(headerSize, roExtra, dynSize: int64);
8693 var c, f, at: longint; e, p, v: int64;
8794 begin
88- MarkLive(entry);
8995 textOff := (headerSize + 15) div 16 * 16;
9096 e := Place(secText, Base + textOff);
9197 textSize := e - (Base + textOff);
9298 roOff := (textOff + textSize + Page - 1) div Page * Page;
9399 e := Place(secRodata, Base + roOff);
100+ extraAdr := (e + 7) div 8 * 8;
101+ if roExtra > 0 then e := extraAdr + roExtra;
94102 roSize := e - (Base + roOff);
95103 bssAdr := (Base + roOff + roSize + Page - 1) div Page * Page;
96- e := Place(secBss, bssAdr);
104+ e := Place(secBss, bssAdr + dynSize);
97105 bssSize := e - bssAdr;
98106
99107 textImg := GetMem(textSize + 1);

src/parse.pas modified +63 -6

@@ -12,7 +12,8 @@
1212 interface.
1313
1414 Depends on: scan, sym, x64, gen.
15- Leaves out (for stage 3): extern and link. }
15+ Leaves out: linking; a module only records the libraries it names,
16+ and whether it uses C or says link static. }
1617
1718 unit parse;
1819
@@ -60,8 +61,9 @@
6061 directDefer: boolean; { ... as the statement itself, not in a list }
6162 deferSlot: int64; { keeps a result while deferred statements run }
6263 curResult: PType; { the result type of the procedure being compiled }
64+ inExtern: boolean; { reading an extern's signature: ... allowed }
6365 tArgv, tBodySig: PType;
64- nameRt, nameFail, nameEq, nameMain, nameBody: longint;
66+ nameRt, nameFail, nameEq, nameMain, nameBody, nameStatic: longint;
6567
6668 procedure Expression(var x: TItem; want: PType); forward;
6769 function ParseType: PType; forward;
@@ -284,6 +286,7 @@
284286 if tok <> sRparen then
285287 repeat
286288 if tok = sEllipsis then begin
289+ if not inExtern then Mark('... is only for extern procedures');
287290 Next; t^.variadic := true; break
288291 end;
289292 isVar := tok = sVar;
@@ -1343,6 +1346,43 @@
13431346 end;
13441347 end;
13451348
1349+{ An extern procedure or variable: C's, reached through the quadword
1350+ that holds its address. }
1351+procedure ExternDecl;
1352+var n: longint; exp: boolean; o, q: PObj; t: PType;
1353+begin
1354+ Next;
1355+ curModule^.usesC := true;
1356+ if tok = sProc then begin
1357+ Next;
1358+ IdentDef(n, exp);
1359+ inExtern := true;
1360+ t := Signature;
1361+ inExtern := false;
1362+ q := t^.fields;
1363+ while q <> nil do begin
1364+ if q^.isVar or not IsScalar(q^.typ) then
1365+ Mark('C takes integers, BOOL, F64, pointers and procedures');
1366+ q := q^.next;
1367+ end;
1368+ if (t^.base <> nil) and not IsScalar(t^.base) then Mark('C returns a single value');
1369+ o := NewObj(oProc, n, t);
1370+ end else begin
1371+ if tok <> sVar then Mark('proc or var expected');
1372+ Next;
1373+ IdentDef(n, exp);
1374+ Expect(sColon, ':');
1375+ declExported := exp;
1376+ t := ParseType;
1377+ declExported := false;
1378+ o := NewObj(oVar, n, t);
1379+ end;
1380+ o^.exported := exp;
1381+ o^.ext := true;
1382+ o^.chunk := ExternChunk(n);
1383+ Declare(o);
1384+end;
1385+
13461386 procedure Declarations(top: boolean);
13471387 var
13481388 n, i, k: longint; exp: boolean; x: TItem; o: PObj; t: PType;
@@ -1434,7 +1474,11 @@
14341474 ProcDecl;
14351475 Expect(sSemicolon, ';');
14361476 end;
1437- sExtern: Mark('extern comes in stage 3');
1477+ sExtern: begin
1478+ if not top then Mark('extern only at the top of a module');
1479+ ExternDecl;
1480+ Expect(sSemicolon, ';');
1481+ end;
14381482 else exit;
14391483 end;
14401484 until false;
@@ -1512,7 +1556,7 @@
15121556 a := m^.args.o[i];
15131557 if (a = nil) or not Same(a^.typ, sig) then
15141558 Mark('needs a procedure with the signature of ' + NameOf(o^.name));
1515- o^.typ := a^.typ; o^.chunk := a^.chunk; o^.isCode := a^.isCode;
1559+ o^.typ := a^.typ; o^.chunk := a^.chunk; o^.isCode := a^.isCode; o^.ext := a^.ext;
15161560 Declare(o);
15171561 s := s + NameOf(a^.module^.name) + '.' + NameOf(a^.name) + ',';
15181562 inc(i);
@@ -1539,7 +1583,7 @@
15391583 var
15401584 st: TScanState; saved: array[0..MaxDepth - 1] of longint; d: longint;
15411585 oldMod: PModule; oldFile: longint; oldCheck: boolean; m, im: PModule;
1542- imp: PImport; alias, mname: longint; o: PObj; body: longint; iargs: TArgs;
1586+ imp: PImport; lib: PLib; alias, mname: longint; o: PObj; body: longint; iargs: TArgs;
15431587 begin
15441588 SaveScan(st);
15451589 SaveScopes(d, saved);
@@ -1598,7 +1642,19 @@
15981642 until false;
15991643 Expect(sSemicolon, ';');
16001644 end;
1601- if tok = sLink then Mark('link comes in stage 3');
1645+ while tok = sLink do begin
1646+ Next;
1647+ if (tok = sIdent) and (id = nameStatic) then m^.linkStatic := true
1648+ else if tok = sString then begin
1649+ New(lib);
1650+ lib^.name := Intern(@sbuf, slen);
1651+ lib^.next := m^.libs;
1652+ m^.libs := lib;
1653+ m^.usesC := true;
1654+ end else Mark('a library or static expected');
1655+ Next;
1656+ Expect(sSemicolon, ';');
1657+ end;
16021658 Declarations(true);
16031659 if tok = sBegin then begin
16041660 if checkMode then SkipBody
@@ -1738,6 +1794,7 @@
17381794 nameEq := Name('eq');
17391795 nameMain := Name('main');
17401796 nameBody := Name('body');
1797+ nameStatic := Name('static');
17411798 rtFail := NewChunk(secText, nameRt, nameFail);
17421799 rtEq := NewChunk(secText, nameRt, nameEq);
17431800 argcChunk := NewChunk(secBss, -1, Name('argc'));

src/sym.pas modified +12 -0

@@ -31,6 +31,7 @@
3131 PObj = ^TObj;
3232 PModule = ^TModule;
3333 PImport = ^TImport;
34+ PLib = ^TLib;
3435
3536 TType = record
3637 form: TForm;
@@ -65,6 +66,8 @@
6566 isVar: boolean; { a var parameter }
6667 fwd: boolean; { oProc: declared forward, no body yet }
6768 isCode: boolean; { oProc: a code procedure }
69+ ext: boolean; { oProc, oVar: C's, reached through its chunk, which
70+ holds its address }
6871 fields: PObj; { oCase: its fields }
6972 module: PModule; { oModule: the module; others: where declared }
7073 link: PObj; { the next top-level declaration of its module }
@@ -83,6 +86,12 @@
8386 next: PImport;
8487 end;
8588
89+ { A library a module links, by its name, as interned }
90+ TLib = record
91+ name: longint;
92+ next: PLib;
93+ end;
94+
8695 TModule = record
8796 name: longint;
8897 sname: longint; { the name of its symbols: List(I64) for an instance }
@@ -95,6 +104,9 @@
95104 done: boolean; { compiled to the end }
96105 checkOnly: boolean; { read only to check another file's interface }
97106 used: boolean; { imported, through others, by the main module }
107+ usesC: boolean; { has an extern, or links a library }
108+ linkStatic: boolean; { says link static }
109+ libs: PLib; { the libraries it links }
98110 next: PModule; { modules in the order they were finished }
99111 end;
100112

src/x64.pas modified +21 -0

@@ -58,6 +58,7 @@
5858 module, name: longint; { for the symbol table; -1 if none }
5959 adr: int64; { its address, set by the linker }
6060 live: boolean; { reached from the entry point }
61+ ext: boolean; { bss: the address of a C symbol, its name }
6162 end;
6263
6364 TFixup = record
@@ -86,6 +87,7 @@
8687 procedure EndChunk(c: longint);
8788 procedure SetData(c: longint; p: PBytes; n, align: longint);
8889 procedure SetBss(c: longint; size, align: longint);
90+function ExternChunk(name: longint): longint;
8991
9092 procedure Put1(b: longint);
9193 procedure Put4(v: longint);
@@ -118,6 +120,7 @@
118120 procedure CallChunk(c: longint);
119121 procedure CallBack(target: longint);
120122 procedure CallR(r: longint);
123+procedure CallM(const m: TMem);
121124 procedure Ret;
122125 procedure Leave;
123126 procedure Syscall;
@@ -240,6 +243,19 @@
240243 chunks^[c].align := align;
241244 end;
242245
246+{ The quadword that holds the address of C's symbol name, filled in
247+ when the program starts; one for each name. }
248+function ExternChunk(name: longint): longint;
249+var c: longint;
250+begin
251+ for c := 0 to numChunks - 1 do
252+ if chunks^[c].ext and (chunks^[c].name = name) then exit(c);
253+ c := NewChunk(secBss, -1, name);
254+ SetBss(c, 8, 8);
255+ chunks^[c].ext := true;
256+ ExternChunk := c;
257+end;
258+
243259 procedure AddFixup(at, chunk, addend: longint);
244260 begin
245261 if numFixups = fixCap then begin
@@ -486,6 +502,11 @@
486502 procedure CallR(r: longint);
487503 begin
488504 OpR(0, false, $FF, 2, r);
505+end;
506+
507+procedure CallM(const m: TMem);
508+begin
509+ OpM(0, false, $FF, 2, m);
489510 end;
490511
491512 procedure Ret; begin Put1($C3) end;

test/check.sh (history) modified +4 -1

@@ -5,6 +5,8 @@
55 # X.expect its standard output
66 # X.args its arguments, one per line (optional)
77 # X.status its exit status (optional; 0 if missing)
8+# A program without X.expect is compiled, not run. test/libc puts
9+# lib/Sys.jed, over the C library, before the system call one.
810 # Programs in test/err must not compile, and must print X.err.
911
1012 jed=./jed
@@ -19,6 +21,7 @@
1921 echo "FAIL $dir/$name: doesn't compile: $(cat $out/$name.cerr)"
2022 fail=$((fail + 1)); return
2123 fi
24+ if [ ! -f $dir/$name.expect ]; then pass=$((pass + 1)); return; fi
2225 set --
2326 if [ -f $dir/$name.args ]; then
2427 while IFS= read -r a; do set -- "$@" "$a"; done < $dir/$name.args
@@ -39,7 +42,7 @@
3942 fi
4043 }
4144
42-for f in examples/*.jed test/run/*.jed; do
45+for f in examples/*.jed test/run/*.jed test/libc/*.jed; do
4346 run $(dirname $f) $(basename $f .jed)
4447 done
4548 for f in test/err/*.jed; do

test/enctest.pas modified +1 -2

@@ -21,12 +21,11 @@
2121 Unary(2, RAX); Unary(3, RAX); Unary(6, RCX); Unary(7, RCX); Cqo;
2222 Extend(RAX, 1, true); Extend(RAX, 1, false); Extend(RAX, 2, true); Extend(RAX, 2, false); Extend(RAX, 4, true); Extend(RAX, 4, false);
2323 SetCC(ccL, RAX); SetCC(ccA, RCX); TestRR(RAX, RAX);
24- Push(RAX); Push(12); Pop(RCX); Pop(R11); CallR(R11); Ret; Leave; Syscall; Mfence; Ud2; RepMovsb; RepStosb;
24+ Push(RAX); Push(12); Pop(RCX); Pop(R11); CallR(R11); CallM(Mem(RCX, 8)); Ret; Leave; Syscall; Mfence; Ud2; RepMovsb; RepStosb;
2525 LockCmpxchg(Mem(RCX, 0), RDX); Xchg(Mem(RCX, 0), RAX); LockXadd(Mem(RCX, 0), RAX);
2626 MovqXR(0, RAX); MovqXR(1, RCX); MovqRX(RAX, 0); MovsdXM(2, Mem(RBP, -8)); MovsdMX(Mem(RBP, -8), 7);
2727 Sse($58, 0, 1); Sse($5E, 0, 1); Ucomisd(0, 1); Cvtsi2sd(0, RAX); Cvttsd2si(RAX, 0); Btc(RAX, 63);
2828 L := NoLabel; Jcc(ccE, L); Jmp(L); FixLink(L); JmpBack(chunks^[e].start); JccBack(ccNE, chunks^[e].start);
2929 EndChunk(e);
30- LinkAll(e, HeaderSize);
3130 WriteElf(ParamStr(1), e);
3231 end.

test/err/ExternRec.err (history) added +1 -0

@@ -0,0 +1 @@
1+C takes integers, BOOL, F64, pointers and procedures

test/err/ExternRec.jed added +7 -0

@@ -0,0 +1,7 @@
1+module ExternRec;
2+
3+type R = record a, b: I64; end;
4+
5+extern proc f(r: R);
6+
7+end ExternRec.

test/err/Static.err (history) added +1 -0

@@ -0,0 +1 @@
1+Bare says link static, but

test/err/Static.jed added +9 -0

@@ -0,0 +1,9 @@
1+module Static;
2+import Bare, C;
3+
4+proc main*;
5+begin
6+ C.printf("%d\n", Bare.f());
7+end;
8+
9+end Static.

test/err/Variadic.err (history) added +1 -0

@@ -0,0 +1 @@
1+... is only for extern procedures

test/err/Variadic.jed added +7 -0

@@ -0,0 +1,7 @@
1+module Variadic;
2+
3+proc f(a: I64; ...);
4+begin
5+end;
6+
7+end Variadic.

test/err/mods/Bare.jed added +10 -0

@@ -0,0 +1,10 @@
1+(* A module that needs a program without C. *)
2+module Bare;
3+link static;
4+
5+proc f*: I64;
6+begin
7+ return 1;
8+end;
9+
10+end Bare.

test/handtest.pas modified +0 -1

@@ -41,6 +41,5 @@
4141 Syscall;
4242 EndChunk(entry);
4343
44- LinkAll(entry, HeaderSize);
4544 WriteElf(ParamStr(1), entry);
4645 end.

test/libc/Through.expect (history) added +2 -0

@@ -0,0 +1,2 @@
1+through C
2+500500

test/libc/Through.jed added +33 -0

@@ -0,0 +1,33 @@
1+(* The library over C's Sys, lib/Sys.jed, which this directory puts
2+ first: output, memory from the heap, and a failed check that still
3+ writes out what Out holds. *)
4+module Through;
5+import Out, Heap, Mem;
6+
7+type Node = record next: ^Node; n: I64; end;
8+
9+proc main*;
10+var p, list: ^Node; i, sum: I64; a: [3]I64;
11+begin
12+ Out.str("through C\n");
13+ list := nil;
14+ for i := 1 to 1000 do
15+ NEW(p, Heap.heap);
16+ p^.n := i;
17+ p^.next := list;
18+ list := p;
19+ end;
20+ sum := 0;
21+ while list # nil do
22+ sum := sum + list^.n;
23+ p := list;
24+ list := list^.next;
25+ Mem.free(Heap.heap, ^U8(p));
26+ end;
27+ Out.int(sum); Out.ln;
28+ i := 3;
29+ a[i] := 1;
30+ Out.str("not reached\n");
31+end;
32+
33+end Through.

test/libc/Through.status (history) added +1 -0

@@ -0,0 +1 @@
1+2

test/libc/mods/Sys.jed added (symbolic link) +1 -0

@@ -0,0 +1 @@
1+../../../lib/Sys.jed
\ No newline at end of file

test/run/AtExit.expect added +5 -0

@@ -0,0 +1,5 @@
1+12 refused
2+main ends
3+third
4+second, which exits again
5+first

test/run/AtExit.jed added +41 -0

@@ -0,0 +1,41 @@
1+(* Rt.exit runs what Rt.atExit registered, the last first, each once,
2+ then ends the program with main's status. *)
3+module AtExit;
4+import Out, Rt;
5+
6+proc first;
7+begin
8+ Out.str("first\n");
9+end;
10+
11+proc second;
12+begin
13+ Out.str("second, which exits again\n");
14+ Rt.exit(5); (* the rest still run, once each; the status is now 5 *)
15+end;
16+
17+proc third;
18+begin
19+ Out.str("third\n");
20+end;
21+
22+proc nothing;
23+begin
24+end;
25+
26+proc main*: I64;
27+var i, full: I64;
28+begin
29+ Rt.atExit(first);
30+ Rt.atExit(second);
31+ Rt.atExit(third);
32+ full := 0;
33+ for i := 1 to 40 do
34+ if Rt.atExit(nothing) = Rt.Full then INC(full); end;
35+ end;
36+ Out.int(full); Out.str(" refused\n");
37+ Out.str("main ends\n");
38+ return 3;
39+end;
40+
41+end AtExit.

test/run/AtExit.status added +1 -0

@@ -0,0 +1 @@
1+5

test/run/Extern.expect (history) added +13 -0

@@ -0,0 +1,13 @@
1+5
2+8
3+42
4+1414
5+-3 0 1 5 9 12
6+cmp called
7+1 2 3 4 5 6 7 eight|3.142 0.5
8+3
9+environ has entries
10+1
11+5
12+printf -42 too 2.5
13+done

test/run/Extern.jed added +65 -0

@@ -0,0 +1,65 @@
1+(* Calling C: arguments in registers and on the stack, reals, ...,
2+ C variables, jed procedures as C's callbacks. *)
3+module Extern;
4+import Out, C;
5+link "libm.so.6";
6+
7+extern proc strlen(s: ^U8): U64;
8+extern proc qsort(base: ^U8; n, size: U64; cmp: proc(a, b: ^I64): I32);
9+extern proc snprintf(buf: ^U8; n: U64; format: ^U8; ...): I32;
10+extern proc atoi(s: ^U8): I32;
11+extern proc abs(n: I32): I32;
12+extern proc sqrt(x: F64): F64;
13+extern proc getenv(name: ^U8): ^U8;
14+extern proc setenv(name, value: ^U8; overwrite: I32): I32;
15+extern var environ: ^^U8;
16+extern var optind: I32;
17+
18+var calls: I64;
19+
20+proc cmp(a, b: ^I64): I32;
21+begin
22+ INC(calls);
23+ if a^ < b^ then return -1; elsif a^ > b^ then return 1; end;
24+ return 0;
25+end;
26+
27+proc main*;
28+var
29+ a: [6]I64; i: I64; buf: [64]U8; n: I32;
30+ len: proc(s: ^U8): U64; e: ^^U8;
31+begin
32+ Out.int(I64(strlen("hello"))); Out.ln;
33+ len := strlen;
34+ Out.int(I64(len("hi there"))); Out.ln;
35+ Out.int(I64(abs(-7)) + I64(atoi("35"))); Out.ln;
36+ Out.int(I64(sqrt(2.0) * 1000.0)); Out.ln;
37+
38+ a := [5, -3, 9, 0, 12, 1];
39+ qsort(^U8(ADR(a)), 6, 8, cmp);
40+ for i := 0 to 5 do Out.int(a[i]); Out.char(' '); end;
41+ Out.ln;
42+ if calls > 0 then Out.str("cmp called\n"); end;
43+
44+ (* nine arguments after the format: some go on the stack *)
45+ n := snprintf(ADR(buf[0]), 64, "%d %d %d %d %d %d %d %s|%.3f %g",
46+ 1, 2, 3, 4, 5, 6, 7, "eight", 3.14159, 0.5);
47+ Out.str(buf[0..I64(n)]); Out.ln;
48+
49+ setenv("JED_TEST", "yes", 1);
50+ Out.int(I64(strlen(getenv("JED_TEST")))); Out.ln;
51+ e := environ;
52+ i := 0;
53+ while e^ # nil do INC(i); e := e + 1; end;
54+ if i > 0 then Out.str("environ has entries\n"); end;
55+ Out.int(I64(optind)); Out.ln;
56+ optind := 5;
57+ Out.int(I64(optind)); Out.ln;
58+
59+ Out.flush;
60+ C.printf("printf %d %s %.1f\n", -42, "too", 2.5);
61+ C.fflush(C.stdout);
62+ Out.str("done\n");
63+end;
64+
65+end Extern.