diff --git a/README.md b/README.md index 6eb58b6..b9effe2 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,14 @@ - **Linear Ownership.** Rejects use-after-free and double-free. The self-hosted compiler infers where each allocation's life ends and places it on the stack or frees it there ([docs/lifecycles.md](docs/lifecycles.md)). - **Lexical Lenses.** Scoped mutable access without manual pointer arithmetic or ownership transfer. - **Native Backend.** `trackc build` writes a static x86-64 Linux executable itself, with no C compiler, assembler or linker. -- **Track only.** The repository holds no C or Rust. Track targets x86-64 Linux only and bootstraps from a committed native seed binary. +- **Track only.** The repository holds no C or Rust. Track bootstraps from a committed native seed binary. +- **Cross-compiling.** `trackc build --target x86_64-windows` writes a Windows PE executable from any host. + +| target | `trackc build --target` | status | +|---|---|---| +| x86_64-linux | default on Linux | static ELF | +| x86_64-windows | `x86_64-windows` | PE32+ console .exe (kernel32); trackc.exe self-hosts | +| aarch64-linux, x86_64/aarch64-macos, aarch64-windows | | not yet | ## Hello World diff --git a/bootstrap/seed/trackc b/bootstrap/seed/trackc index 26e4437..bf955cb 100755 Binary files a/bootstrap/seed/trackc and b/bootstrap/seed/trackc differ diff --git a/compiler/rt/sys.trk b/compiler/rt/os/linux.trk similarity index 96% rename from compiler/rt/sys.trk rename to compiler/rt/os/linux.trk index 15b9a81..9695e8f 100644 --- a/compiler/rt/sys.trk +++ b/compiler/rt/os/linux.trk @@ -1,5 +1,9 @@ -// rt/sys.trk — Track runtime: arguments, environment, processes, clock, -// files, sockets. All through Linux x86-64 system calls. +// rt/os/linux.trk — Track runtime OS layer for Linux: arguments, +// environment, processes, clock, files, sockets, all through Linux x86-64 +// system calls. Every OS layer (rt/os/.trk) defines the same OS +// interface (docs/native.md, "The OS layer"); trackc loads the one for +// the target. On Linux the portable modules' own `syscall6` calls go +// straight to the kernel; other OS layers also define `os_syscall`. // ---------------------------------------------------------------- process diff --git a/compiler/rt/os/windows.trk b/compiler/rt/os/windows.trk new file mode 100644 index 0000000..8cf8551 --- /dev/null +++ b/compiler/rt/os/windows.trk @@ -0,0 +1,700 @@ +// rt/os/windows.trk — Track runtime OS layer for Windows (kernel32). +// +// Implements the OS interface (docs/native.md, "The OS layer") with +// kernel32 functions called through the import table (`extern`): +// +// os_start process entry: argc/argv from GetCommandLineW, then rt_start +// os_syscall the kernel calls the portable modules (mem, io, libc) +// make through `syscall6`, by Linux number: read, write, +// open, close, stat, lseek, mmap, munmap, mremap, +// madvise, pipe, access, getpid, kill, unlink, +// clock_gettime, exit_group, fchmod. trackc lowers +// `syscall6(nr, a..f)` to `os_syscall(nr, a..e)` on +// every target but Linux. +// os_args_count, os_arg, env_get, env_exists, sys_exec, process_spawn, +// clock_ms, file_open, file_close, file_read_all, file_write, +// file_exists, file_remove, file_size, dir_exists, file_copy, +// track_file_read, track_file_write_all, net_socket_* (not yet: -1) +// +// A file descriptor is a HANDLE; 0, 1 and 2 stand for the standard +// handles. Paths and arguments are UTF-8 in Track and UTF-16 for Windows. + +extern "kernel32.dll" fn GetStdHandle(which: i64) -> i64; +extern "kernel32.dll" fn WriteFile(h: i64, buf: i64, n: i64, done: i64, ov: i64) -> i32; +extern "kernel32.dll" fn ReadFile(h: i64, buf: i64, n: i64, done: i64, ov: i64) -> i32; +extern "kernel32.dll" fn CreateFileW(path: i64, access: i64, share: i64, sec: i64, disp: i64, flags: i64, tmpl: i64) -> i64; +extern "kernel32.dll" fn CloseHandle(h: i64) -> i32; +extern "kernel32.dll" fn ExitProcess(code: i64) -> i64; +extern "kernel32.dll" fn VirtualAlloc(addr: i64, size: i64, kind: i64, prot: i64) -> i64; +extern "kernel32.dll" fn VirtualFree(addr: i64, size: i64, kind: i64) -> i32; +extern "kernel32.dll" fn GetCommandLineW() -> i64; +extern "kernel32.dll" fn GetEnvironmentVariableW(name: i64, buf: i64, n: i64) -> u32; +extern "kernel32.dll" fn GetFileAttributesW(path: i64) -> u32; +extern "kernel32.dll" fn GetFileAttributesExW(path: i64, level: i64, info: i64) -> i32; +extern "kernel32.dll" fn DeleteFileW(path: i64) -> i32; +extern "kernel32.dll" fn SetFileInformationByHandle(h: i64, class: i64, info: i64, size: i64) -> i32; +extern "kernel32.dll" fn SetFilePointerEx(h: i64, dist: i64, newpos: i64, how: i64) -> i32; +extern "kernel32.dll" fn QueryPerformanceCounter(out: i64) -> i32; +extern "kernel32.dll" fn QueryPerformanceFrequency(out: i64) -> i32; +extern "kernel32.dll" fn GetSystemTimePreciseAsFileTime(out: i64) -> i64; +extern "kernel32.dll" fn CreatePipe(rd: i64, wr: i64, sec: i64, size: i64) -> i32; +extern "kernel32.dll" fn GetCurrentProcessId() -> u32; +extern "kernel32.dll" fn GetLastError() -> u32; +extern "kernel32.dll" fn CreateProcessW(app: i64, cmd: i64, psec: i64, tsec: i64, inherit: i64, flags: i64, env: i64, dir: i64, si: i64, pi: i64) -> i32; +extern "kernel32.dll" fn WaitForSingleObject(h: i64, ms: i64) -> u32; +extern "kernel32.dll" fn GetExitCodeProcess(h: i64, code: i64) -> i32; + +const WS_SCRATCH = 6144; // 64 bytes of out-parameters in the state page +const WS_STAT = 6208; // WIN32_FILE_ATTRIBUTE_DATA (36 bytes) + +fn ws(off: i64) -> i64 { return RT_BASE + WS_SCRATCH + off; } + +// ------------------------------------------------------------- UTF-16 + +// A UTF-16 copy (NUL-terminated, heap) of the UTF-8 text `s`. +fn win_wide(s: i64) -> i64 { + let n = rt_strlen(s); + let w = rt_malloc(4 * n + 4); + let mut i: i64 = 0; + let mut o: i64 = 0; + while i < n { + let b0 = load8(s + i); + let mut cp = b0; + let mut k: i64 = 1; + if b0 >= 240 && i + 3 < n + 1 { + cp = ((b0 & 7) << 18) | ((load8(s + i + 1) & 63) << 12) | ((load8(s + i + 2) & 63) << 6) | (load8(s + i + 3) & 63); + k = 4; + } else if b0 >= 224 { + cp = ((b0 & 15) << 12) | ((load8(s + i + 1) & 63) << 6) | (load8(s + i + 2) & 63); + k = 3; + } else if b0 >= 192 { + cp = ((b0 & 31) << 6) | (load8(s + i + 1) & 63); + k = 2; + } + if cp >= 65536 { + let v = cp - 65536; + win_put16(w + o, 55296 + (v >> 10)); + win_put16(w + o + 2, 56320 + (v & 1023)); + o = o + 4; + } else { + win_put16(w + o, cp); + o = o + 2; + } + i = i + k; + } + win_put16(w + o, 0); + return w; +} + +fn win_put16(p: i64, v: i64) -> i64 { + store8(p, v & 255); + return store8(p + 1, (v >> 8) & 255); +} + +fn win_get16(p: i64) -> i64 { return load8(p) | (load8(p + 1) << 8); } + +// Append the UTF-8 encoding of `cp` at `out`; returns the bytes written. +fn win_utf8(out: i64, cp: i64) -> i64 { + if cp < 128 { + store8(out, cp); + return 1; + } + if cp < 2048 { + store8(out, 192 | (cp >> 6)); + store8(out + 1, 128 | (cp & 63)); + return 2; + } + if cp < 65536 { + store8(out, 224 | (cp >> 12)); + store8(out + 1, 128 | ((cp >> 6) & 63)); + store8(out + 2, 128 | (cp & 63)); + return 3; + } + store8(out, 240 | (cp >> 18)); + store8(out + 1, 128 | ((cp >> 12) & 63)); + store8(out + 2, 128 | ((cp >> 6) & 63)); + store8(out + 3, 128 | (cp & 63)); + return 4; +} + +// Code point of the UTF-16 text at `w` (a surrogate pair or one unit). +fn win_cp(w: i64) -> i64 { + let u = win_get16(w); + if u >= 55296 && u < 56320 { + let v = win_get16(w + 2); + if v >= 56320 && v < 57344 { + return 65536 + ((u - 55296) << 10) + (v - 56320); + } + } + return u; +} + +// Bytes of UTF-16 that code point `cp` took. +fn win_cplen(cp: i64) -> i64 { + if cp >= 65536 { + return 4; + } + return 2; +} + +// A UTF-8 copy (heap) of `n` UTF-16 units at `w`. +fn win_narrow(w: i64, n: i64) -> i64 { + let out = rt_malloc(3 * n + 1); + let mut i: i64 = 0; + let mut o: i64 = 0; + while i < 2 * n { + let cp = win_cp(w + i); + i = i + win_cplen(cp); + o = o + win_utf8(out + o, cp); + } + store8(out + o, 0); + return out; +} + +// ------------------------------------------------------------- process + +fn win_space(u: i64) -> bool { return u == 32 || u == 9; } + +// The process entry (trackc's Windows `_start` calls it): split +// GetCommandLineW the way CommandLineToArgvW does, as UTF-8, into an +// argv array followed by an empty envp, then rt_start. +fn os_start() -> i64 { + let cl = GetCommandLineW(); + let mut wl: i64 = 0; + while win_get16(cl + 2 * wl) != 0 { + wl = wl + 1; + } + let size = 8 * (wl + 4) + 4 * wl + 64; + let argv = VirtualAlloc(0, size, 12288, 4); + let mut out = argv + 8 * (wl + 4); + let mut argc: i64 = 0; + let mut i: i64 = 0; + while true { + while win_space(win_get16(cl + 2 * i)) { + i = i + 1; + } + if win_get16(cl + 2 * i) == 0 { + store64(argv + 8 * argc, 0); + store64(argv + 8 * argc + 8, 0); + return rt_start(argc, argv); + } + store64(argv + 8 * argc, out); + argc = argc + 1; + let mut quoted = false; + let mut going = true; + while going { + let u = win_get16(cl + 2 * i); + if u == 0 || (!quoted && win_space(u)) { + going = false; + } else if u == 92 { + let mut nb: i64 = 0; + while win_get16(cl + 2 * i) == 92 { + nb = nb + 1; + i = i + 1; + } + if win_get16(cl + 2 * i) == 34 { + let mut h: i64 = 0; + while h < nb / 2 { + store8(out, 92); + out = out + 1; + h = h + 1; + } + if nb % 2 == 1 { + store8(out, 34); + out = out + 1; + i = i + 1; + } + } else { + let mut h: i64 = 0; + while h < nb { + store8(out, 92); + out = out + 1; + h = h + 1; + } + } + } else if u == 34 { + if quoted && win_get16(cl + 2 * i + 2) == 34 { + store8(out, 34); + out = out + 1; + i = i + 1; + } else { + quoted = !quoted; + } + i = i + 1; + } else { + let cp = win_cp(cl + 2 * i); + i = i + win_cplen(cp) / 2; + out = out + win_utf8(out, cp); + } + } + store8(out, 0); + out = out + 1; + } + return 0; +} + +fn os_args_count() -> i64 { return rs(RS_ARGC); } + +fn os_arg(idx: i64) -> i64 { + if idx >= 0 && idx < rs(RS_ARGC) { + return rt_dup(load64(rs(RS_ARGV) + 8 * idx)); + } + return rt_dup_n("", 0); +} + +// Value of environment variable `key` (heap UTF-8), or 0 when unset. +fn rt_getenv(key: i64) -> i64 { + let wk = win_wide(key); + let mut cap: i64 = 256; + let mut buf = rt_malloc(2 * cap); + let mut n = GetEnvironmentVariableW(wk, buf, cap); + if n > cap { + cap = n; + rt_free(buf); + buf = rt_malloc(2 * cap); + n = GetEnvironmentVariableW(wk, buf, cap); + } + rt_free(wk); + if n == 0 && GetLastError() == 203 { + rt_free(buf); + return 0; + } + let v = win_narrow(buf, n); + rt_free(buf); + return v; +} + +fn env_get(key: i64) -> i64 { + if key == 0 { + return rt_dup_n("", 0); + } + let v = rt_getenv(key); + if v == 0 { + return rt_dup_n("", 0); + } + return v; +} + +fn env_exists(key: i64) -> i64 { + if key != 0 { + let v = rt_getenv(key); + if v != 0 { + rt_free(v); + return 1; + } + } + return 0; +} + +// system(3) with cmd.exe: `cmd.exe /c cmd`; the exit code, -1 when the +// process could not start. +fn sys_exec(cmd: i64) -> i64 { + if cmd == 0 { + return -1; + } + rt_flush(); + let line = str_concat("cmd.exe /c ", cmd); + let wl = win_wide(line); + let si = rt_malloc(104); + rt_zero(si, 104); + store64(si, 104); + let pi = rt_malloc(24); + rt_zero(pi, 24); + let ok = CreateProcessW(0, wl, 0, 0, 1, 0, 0, 0, si, pi); + rt_free(wl); + if ok == 0 { + return -1; + } + let hp = load64(pi); + WaitForSingleObject(hp, 4294967295); + store64(ws(0), 0); + GetExitCodeProcess(hp, ws(0)); + CloseHandle(hp); + CloseHandle(load64(pi + 8)); + return load64(ws(0)) & 4294967295; +} + +fn process_spawn(cmd: i64) -> i64 { return sys_exec(cmd); } + +fn clock_ms() -> i64 { + QueryPerformanceFrequency(ws(0)); + QueryPerformanceCounter(ws(8)); + let f = load64(ws(0)); + let t = load64(ws(8)); + return t / f * 1000 + (t % f) * 1000 / f; +} + +// ---------------------------------------------------------- kernel calls + +fn win_handle(fd: i64) -> i64 { + if fd >= 0 && fd <= 2 { + return GetStdHandle(-10 - fd); + } + return fd; +} + +// open(2) flags -> CreateFileW; a HANDLE or -2 (ENOENT). +fn win_open(path: i64, flags: i64) -> i64 { + let mode = flags & 3; + let mut access: i64 = 2147483648; // GENERIC_READ + if mode == 1 { + access = 1073741824; // GENERIC_WRITE + } else if mode == 2 { + access = 3221225472; + } + let mut disp: i64 = 3; // OPEN_EXISTING + if (flags & 64) != 0 { + disp = 4; // OPEN_ALWAYS + if (flags & 512) != 0 { + disp = 2; // CREATE_ALWAYS + } + } else if (flags & 512) != 0 { + disp = 5; // TRUNCATE_EXISTING + } + let wp = win_wide(path); + let h = CreateFileW(wp, access, 7, 0, disp, 128, 0); + rt_free(wp); + if h == -1 || h == 0 { + return -2; + } + if (flags & 1024) != 0 { + SetFilePointerEx(h, 0, 0, 2); + } + return h; +} + +fn win_stat(path: i64, st: i64) -> i64 { + let wp = win_wide(path); + let ok = GetFileAttributesExW(wp, 0, RT_BASE + WS_STAT); + rt_free(wp); + if ok == 0 { + return -2; + } + let attrs = load64(RT_BASE + WS_STAT) & 4294967295; + let hi = load64(RT_BASE + WS_STAT + 28) & 4294967295; + let lo = load64(RT_BASE + WS_STAT + 32) & 4294967295; + rt_zero(st, 144); + if (attrs & 16) != 0 { + store64(st + 24, 16877); // S_IFDIR | 0755 + } else { + store64(st + 24, 33188); // S_IFREG | 0644 + } + store64(st + 48, (hi << 32) | lo); + return 0; +} + +// The `syscall6` calls of the portable runtime modules, by Linux number; +// -38 (ENOSYS) for the ones Windows has no counterpart for here. +fn os_syscall(nr: i64, a: i64, b: i64, d: i64, e: i64, f: i64) -> i64 { + if nr == 0 || nr == 1 { + store64(ws(0), 0); + let mut ok: i64 = 0; + if nr == 0 { + ok = ReadFile(win_handle(a), b, d, ws(0), 0); + } else { + ok = WriteFile(win_handle(a), b, d, ws(0), 0); + } + if ok == 0 { + let why = GetLastError(); + if nr == 0 && (why == 109 || why == 38) { + return 0; // broken pipe / end of file + } + if why == 998 { + return -14; // EFAULT + } + return -5; + } + return load64(ws(0)) & 4294967295; + } + if nr == 2 { + return win_open(a, b); + } + if nr == 3 { + if a > 2 && CloseHandle(a) == 0 { + return -9; + } + return 0; + } + if nr == 4 { + return win_stat(a, b); + } + if nr == 8 { + if SetFilePointerEx(win_handle(a), b, ws(0), d) == 0 { + return -29; // ESPIPE + } + return load64(ws(0)); + } + if nr == 9 { + let p = VirtualAlloc(a, b, 12288, 4); // MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE + if p == 0 { + return -12; + } + return p; + } + if nr == 11 { + VirtualFree(a, 0, 32768); // MEM_RELEASE + return 0; + } + if nr == 25 { + let q = VirtualAlloc(0, d, 12288, 4); + if q == 0 { + return -12; + } + let mut n = b; + if d < n { + n = d; + } + rt_copy(q, a, n); + VirtualFree(a, 0, 32768); + return q; + } + if nr == 28 || nr == 91 { + return 0; // madvise, fchmod + } + if nr == 22 { + if CreatePipe(ws(0), ws(8), 0, 0) == 0 { + return -24; + } + store64(a, (load64(ws(0)) & 4294967295) | (load64(ws(8)) << 32)); + return 0; + } + if nr == 21 { + let wp = win_wide(a); + let attrs = GetFileAttributesW(wp); + rt_free(wp); + if attrs == 4294967295 { + return -2; + } + return 0; + } + if nr == 87 { + // POSIX semantics: the name goes now even while handles are open + let wp = win_wide(a); + let mut ok: i64 = 0; + let h = CreateFileW(wp, 65536, 7, 0, 3, 33554432, 0); // DELETE, OPEN_EXISTING, BACKUP_SEMANTICS + if h != -1 && h != 0 { + store64(ws(0), 3); // FILE_DISPOSITION_DELETE | POSIX_SEMANTICS + ok = SetFileInformationByHandle(h, 21, ws(0), 4); + CloseHandle(h); + } + if ok == 0 { + ok = DeleteFileW(wp); + } + rt_free(wp); + if ok == 0 { + return -2; + } + return 0; + } + if nr == 39 { + return GetCurrentProcessId(); + } + if nr == 62 { + ExitProcess(128 + b); // a signal: die with 128 + signo + return 0; + } + if nr == 228 { + QueryPerformanceFrequency(ws(0)); + QueryPerformanceCounter(ws(8)); + let fr = load64(ws(0)); + let t = load64(ws(8)); + store64(b, t / fr); + store64(b + 8, (t % fr) * 1000000000 / fr); + return 0; + } + if nr == 231 || nr == 60 { + ExitProcess(a); + return 0; + } + return -38; +} + +// ------------------------------------------------------------------ files +// +// A file handle is a runtime record [HANDLE]; 0 when the open failed. + +const O_RDONLY = 0; +const O_WRONLY_CREAT_TRUNC = 577; +const O_WRONLY_CREAT_APPEND = 1089; +const O_RDWR = 2; + +fn rt_open_flags(mode: i64) -> i64 { + let m = load8(mode); + let plus = rt_find(mode, "+") >= 0; + if m == 114 { + if plus { + return O_RDWR; + } + return O_RDONLY; + } + if m == 119 { + if plus { + return 578; + } + return O_WRONLY_CREAT_TRUNC; + } + if m == 97 { + if plus { + return 1090; + } + return O_WRONLY_CREAT_APPEND; + } + return -1; +} + +fn file_open(path: i64, mode: i64) -> i64 { + if path == 0 || mode == 0 { + return 0; + } + let flags = rt_open_flags(mode); + if flags < 0 { + return 0; + } + let fd = win_open(path, flags); + if fd < 0 { + return 0; + } + let h = rt_malloc(8); + store64(h, fd); + return h; +} + +fn file_close(h: i64) -> i64 { + if h != 0 { + CloseHandle(load64(h)); + rt_free(h); + } + return 0; +} + +// Everything from `fd` to end of file; "" on error. +fn rt_read_fd(fd: i64) -> i64 { + let mut cap: i64 = 4096; + let end = os_syscall(8, fd, 0, 2, 0, 0); + if end >= 0 { + if os_syscall(8, fd, 0, 0, 0, 0) < 0 { + return rt_dup_n("", 0); + } + cap = end + 1; + } + let mut buf = rt_malloc(cap + 1); + let mut got: i64 = 0; + let mut going = true; + while going { + if got == cap { + cap = cap * 2; + buf = rt_realloc(buf, cap + 1); + } + let r = os_syscall(0, fd, buf + got, cap - got, 0, 0); + if r <= 0 { + going = false; + } else { + got = got + r; + } + } + store8(buf + got, 0); + return buf; +} + +fn file_read_all(h: i64) -> i64 { + if h == 0 { + return rt_dup_n("", 0); + } + return rt_read_fd(load64(h)); +} + +fn file_write(h: i64, content: i64) -> i64 { + if h == 0 || content == 0 { + return -1; + } + return rt_write_all(load64(h), content, rt_strlen(content)); +} + +fn file_exists(path: i64) -> i64 { + if path != 0 && os_syscall(21, path, 0, 0, 0, 0) == 0 { + return 1; + } + return 0; +} + +fn file_remove(path: i64) -> i64 { + if path != 0 && os_syscall(87, path, 0, 0, 0, 0) == 0 { + return 0; + } + return -1; +} + +fn file_size(path: i64) -> i64 { + let st = RT_BASE + RS_STAT; + if path == 0 || win_stat(path, st) != 0 { + return -1; + } + return load64(st + 48); +} + +fn dir_exists(path: i64) -> bool { + let st = RT_BASE + RS_STAT; + if path == 0 || win_stat(path, st) != 0 { + return false; + } + return (load64(st + 24) & 61440) == 16384; +} + +fn file_copy(src: i64, dst: i64) -> i64 { + if src == 0 || dst == 0 { + return -1; + } + let content = track_file_read(src); + if file_exists(src) == 0 { + return -1; + } + let fd = win_open(dst, O_WRONLY_CREAT_TRUNC); + if fd < 0 { + return -1; + } + rt_write_all(fd, content, rt_strlen(content)); + CloseHandle(fd); + return 0; +} + +fn track_file_read(path: i64) -> i64 { + if path == 0 { + return rt_dup_n("", 0); + } + let fd = win_open(path, O_RDONLY); + if fd < 0 { + return rt_dup_n("", 0); + } + let out = rt_read_fd(fd); + CloseHandle(fd); + return out; +} + +fn track_file_write_all(path: i64, content: i64) -> i64 { + if path == 0 { + return -1; + } + let fd = win_open(path, O_WRONLY_CREAT_TRUNC); + if fd < 0 { + return -1; + } + let mut status: i64 = -1; + if content != 0 { + status = rt_write_all(fd, content, rt_strlen(content)); + } + if CloseHandle(fd) == 0 { + status = -1; + } + return status; +} + +// ---------------------------------------------------------------- network +// +// Not yet on Windows (Winsock): every call fails. + +fn net_socket_tcp_listen(port: i64) -> i64 { return -1; } +fn net_socket_accept(server_fd: i64) -> i64 { return -1; } +fn net_socket_connect(host: i64, port: i64) -> i64 { return -1; } +fn net_socket_send(fd: i64, data: i64, len: i64) -> i64 { return -1; } +fn net_socket_recv(fd: i64, buf: i64, max_len: i64) -> i64 { return -1; } +fn net_socket_close(fd: i64) -> i64 { return 0; } diff --git a/compiler/src/ast.trk b/compiler/src/ast.trk index b30ef5c..c0501fe 100644 --- a/compiler/src/ast.trk +++ b/compiler/src/ast.trk @@ -45,6 +45,7 @@ const K_UNION = 31; // a = name, b = [name, payload type (-1)]* const K_MATCH = 32; // a = target, b = [pattern, guard (-1), body]* const K_STRUCT = 33; // a = name, b = [field name, type]* const K_FIELD = 34; // a = target, b = field name +const K_EXTERN = 35; // a = name, b = library text, c = [name, type]*, d = return type (-1) // Patterns const P_IDENT = 40; // a = name diff --git a/compiler/src/checker.trk b/compiler/src/checker.trk index c485805..bba9094 100644 --- a/compiler/src/checker.trk +++ b/compiler/src/checker.trk @@ -2259,6 +2259,9 @@ fn check_expr(c: i64, n: i64) -> i64 { if k == K_MACRODEF { return check_function(c, n, true); } + if k == K_EXTERN { + return 0; + } if k == K_USE { return check_use(c, n); } @@ -2505,7 +2508,7 @@ fn check_program(c: i64) -> i64 { declare_enum(c, n); } else if k == K_UNION { declare_union(c, n); - } else if k == K_FN || k == K_MACRODEF { + } else if k == K_FN || k == K_MACRODEF || k == K_EXTERN { fn_register(c, na(c, n), nd(c, n)); } else if k == K_CONST { let mut ty = infer_type(c, nb(c, n)); diff --git a/compiler/src/ffi.trk b/compiler/src/ffi.trk new file mode 100644 index 0000000..87be023 --- /dev/null +++ b/compiler/src/ffi.trk @@ -0,0 +1,90 @@ +// ffi.trk — calls to functions in system libraries (`extern "lib" fn`). +// +// The backend records every imported function it calls in an import +// table: a vector of (library text, symbol text) pairs, the import id of a +// pair being its index / 2. Each call site leaves a fixup: a vector of +// (code position, import id) pairs, the position being a 32-bit field the +// image writer fills once it has laid out the import table. On Windows +// (pe.trk) the field is the rip-relative displacement of the import's IAT +// slot (`call [rip + disp32]`); a Mach-O writer (dyld binding to +// libSystem) or an aarch64 backend reuses the same two vectors and adds +// its own call sequence next to ffi_win64_call. +// +// Track's own calling convention (ngen.trk ng_arg_reg) is not the +// platform's, so each call converts: arguments are evaluated and pushed +// first (first argument deepest), then the call sequence moves them into +// the platform's registers and stack slots. + +import "base"; +import "x64"; + +// Import id of `lib`/`sym` in `imports`, adding the pair when new. +fn ffi_import_id(imports: i64, lib: i64, sym: i64) -> i64 { + let mut i: i64 = 0; + while i < vlen(imports) { + if text_eq(vget(imports, i), lib) && text_eq(vget(imports, i + 1), sym) { + return i / 2; + } + i = i + 2; + } + vpush(imports, lib); + vpush(imports, sym); + return vlen(imports) / 2 - 1; +} + +fn ffi_rm_disp(b: i64, rex: i64, op: i64, modrm: i64, disp: i64) -> i64 { + x_bytes3(b, rex, op, modrm); + return x_u32(b, disp); +} + +// Win64 call of import `id`, its `nargs` arguments pushed (first argument +// deepest). rcx, rdx, r8, r9 take arguments 1-4, the rest go on the stack +// above the 32-byte shadow space, rsp is 16-byte aligned at the call. +// `ret`: 0 keeps rax, 1 sign-extends eax (i32), 2 zero-extends it (u32, +// bool, Win32 BOOL). Leaves the result in rax and pops the arguments. +// Clobbers rax, rcx, rdx, r8-r11 (all volatile in both conventions). +fn ffi_win64_call(b: i64, fixups: i64, id: i64, nargs: i64, ret: i64) -> i64 { + let mut extra: i64 = 0; + if nargs > 4 { + extra = nargs - 4; + } + let frame = (32 + 8 * extra + 8 + 15) & (0 - 16); + x_bytes3(b, 73, 137, 227); // mov r11, rsp (the pushed arguments) + x_bytes3(b, 72, 131, 228); + x_byte(b, 240); // and rsp, -16 + x_bytes3(b, 72, 129, 236); + x_u32(b, frame); // sub rsp, frame + x_bytes3(b, 76, 137, 156); + x_byte(b, 36); + x_u32(b, frame - 8); // mov [rsp + frame - 8], r11 + let mut i: i64 = 4; + while i < nargs { + ffi_rm_disp(b, 73, 139, 131, 8 * (nargs - 1 - i)); // mov rax, [r11 + d] + x_bytes3(b, 72, 137, 132); + x_byte(b, 36); + x_u32(b, 32 + 8 * (i - 4)); // mov [rsp + 32 + 8k], rax + i = i + 1; + } + if nargs > 0 { ffi_rm_disp(b, 73, 139, 139, 8 * (nargs - 1)); } // mov rcx, [r11 + d] + if nargs > 1 { ffi_rm_disp(b, 73, 139, 147, 8 * (nargs - 2)); } // mov rdx, [r11 + d] + if nargs > 2 { ffi_rm_disp(b, 77, 139, 131, 8 * (nargs - 3)); } // mov r8, [r11 + d] + if nargs > 3 { ffi_rm_disp(b, 77, 139, 139, 8 * (nargs - 4)); } // mov r9, [r11 + d] + x_bytes2(b, 255, 21); // call [rip + disp32] + vpush(fixups, vlen(b)); + vpush(fixups, id); + x_u32(b, 0); + x_bytes3(b, 72, 139, 164); + x_byte(b, 36); + x_u32(b, frame - 8); // mov rsp, [rsp + frame - 8] + if nargs > 0 { + x_bytes3(b, 72, 129, 196); + x_u32(b, 8 * nargs); // add rsp, 8 * nargs + } + if ret == 1 { + return x_bytes3(b, 72, 99, 192); // movsxd rax, eax + } + if ret == 2 { + return x_bytes2(b, 137, 192); // mov eax, eax + } + return 0; +} diff --git a/compiler/src/main.trk b/compiler/src/main.trk index 2048b25..1437317 100644 --- a/compiler/src/main.trk +++ b/compiler/src/main.trk @@ -24,6 +24,7 @@ import "symbols"; import "checker"; import "life"; import "ngen"; +import "pe"; import "runtime_trk"; import "lsp"; @@ -32,7 +33,7 @@ fn trackc_version() -> i64 { return "1.0.0"; } fn usage() -> i64 { err("trackc 1.0.0 — the self-hosted Track compiler\n\n"); err("USAGE:\n"); - err(" trackc build [-o ] Compile to a static x86-64 Linux ELF\n"); + err(" trackc build [-o ] Compile to a native executable (ELF, or PE for windows)\n"); err(" -g, --symbols ...with a symbol table (nm, perf, gdb)\n"); err(" trackc run [args...] Compile and run\n"); err(" trackc check Parse and ownership-check only\n"); @@ -43,6 +44,8 @@ fn usage() -> i64 { err(" trackc --version Show version info\n"); err("\nOPTIONS:\n"); err(" --deny-warnings exit 1 when any warning is reported\n"); + err(" --target - build/run/check for x86_64|aarch64 - linux|macos|windows\n"); + err(" (also TRACKC_TARGET; default: the host; built today: x86_64-linux, x86_64-windows)\n"); return 0; } @@ -79,8 +82,13 @@ fn load_checked(path: i64, with_rt: bool) -> i64 { let from = vlen(cx(c, CX_ITEMS)); let node_from = node_count(c); let mut m: i64 = 0; + let os_file = text_cat3("rt/os/", target_os_name(), ".trk"); while m < rt_module_count() { - load_embedded_module(c, rt_module_name(m), rt_module_source(m)); + let name = rt_module_name(m); + // one OS layer: the target's (rt/os/.trk) + if !text_starts(name, "rt/os/") || text_eq(name, os_file) { + load_embedded_module(c, name, rt_module_source(m)); + } m = m + 1; } isolate_runtime(c, from, node_from); @@ -107,6 +115,117 @@ fn warning_count_text(n: i64) -> i64 { return text_cat(text_of_int(n), " warnings"); } +// ---------------------------------------------------------------- targets +// +// `--target -` (or `--target=-`, or TRACKC_TARGET): +// arch x86_64 or aarch64, os linux, macos or windows. The default is the +// host. TG_* match ngen's NG_TARGET. + +const TG_LINUX = 0; +const TG_WINDOWS = 1; +const TG_MACOS = 2; + +// The host's target: Windows when trackc itself runs there. +fn host_target() -> i64 { + if text_eq(env_get("OS"), "Windows_NT") { + return "x86_64-windows"; + } + let me = arg_text(0); + if text_ends(me, ".exe") || text_ends(me, ".EXE") { + return "x86_64-windows"; + } + return "x86_64-linux"; +} + +fn target_text() -> i64 { + let mut i: i64 = 2; + while i < arg_count() { + let a = arg_text(i); + if text_eq(a, "--target") && i + 1 < arg_count() { + return arg_text(i + 1); + } + if text_starts(a, "--target=") { + return str_substr(a, 9, text_len(a) - 9); + } + i = i + 1; + } + if env_exists("TRACKC_TARGET") != 0 { + let t: i64 = env_get("TRACKC_TARGET"); + if text_len(t) > 0 { + return t; + } + } + return host_target(); +} + +fn target_dash(t: i64) -> i64 { + let mut i: i64 = 0; + while i < text_len(t) { + if text_eq(str_substr(t, i, 1), "-") { + return i; + } + i = i + 1; + } + return -1; +} + +fn target_arch_name() -> i64 { + let t = target_text(); + let d = target_dash(t); + if d < 0 { + return t; + } + return str_substr(t, 0, d); +} + +fn target_os_name() -> i64 { + let t = target_text(); + let d = target_dash(t); + if d < 0 { + return ""; + } + return str_substr(t, d + 1, text_len(t) - d - 1); +} + +fn target_os() -> i64 { + let os = target_os_name(); + if text_eq(os, "windows") { + return TG_WINDOWS; + } + if text_eq(os, "macos") { + return TG_MACOS; + } + return TG_LINUX; +} + +// Exit with a clear message unless the target names a known arch and OS. +fn check_target_known() -> i64 { + let arch = target_arch_name(); + let os = target_os_name(); + let arch_ok = text_eq(arch, "x86_64") || text_eq(arch, "aarch64"); + let os_ok = text_eq(os, "linux") || text_eq(os, "macos") || text_eq(os, "windows"); + if !arch_ok || !os_ok { + err(text_cat3("trackc: unknown target '", target_text(), "'\n")); + err(" expected -: arch x86_64 or aarch64, os linux, macos or windows\n"); + quit(2); + } + return 0; +} + +// Exit unless this trackc can generate code for the target. +fn check_target_buildable() -> i64 { + check_target_known(); + let arch = target_arch_name(); + let os = target_os_name(); + if text_eq(arch, "x86_64") && (text_eq(os, "linux") || text_eq(os, "windows")) { + return 0; + } + err(text_cat3("trackc: target '", target_text(), "' is not supported yet\n")); + err(" supported: x86_64-linux, x86_64-windows\n"); + quit(2); + return 0; +} + fn front_end(path: i64) -> i64 { return load_checked(path, false); } @@ -168,7 +287,9 @@ fn file_arg_index() -> i64 { let a = arg_text(i); if text_eq(a, "-o") { i = i + 2; - } else if text_starts(a, "--rt=") || text_eq(a, "--native") || text_eq(a, "--deny-warnings") || text_eq(a, "--place") || text_eq(a, "-g") || text_eq(a, "--symbols") { + } else if text_eq(a, "--target") { + i = i + 2; + } else if text_starts(a, "--target=") || text_starts(a, "--rt=") || text_eq(a, "--native") || text_eq(a, "--deny-warnings") || text_eq(a, "--place") || text_eq(a, "-g") || text_eq(a, "--symbols") { i = i + 1; } else { return i; @@ -181,9 +302,16 @@ fn file_arg_index() -> i64 { // x86-64 ELF executable at `exe`; `-g` (or `--symbols`) adds a symbol table // naming every function. fn build_native(path: i64, exe: i64) -> i64 { + check_target_buildable(); let c = load_checked(path, true); life_place_program(c); // stack cells (ngen `ng_site_cell`) - let body = generate_native(c); + let os = target_os(); + let mut body: i64 = 0; + if os == TG_LINUX { + body = generate_native(c); + } else { + body = generate_native_for(c, os); + } if body == 0 { quit(1); } @@ -196,6 +324,13 @@ fn build_native(path: i64, exe: i64) -> i64 { err(text_cat3("trackc: cannot create directory '", dir, "'\n")); quit(1); } + if os == TG_WINDOWS { + if pe_write_file(exe, body, native_code_len(c), native_imports(c), native_import_fixups(c)) != 0 { + err(text_cat3("trackc: cannot write '", exe, "'\n")); + quit(1); + } + return 0; + } if elf_write_file(exe, body, native_code_len(c), syms) != 0 { err(text_cat3("trackc: cannot write '", exe, "'\n")); quit(1); @@ -208,6 +343,9 @@ fn cmd_build(path: i64) -> i64 { let mut exe = output_flag(); if exe == 0 { exe = file_stem(path); + if target_os() == TG_WINDOWS { + exe = text_cat(exe, ".exe"); + } } build_native(path, exe); out(text_cat3("✓ Built: ", exe, "\n")); @@ -224,6 +362,11 @@ fn require_file() -> i64 { } fn cmd_run(path: i64) -> i64 { + check_target_buildable(); + if !text_eq(target_text(), host_target()) { + err(text_cat3("trackc: cannot run a ", target_text(), " program on this host; use `trackc build --target ...`\n")); + quit(2); + } let mut tmp: i64 = "/tmp"; if env_exists("TMPDIR") != 0 { let t: i64 = env_get("TMPDIR"); @@ -333,6 +476,7 @@ fn main() -> i64 { return 0; } if text_eq(command, "check") { + check_target_known(); let path = require_file(); let c = front_end(path); let n = cx(c, CX_NWARN); diff --git a/compiler/src/ngen.trk b/compiler/src/ngen.trk index d3b7ac4..ed39519 100644 --- a/compiler/src/ngen.trk +++ b/compiler/src/ngen.trk @@ -19,6 +19,7 @@ import "base"; import "ast"; import "symbols"; import "x64"; +import "ffi"; import "elf"; import "life"; import "checker"; @@ -88,7 +89,11 @@ const NG_BARS = 61; // ng_stack_bars of the function ng_function is generatin const NG_BINDSTK = 62; // (kind, value) pairs of the arguments ng_bind_args is binding, nested calls above const NG_ACCCARRY = 63; // accumulator loop: (call, slot, HK_*, position) per argument temporary its back edges carry (F3, F3b) const NG_FWD = 64; // name id -> 0 unknown, -1 none, else the collection primitive the function forwards to (ng_forward) -const NG_SLOTS = 65; +const NG_TARGET = 65; // target OS: 0 linux, 1 windows, 2 macos (TG_* in main.trk) +const NG_IMPORTS = 66; // (library, symbol) text pairs of the imported functions called (ffi.trk) +const NG_IMPFIX = 67; // (code position, import id) fixups of their call sites +const NG_EXTERNS = 68; // name id -> 1 + K_EXTERN node, 0 when the name is not imported +const NG_SLOTS = 69; fn ng(c: i64, slot: i64) -> i64 { return vget(cx(c, CX_GEN), slot); } fn ng_set(c: i64, slot: i64, v: i64) -> i64 { return vset(cx(c, CX_GEN), slot, v); } @@ -3972,6 +3977,8 @@ fn ng_call_body(c: i64, n: i64, args: i64) -> i64 { } } else if builtin >= 0 { arity = builtin; + } else if ng_extern_of(c, target) >= 0 { + return ng_extern_call(c, ng_extern_of(c, target), args, count); } else { vpush(ng(c, NG_MISSING), target); } @@ -4063,6 +4070,12 @@ fn ng_call_body(c: i64, n: i64, args: i64) -> i64 { if text_eq(text, "syscall6") { ng_set(c, NG_CLOB, 1); ng_set(c, NG_VOLX, 1); + if ng(c, NG_TARGET) != 0 { + // no Linux kernel: the OS layer's os_syscall(nr, a..e) (the + // runtime never passes a sixth argument) + x_pop_rax(b); + return ng_call_rt(c, "os_syscall", 6); + } return x_sys_insn(b); } let nr = ng_libc_syscall(text); @@ -5710,6 +5723,7 @@ fn ng_function(c: i64, f: i64, prelude: i64) -> i64 { let start = vlen(b); let calls = vlen(ng(c, NG_CALLS)); let strs = vlen(ng(c, NG_STRS)); + let impfix = vlen(ng(c, NG_IMPFIX)); ng_set(c, NG_PASS, 1); ng_set(c, NG_CLOB, 0); ng_set(c, NG_VOLX, 0); @@ -5728,6 +5742,7 @@ fn ng_function(c: i64, f: i64, prelude: i64) -> i64 { vtrunc(b, start); vtrunc(ng(c, NG_CALLS), calls); vtrunc(ng(c, NG_STRS), strs); + vtrunc(ng(c, NG_IMPFIX), impfix); let regs = ng(c, NG_REG); vfill(regs, nslot, -1); let pins = ng(c, NG_PIN); @@ -5871,6 +5886,79 @@ fn native_code_len(c: i64) -> i64 { return ng(c, NG_CODELEN); } +// ------------------------------------------------- imported functions +// +// `extern "lib" fn` items (K_EXTERN): calls go through the platform's +// import mechanism (ffi.trk), never through Track's convention. + +fn ng_extern_table(c: i64) -> i64 { + let t = vnew(); + let items = cx(c, CX_ITEMS); + let mut i: i64 = 0; + while i < vlen(items) { + let n = vget(items, i); + if nk(c, n) == K_EXTERN { + while vlen(t) <= na(c, n) { + vpush(t, 0); + } + vset(t, na(c, n), n + 1); + } + i = i + 1; + } + return t; +} + +// The K_EXTERN node declaring `name`, or -1. +fn ng_extern_of(c: i64, name: i64) -> i64 { + let t = ng(c, NG_EXTERNS); + if name < vlen(t) { + return vget(t, name) - 1; + } + return -1; +} + +fn ng_extern_call(c: i64, e: i64, args: i64, count: i64) -> i64 { + let b = ncode(c); + if ng(c, NG_TARGET) != 1 { + err(text_cat3("trackc: native: imported function '", name_text(c, na(c, e)), "' needs --target x86_64-windows (this target has no import support yet)\n")); + quit(1); + } + let mut i: i64 = 0; + while i < count { + ng_gen(c, list_at(c, args, i)); + x_push_rax(b); + i = i + 1; + } + let id = ffi_import_id(ng(c, NG_IMPORTS), nb(c, e), name_text(c, na(c, e))); + let ret = nd(c, e); + let mut kind: i64 = 0; + if ret >= 0 && is_prim(c, ret, PRIM_I32) { + kind = 1; + } else if ret >= 0 && (is_prim(c, ret, PRIM_U32) || is_prim(c, ret, PRIM_BOOL)) { + kind = 2; + } + ng_set(c, NG_CLOB, 1); + ng_set(c, NG_VOLX, 1); + return ffi_win64_call(b, ng(c, NG_IMPFIX), id, count, kind); +} + +// Imports and fixups of the generated body, for the image writer. +fn native_imports(c: i64) -> i64 { return ng(c, NG_IMPORTS); } +fn native_import_fixups(c: i64) -> i64 { return ng(c, NG_IMPFIX); } + +// Windows entry: rsp is 8 mod 16. os_start (the OS layer) builds argc/argv +// and calls rt_start; then sys_exit(main()), which ends in ExitProcess. +fn ng_entry_win(c: i64) -> i64 { + let b = ncode(c); + x_bytes3(b, 72, 131, 236); + x_byte(b, 8); // sub rsp, 8 + ng_call_rt(c, "os_start", 0); + ng_call_rt(c, "main", 0); + x_push_rax(b); + ng_call_rt(c, "sys_exit", 1); + return x_byte(b, 204); // int3: sys_exit does not return +} + fn ng_is_declaration(c: i64, n: i64) -> bool { let k = nk(c, n); return k == K_FN || k == K_MACRODEF; @@ -5900,6 +5988,11 @@ fn ng_entry(c: i64) -> i64 { // image for the loaded, checked program, or report undefined functions // and return 0. elf_write_file adds the headers. fn generate_native(c: i64) -> i64 { + return generate_native_for(c, 0); +} + +// generate_native for target OS `target` (NG_TARGET). +fn generate_native_for(c: i64, target: i64) -> i64 { let state = vfill(vnew_cap(NG_SLOTS), NG_SLOTS, 0); vset(c, CX_GEN, state); ng_set(c, NG_CODE, vnew_cap(1048576)); @@ -5940,7 +6033,15 @@ fn generate_native(c: i64) -> i64 { ng_set(c, NG_PASS, 2); ng_set(c, NG_SYMS, vnew()); ng_set(c, NG_CODELEN, 0); - ng_entry(c); + ng_set(c, NG_TARGET, target); + ng_set(c, NG_IMPORTS, vnew()); + ng_set(c, NG_IMPFIX, vnew()); + ng_set(c, NG_EXTERNS, ng_extern_table(c)); + if target == 1 { + ng_entry_win(c); + } else { + ng_entry(c); + } ng_symbol(c, "_start", 0); let items = cx(c, CX_ITEMS); let files = cx(c, CX_ITEMFILE); @@ -6013,8 +6114,12 @@ fn generate_native(c: i64) -> i64 { } return 0; } - // data after the code, 8-aligned - while vlen(b) % 8 != 0 { + // data after the code, 8-aligned (page-aligned for a PE .data section) + let mut align: i64 = 8; + if target == 1 { + align = 4096; + } + while vlen(b) % align != 0 { x_byte(b, 204); } let base = vlen(b); diff --git a/compiler/src/parser.trk b/compiler/src/parser.trk index 7520e07..2be5ec1 100644 --- a/compiler/src/parser.trk +++ b/compiler/src/parser.trk @@ -624,6 +624,9 @@ fn parse_statement_inner(c: i64) -> i64 { if k == TK_ATMACRO { return parse_macro_def(c); } if k == TK_ENUM { return parse_enum(c); } if k == TK_UNION { return parse_union(c); } + if k == TK_IDENT && p_kind_at(c, 1) == TK_STR && text_eq(name_text(c, p_value(c)), "extern") { + return parse_extern(c); + } let expr = parse_expr(c); if p_accept(c, TK_EQ) { return node2(c, K_ASSIGN, expr, parse_expr(c), npos(c, expr)); @@ -703,6 +706,24 @@ fn parse_fn(c: i64) -> i64 { return node_new(c, K_FN, name, generics, params, ret, body, pos); } +// `extern "lib" fn name(params) -> T;`: a function in a system library +// (docs/native.md, "Imported functions"). `extern` is a contextual word, +// not a keyword: only `extern` followed by a string starts one. +fn parse_extern(c: i64) -> i64 { + let pos = p_pos(c); + p_advance(c); + let lib = p_value(c); + p_advance(c); + p_expect(c, TK_FN); + let name = p_ident(c); + let params = parse_params(c); + let mut ret: i64 = -1; + if p_accept(c, TK_ARROW) { + ret = parse_type(c); + } + return node_new(c, K_EXTERN, name, lib, params, ret, -1, pos); +} + fn parse_macro_def(c: i64) -> i64 { let pos = p_pos(c); p_expect(c, TK_ATMACRO); diff --git a/compiler/src/pe.trk b/compiler/src/pe.trk new file mode 100644 index 0000000..093c086 --- /dev/null +++ b/compiler/src/pe.trk @@ -0,0 +1,336 @@ +// pe.trk — PE32+ console executable writer (x86_64-windows). +// +// Layout (SectionAlignment 0x1000, FileAlignment 0x200, ImageBase +// 0x140000000, no relocations: the image loads at its base): +// +// headers DOS header + stub, "PE\0\0", COFF header, PE32+ optional +// header (16 data directories), three section headers +// .text the code (RVA 0x1000, entry at its first byte) +// .data the data ngen appends after the code; ngen page-aligns the +// code for this target, so rip-relative references made by +// generate_native stay correct with .data at 0x1000 + code +// .idata import descriptors, lookup tables, the IAT, hint/name +// entries and library names, one descriptor per library +// +// The import table comes from ngen (native_imports: (library, symbol) +// pairs; native_import_fixups: (code position, import id)): each fixup +// is the disp32 of a `call [rip + disp32]` and gets the distance to its +// IAT slot. Files are written with the same open64/write/fchmod/close as +// elf.trk. + +import "base"; +import "x64"; + +const PE_BASE = 5368709120; // 0x140000000 +const PE_SALIGN = 4096; +const PE_FALIGN = 512; +const PE_HEADERS = 512; +const PE_TEXT_RVA = 4096; + +fn pe_u16(b: i64, v: i64) -> i64 { + x_byte(b, v); + return x_byte(b, v >> 8); +} + +fn pe_up(n: i64, a: i64) -> i64 { return (n + a - 1) / a * a; } + +fn pe_pad(b: i64, size: i64) -> i64 { + while vlen(b) < size { + vpush(b, 0); + } + return 0; +} + +fn pe_name8(b: i64, name: i64) -> i64 { + let bytes = text_bytes(name); + let mut i: i64 = 0; + while i < 8 { + if i < vlen(bytes) { + vpush(b, vget(bytes, i)); + } else { + vpush(b, 0); + } + i = i + 1; + } + return 0; +} + +fn pe_section(b: i64, name: i64, vsize: i64, rva: i64, rawsize: i64, rawptr: i64, flags: i64) -> i64 { + pe_name8(b, name); + x_u32(b, vsize); + x_u32(b, rva); + x_u32(b, rawsize); + x_u32(b, rawptr); + x_u32(b, 0); + x_u32(b, 0); + pe_u16(b, 0); + pe_u16(b, 0); + return x_u32(b, flags); +} + +fn pe_cstr(b: i64, s: i64) -> i64 { + let bytes = text_bytes(s); + let mut i: i64 = 0; + while i < vlen(bytes) { + vpush(b, vget(bytes, i)); + i = i + 1; + } + return vpush(b, 0); +} + +// The .idata contents at `rva`; fills `slots` (import id -> IAT slot RVA) +// and `dirs` with [import dir RVA, size, IAT RVA, size]. +fn pe_idata(imports: i64, rva: i64, slots: i64, dirs: i64) -> i64 { + let n = vlen(imports) / 2; + let libs = vnew(); + let mut i: i64 = 0; + while i < n { + let lib = vget(imports, 2 * i); + let mut seen = false; + let mut j: i64 = 0; + while j < vlen(libs) { + if text_eq(vget(libs, j), lib) { + seen = true; + } + j = j + 1; + } + if !seen { + vpush(libs, lib); + } + i = i + 1; + } + let nlib = vlen(libs); + // order: imports grouped by library, each group 0-terminated + let order = vnew(); + let mut l: i64 = 0; + while l < nlib { + let mut k: i64 = 0; + while k < n { + if text_eq(vget(imports, 2 * k), vget(libs, l)) { + vpush(order, k); + } + k = k + 1; + } + vpush(order, -1); + l = l + 1; + } + let desc_size = 20 * (nlib + 1); + let ilt = rva + desc_size; + let iat = ilt + 8 * vlen(order); + let names_at = iat + 8 * vlen(order); + // hint/name entries, then library names + let names = vnew(); + let hint = vfill(vnew(), n, 0); + let mut q: i64 = 0; + while q < n { + vset(hint, q, names_at + vlen(names)); + pe_u16(names, 0); + pe_cstr(names, vget(imports, 2 * q + 1)); + if vlen(names) % 2 != 0 { + vpush(names, 0); + } + q = q + 1; + } + let libname = vnew(); + let mut m: i64 = 0; + while m < nlib { + vpush(libname, names_at + vlen(names)); + pe_cstr(names, vget(libs, m)); + m = m + 1; + } + let b = vnew(); + // descriptors + let mut pos: i64 = 0; + let mut d: i64 = 0; + while d < nlib { + x_u32(b, ilt + 8 * pos); + x_u32(b, 0); + x_u32(b, 0); + x_u32(b, vget(libname, d)); + x_u32(b, iat + 8 * pos); + while vget(order, pos) >= 0 { + pos = pos + 1; + } + pos = pos + 1; + d = d + 1; + } + let mut z: i64 = 0; + while z < 20 { + vpush(b, 0); + z = z + 1; + } + // lookup table, then the IAT (same contents until the loader binds it) + let mut pass: i64 = 0; + while pass < 2 { + let mut o: i64 = 0; + while o < vlen(order) { + let k = vget(order, o); + if k < 0 { + x_u64(b, 0); + } else { + x_u64(b, vget(hint, k)); + if pass == 1 { + vset(slots, k, iat + 8 * o); + } + } + o = o + 1; + } + pass = pass + 1; + } + let mut w: i64 = 0; + while w < vlen(names) { + vpush(b, vget(names, w)); + w = w + 1; + } + vset(dirs, 0, rva); + vset(dirs, 1, desc_size); + vset(dirs, 2, iat); + vset(dirs, 3, 8 * vlen(order)); + return b; +} + +// The whole PE image of code+data `body` (the first `code` bytes code, +// page-aligned) calling `imports` from the sites `fixups`. +fn pe_image(body: i64, code: i64, imports: i64, fixups: i64) -> i64 { + let mut dsize = vlen(body) - code; + if dsize < 8 { + dsize = 8; + } + let data_rva = PE_TEXT_RVA + pe_up(code, PE_SALIGN); + let idata_rva = data_rva + pe_up(dsize, PE_SALIGN); + let slots = vfill(vnew(), vlen(imports) / 2, 0); + let dirs = vfill(vnew(), 4, 0); + let idata = pe_idata(imports, idata_rva, slots, dirs); + let image_size = idata_rva + pe_up(vlen(idata), PE_SALIGN); + // bind the call sites to their IAT slots + let mut f: i64 = 0; + while f < vlen(fixups) { + let at = vget(fixups, f); + x_patch32(body, at, vget(slots, vget(fixups, f + 1)) - (PE_TEXT_RVA + at + 4)); + f = f + 2; + } + let text_raw = pe_up(code, PE_FALIGN); + let data_raw = pe_up(dsize, PE_FALIGN); + let idata_raw = pe_up(vlen(idata), PE_FALIGN); + let b = vnew_cap(PE_HEADERS + text_raw + data_raw + idata_raw); + // DOS header: "MZ", e_lfanew = 0x80; a stub that prints and exits + pe_u16(b, 23117); + pe_pad(b, 60); + x_u32(b, 128); + let stub = vnew(); + x_bytes3(stub, 14, 31, 186); // push cs; pop ds; mov dx, 0x000e + x_bytes3(stub, 14, 0, 180); // ...; mov ah, 9 + x_bytes3(stub, 9, 205, 33); // int 21h + x_bytes3(stub, 184, 1, 76); // mov ax, 0x4c01 + x_bytes2(stub, 205, 33); // int 21h + pe_cstr(stub, "This program needs Windows.$"); + let mut s: i64 = 0; + while s < vlen(stub) { + vpush(b, vget(stub, s)); + s = s + 1; + } + pe_pad(b, 128); + // PE signature and COFF header + x_u32(b, 17744); // "PE\0\0" + pe_u16(b, 34404); // IMAGE_FILE_MACHINE_AMD64 + pe_u16(b, 3); // sections + x_u32(b, 0); + x_u32(b, 0); + x_u32(b, 0); + pe_u16(b, 240); // optional header size + pe_u16(b, 35); // RELOCS_STRIPPED | EXECUTABLE | LARGE_ADDRESS_AWARE + // PE32+ optional header + pe_u16(b, 523); // 0x20b + x_byte(b, 1); + x_byte(b, 0); + x_u32(b, text_raw); // SizeOfCode + x_u32(b, data_raw + idata_raw); + x_u32(b, 0); + x_u32(b, PE_TEXT_RVA); // entry point + x_u32(b, PE_TEXT_RVA); // BaseOfCode + x_u64(b, PE_BASE); + x_u32(b, PE_SALIGN); + x_u32(b, PE_FALIGN); + pe_u16(b, 6); + pe_u16(b, 0); // OS version + pe_u16(b, 0); + pe_u16(b, 0); // image version + pe_u16(b, 6); + pe_u16(b, 0); // subsystem version + x_u32(b, 0); + x_u32(b, image_size); + x_u32(b, PE_HEADERS); + x_u32(b, 0); // checksum + pe_u16(b, 3); // IMAGE_SUBSYSTEM_WINDOWS_CUI + pe_u16(b, 33024); // NX_COMPAT | TERMINAL_SERVER_AWARE + x_u64(b, 268435456); // stack reserve 256 MiB (trackc recurses deeply) + x_u64(b, 16777216); // stack commit 16 MiB (frames skip guard pages) + x_u64(b, 1048576); + x_u64(b, 4096); + x_u32(b, 0); + x_u32(b, 16); + let mut dd: i64 = 0; + while dd < 16 { + if dd == 1 { + x_u32(b, vget(dirs, 0)); + x_u32(b, vget(dirs, 1)); + } else if dd == 12 { + x_u32(b, vget(dirs, 2)); + x_u32(b, vget(dirs, 3)); + } else { + x_u64(b, 0); + } + dd = dd + 1; + } + pe_section(b, ".text", code, PE_TEXT_RVA, text_raw, PE_HEADERS, 1610612768); + pe_section(b, ".data", dsize, data_rva, data_raw, PE_HEADERS + text_raw, 3221225536); + pe_section(b, ".idata", vlen(idata), idata_rva, idata_raw, PE_HEADERS + text_raw + data_raw, 3221225536); + pe_pad(b, PE_HEADERS); + let mut i: i64 = 0; + while i < code { + vpush(b, vget(body, i)); + i = i + 1; + } + pe_pad(b, PE_HEADERS + text_raw); + while i < vlen(body) { + vpush(b, vget(body, i)); + i = i + 1; + } + pe_pad(b, PE_HEADERS + text_raw + data_raw); + let mut k: i64 = 0; + while k < vlen(idata) { + vpush(b, vget(idata, k)); + k = k + 1; + } + pe_pad(b, PE_HEADERS + text_raw + data_raw + idata_raw); + return b; +} + +// Write the PE image to `path` (mode 0755 where that means anything). +// Returns 0 on success. +fn pe_write_file(path: i64, body: i64, code: i64, imports: i64, fixups: i64) -> i64 { + let img = pe_image(body, code, imports, fixups); + let n = vlen(img); + let buf: i64 = alloc(n + 8); + let mut i: i64 = 0; + while i < n { + memset(buf + i, vget(img, i), 1); + i = i + 1; + } + let fd: i64 = open64(path, 577, 493); + if fd < 0 { + return 1; + } + fchmod(fd, 493); + let mut done: i64 = 0; + while done < n { + let w: i64 = write(fd, buf + done, n - done); + if w <= 0 { + close(fd); + return 1; + } + done = done + w; + } + close(fd); + return 0; +} diff --git a/compiler/src/runtime_trk.trk b/compiler/src/runtime_trk.trk index df7dc07..b6807bb 100644 --- a/compiler/src/runtime_trk.trk +++ b/compiler/src/runtime_trk.trk @@ -3,15 +3,16 @@ import "base"; -fn rt_module_count() -> i64 { return 6; } +fn rt_module_count() -> i64 { return 7; } fn rt_module_name(i: i64) -> i64 { if i == 0 { return "rt/mem.trk"; } if i == 1 { return "rt/io.trk"; } if i == 2 { return "rt/str.trk"; } if i == 3 { return "rt/vec.trk"; } - if i == 4 { return "rt/sys.trk"; } - if i == 5 { return "rt/libc.trk"; } + if i == 4 { return "rt/os/linux.trk"; } + if i == 5 { return "rt/os/windows.trk"; } + if i == 6 { return "rt/libc.trk"; } return ""; } @@ -1697,8 +1698,12 @@ fn rt_module_source_3(b: i64) -> i64 { } fn rt_module_source_4(b: i64) -> i64 { - sb_line(b, "// rt/sys.trk — Track runtime: arguments, environment, processes, clock,"); - sb_line(b, "// files, sockets. All through Linux x86-64 system calls."); + sb_line(b, "// rt/os/linux.trk — Track runtime OS layer for Linux: arguments,"); + sb_line(b, "// environment, processes, clock, files, sockets, all through Linux x86-64"); + sb_line(b, "// system calls. Every OS layer (rt/os/.trk) defines the same OS"); + sb_line(b, "// interface (docs/native.md, \"The OS layer\"); trackc loads the one for"); + sb_line(b, "// the target. On Linux the portable modules' own `syscall6` calls go"); + sb_line(b, "// straight to the kernel; other OS layers also define `os_syscall`."); sb_line(b, ""); sb_line(b, "// ---------------------------------------------------------------- process"); sb_line(b, ""); @@ -2136,6 +2141,710 @@ fn rt_module_source_4(b: i64) -> i64 { } fn rt_module_source_5(b: i64) -> i64 { + sb_line(b, "// rt/os/windows.trk — Track runtime OS layer for Windows (kernel32)."); + sb_line(b, "//"); + sb_line(b, "// Implements the OS interface (docs/native.md, \"The OS layer\") with"); + sb_line(b, "// kernel32 functions called through the import table (`extern`):"); + sb_line(b, "//"); + sb_line(b, "// os_start process entry: argc/argv from GetCommandLineW, then rt_start"); + sb_line(b, "// os_syscall the kernel calls the portable modules (mem, io, libc)"); + sb_line(b, "// make through `syscall6`, by Linux number: read, write,"); + sb_line(b, "// open, close, stat, lseek, mmap, munmap, mremap,"); + sb_line(b, "// madvise, pipe, access, getpid, kill, unlink,"); + sb_line(b, "// clock_gettime, exit_group, fchmod. trackc lowers"); + sb_line(b, "// `syscall6(nr, a..f)` to `os_syscall(nr, a..e)` on"); + sb_line(b, "// every target but Linux."); + sb_line(b, "// os_args_count, os_arg, env_get, env_exists, sys_exec, process_spawn,"); + sb_line(b, "// clock_ms, file_open, file_close, file_read_all, file_write,"); + sb_line(b, "// file_exists, file_remove, file_size, dir_exists, file_copy,"); + sb_line(b, "// track_file_read, track_file_write_all, net_socket_* (not yet: -1)"); + sb_line(b, "//"); + sb_line(b, "// A file descriptor is a HANDLE; 0, 1 and 2 stand for the standard"); + sb_line(b, "// handles. Paths and arguments are UTF-8 in Track and UTF-16 for Windows."); + sb_line(b, ""); + sb_line(b, "extern \"kernel32.dll\" fn GetStdHandle(which: i64) -> i64;"); + sb_line(b, "extern \"kernel32.dll\" fn WriteFile(h: i64, buf: i64, n: i64, done: i64, ov: i64) -> i32;"); + sb_line(b, "extern \"kernel32.dll\" fn ReadFile(h: i64, buf: i64, n: i64, done: i64, ov: i64) -> i32;"); + sb_line(b, "extern \"kernel32.dll\" fn CreateFileW(path: i64, access: i64, share: i64, sec: i64, disp: i64, flags: i64, tmpl: i64) -> i64;"); + sb_line(b, "extern \"kernel32.dll\" fn CloseHandle(h: i64) -> i32;"); + sb_line(b, "extern \"kernel32.dll\" fn ExitProcess(code: i64) -> i64;"); + sb_line(b, "extern \"kernel32.dll\" fn VirtualAlloc(addr: i64, size: i64, kind: i64, prot: i64) -> i64;"); + sb_line(b, "extern \"kernel32.dll\" fn VirtualFree(addr: i64, size: i64, kind: i64) -> i32;"); + sb_line(b, "extern \"kernel32.dll\" fn GetCommandLineW() -> i64;"); + sb_line(b, "extern \"kernel32.dll\" fn GetEnvironmentVariableW(name: i64, buf: i64, n: i64) -> u32;"); + sb_line(b, "extern \"kernel32.dll\" fn GetFileAttributesW(path: i64) -> u32;"); + sb_line(b, "extern \"kernel32.dll\" fn GetFileAttributesExW(path: i64, level: i64, info: i64) -> i32;"); + sb_line(b, "extern \"kernel32.dll\" fn DeleteFileW(path: i64) -> i32;"); + sb_line(b, "extern \"kernel32.dll\" fn SetFileInformationByHandle(h: i64, class: i64, info: i64, size: i64) -> i32;"); + sb_line(b, "extern \"kernel32.dll\" fn SetFilePointerEx(h: i64, dist: i64, newpos: i64, how: i64) -> i32;"); + sb_line(b, "extern \"kernel32.dll\" fn QueryPerformanceCounter(out: i64) -> i32;"); + sb_line(b, "extern \"kernel32.dll\" fn QueryPerformanceFrequency(out: i64) -> i32;"); + sb_line(b, "extern \"kernel32.dll\" fn GetSystemTimePreciseAsFileTime(out: i64) -> i64;"); + sb_line(b, "extern \"kernel32.dll\" fn CreatePipe(rd: i64, wr: i64, sec: i64, size: i64) -> i32;"); + sb_line(b, "extern \"kernel32.dll\" fn GetCurrentProcessId() -> u32;"); + sb_line(b, "extern \"kernel32.dll\" fn GetLastError() -> u32;"); + sb_line(b, "extern \"kernel32.dll\" fn CreateProcessW(app: i64, cmd: i64, psec: i64, tsec: i64, inherit: i64, flags: i64, env: i64, dir: i64, si: i64, pi: i64) -> i32;"); + sb_line(b, "extern \"kernel32.dll\" fn WaitForSingleObject(h: i64, ms: i64) -> u32;"); + sb_line(b, "extern \"kernel32.dll\" fn GetExitCodeProcess(h: i64, code: i64) -> i32;"); + sb_line(b, ""); + sb_line(b, "const WS_SCRATCH = 6144; // 64 bytes of out-parameters in the state page"); + sb_line(b, "const WS_STAT = 6208; // WIN32_FILE_ATTRIBUTE_DATA (36 bytes)"); + sb_line(b, ""); + sb_line(b, "fn ws(off: i64) -> i64 { return RT_BASE + WS_SCRATCH + off; }"); + sb_line(b, ""); + sb_line(b, "// ------------------------------------------------------------- UTF-16"); + sb_line(b, ""); + sb_line(b, "// A UTF-16 copy (NUL-terminated, heap) of the UTF-8 text `s`."); + sb_line(b, "fn win_wide(s: i64) -> i64 {"); + sb_line(b, " let n = rt_strlen(s);"); + sb_line(b, " let w = rt_malloc(4 * n + 4);"); + sb_line(b, " let mut i: i64 = 0;"); + sb_line(b, " let mut o: i64 = 0;"); + sb_line(b, " while i < n {"); + sb_line(b, " let b0 = load8(s + i);"); + sb_line(b, " let mut cp = b0;"); + sb_line(b, " let mut k: i64 = 1;"); + sb_line(b, " if b0 >= 240 && i + 3 < n + 1 {"); + sb_line(b, " cp = ((b0 & 7) << 18) | ((load8(s + i + 1) & 63) << 12) | ((load8(s + i + 2) & 63) << 6) | (load8(s + i + 3) & 63);"); + sb_line(b, " k = 4;"); + sb_line(b, " } else if b0 >= 224 {"); + sb_line(b, " cp = ((b0 & 15) << 12) | ((load8(s + i + 1) & 63) << 6) | (load8(s + i + 2) & 63);"); + sb_line(b, " k = 3;"); + sb_line(b, " } else if b0 >= 192 {"); + sb_line(b, " cp = ((b0 & 31) << 6) | (load8(s + i + 1) & 63);"); + sb_line(b, " k = 2;"); + sb_line(b, " }"); + sb_line(b, " if cp >= 65536 {"); + sb_line(b, " let v = cp - 65536;"); + sb_line(b, " win_put16(w + o, 55296 + (v >> 10));"); + sb_line(b, " win_put16(w + o + 2, 56320 + (v & 1023));"); + sb_line(b, " o = o + 4;"); + sb_line(b, " } else {"); + sb_line(b, " win_put16(w + o, cp);"); + sb_line(b, " o = o + 2;"); + sb_line(b, " }"); + sb_line(b, " i = i + k;"); + sb_line(b, " }"); + sb_line(b, " win_put16(w + o, 0);"); + sb_line(b, " return w;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn win_put16(p: i64, v: i64) -> i64 {"); + sb_line(b, " store8(p, v & 255);"); + sb_line(b, " return store8(p + 1, (v >> 8) & 255);"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn win_get16(p: i64) -> i64 { return load8(p) | (load8(p + 1) << 8); }"); + sb_line(b, ""); + sb_line(b, "// Append the UTF-8 encoding of `cp` at `out`; returns the bytes written."); + sb_line(b, "fn win_utf8(out: i64, cp: i64) -> i64 {"); + sb_line(b, " if cp < 128 {"); + sb_line(b, " store8(out, cp);"); + sb_line(b, " return 1;"); + sb_line(b, " }"); + sb_line(b, " if cp < 2048 {"); + sb_line(b, " store8(out, 192 | (cp >> 6));"); + sb_line(b, " store8(out + 1, 128 | (cp & 63));"); + sb_line(b, " return 2;"); + sb_line(b, " }"); + sb_line(b, " if cp < 65536 {"); + sb_line(b, " store8(out, 224 | (cp >> 12));"); + sb_line(b, " store8(out + 1, 128 | ((cp >> 6) & 63));"); + sb_line(b, " store8(out + 2, 128 | (cp & 63));"); + sb_line(b, " return 3;"); + sb_line(b, " }"); + sb_line(b, " store8(out, 240 | (cp >> 18));"); + sb_line(b, " store8(out + 1, 128 | ((cp >> 12) & 63));"); + sb_line(b, " store8(out + 2, 128 | ((cp >> 6) & 63));"); + sb_line(b, " store8(out + 3, 128 | (cp & 63));"); + sb_line(b, " return 4;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "// Code point of the UTF-16 text at `w` (a surrogate pair or one unit)."); + sb_line(b, "fn win_cp(w: i64) -> i64 {"); + sb_line(b, " let u = win_get16(w);"); + sb_line(b, " if u >= 55296 && u < 56320 {"); + sb_line(b, " let v = win_get16(w + 2);"); + sb_line(b, " if v >= 56320 && v < 57344 {"); + sb_line(b, " return 65536 + ((u - 55296) << 10) + (v - 56320);"); + sb_line(b, " }"); + sb_line(b, " }"); + sb_line(b, " return u;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "// Bytes of UTF-16 that code point `cp` took."); + sb_line(b, "fn win_cplen(cp: i64) -> i64 {"); + sb_line(b, " if cp >= 65536 {"); + sb_line(b, " return 4;"); + sb_line(b, " }"); + sb_line(b, " return 2;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "// A UTF-8 copy (heap) of `n` UTF-16 units at `w`."); + sb_line(b, "fn win_narrow(w: i64, n: i64) -> i64 {"); + sb_line(b, " let out = rt_malloc(3 * n + 1);"); + sb_line(b, " let mut i: i64 = 0;"); + sb_line(b, " let mut o: i64 = 0;"); + sb_line(b, " while i < 2 * n {"); + sb_line(b, " let cp = win_cp(w + i);"); + sb_line(b, " i = i + win_cplen(cp);"); + sb_line(b, " o = o + win_utf8(out + o, cp);"); + sb_line(b, " }"); + sb_line(b, " store8(out + o, 0);"); + sb_line(b, " return out;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "// ------------------------------------------------------------- process"); + sb_line(b, ""); + sb_line(b, "fn win_space(u: i64) -> bool { return u == 32 || u == 9; }"); + sb_line(b, ""); + sb_line(b, "// The process entry (trackc's Windows `_start` calls it): split"); + sb_line(b, "// GetCommandLineW the way CommandLineToArgvW does, as UTF-8, into an"); + sb_line(b, "// argv array followed by an empty envp, then rt_start."); + sb_line(b, "fn os_start() -> i64 {"); + sb_line(b, " let cl = GetCommandLineW();"); + sb_line(b, " let mut wl: i64 = 0;"); + sb_line(b, " while win_get16(cl + 2 * wl) != 0 {"); + sb_line(b, " wl = wl + 1;"); + sb_line(b, " }"); + sb_line(b, " let size = 8 * (wl + 4) + 4 * wl + 64;"); + sb_line(b, " let argv = VirtualAlloc(0, size, 12288, 4);"); + sb_line(b, " let mut out = argv + 8 * (wl + 4);"); + sb_line(b, " let mut argc: i64 = 0;"); + sb_line(b, " let mut i: i64 = 0;"); + sb_line(b, " while true {"); + sb_line(b, " while win_space(win_get16(cl + 2 * i)) {"); + sb_line(b, " i = i + 1;"); + sb_line(b, " }"); + sb_line(b, " if win_get16(cl + 2 * i) == 0 {"); + sb_line(b, " store64(argv + 8 * argc, 0);"); + sb_line(b, " store64(argv + 8 * argc + 8, 0);"); + sb_line(b, " return rt_start(argc, argv);"); + sb_line(b, " }"); + sb_line(b, " store64(argv + 8 * argc, out);"); + sb_line(b, " argc = argc + 1;"); + sb_line(b, " let mut quoted = false;"); + sb_line(b, " let mut going = true;"); + sb_line(b, " while going {"); + sb_line(b, " let u = win_get16(cl + 2 * i);"); + sb_line(b, " if u == 0 || (!quoted && win_space(u)) {"); + sb_line(b, " going = false;"); + sb_line(b, " } else if u == 92 {"); + sb_line(b, " let mut nb: i64 = 0;"); + sb_line(b, " while win_get16(cl + 2 * i) == 92 {"); + sb_line(b, " nb = nb + 1;"); + sb_line(b, " i = i + 1;"); + sb_line(b, " }"); + sb_line(b, " if win_get16(cl + 2 * i) == 34 {"); + sb_line(b, " let mut h: i64 = 0;"); + sb_line(b, " while h < nb / 2 {"); + sb_line(b, " store8(out, 92);"); + sb_line(b, " out = out + 1;"); + sb_line(b, " h = h + 1;"); + sb_line(b, " }"); + sb_line(b, " if nb % 2 == 1 {"); + sb_line(b, " store8(out, 34);"); + sb_line(b, " out = out + 1;"); + sb_line(b, " i = i + 1;"); + sb_line(b, " }"); + sb_line(b, " } else {"); + sb_line(b, " let mut h: i64 = 0;"); + sb_line(b, " while h < nb {"); + sb_line(b, " store8(out, 92);"); + sb_line(b, " out = out + 1;"); + sb_line(b, " h = h + 1;"); + sb_line(b, " }"); + sb_line(b, " }"); + sb_line(b, " } else if u == 34 {"); + sb_line(b, " if quoted && win_get16(cl + 2 * i + 2) == 34 {"); + sb_line(b, " store8(out, 34);"); + sb_line(b, " out = out + 1;"); + sb_line(b, " i = i + 1;"); + sb_line(b, " } else {"); + sb_line(b, " quoted = !quoted;"); + sb_line(b, " }"); + sb_line(b, " i = i + 1;"); + sb_line(b, " } else {"); + sb_line(b, " let cp = win_cp(cl + 2 * i);"); + sb_line(b, " i = i + win_cplen(cp) / 2;"); + sb_line(b, " out = out + win_utf8(out, cp);"); + sb_line(b, " }"); + sb_line(b, " }"); + sb_line(b, " store8(out, 0);"); + sb_line(b, " out = out + 1;"); + sb_line(b, " }"); + sb_line(b, " return 0;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn os_args_count() -> i64 { return rs(RS_ARGC); }"); + sb_line(b, ""); + sb_line(b, "fn os_arg(idx: i64) -> i64 {"); + sb_line(b, " if idx >= 0 && idx < rs(RS_ARGC) {"); + sb_line(b, " return rt_dup(load64(rs(RS_ARGV) + 8 * idx));"); + sb_line(b, " }"); + sb_line(b, " return rt_dup_n(\"\", 0);"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "// Value of environment variable `key` (heap UTF-8), or 0 when unset."); + sb_line(b, "fn rt_getenv(key: i64) -> i64 {"); + sb_line(b, " let wk = win_wide(key);"); + sb_line(b, " let mut cap: i64 = 256;"); + sb_line(b, " let mut buf = rt_malloc(2 * cap);"); + sb_line(b, " let mut n = GetEnvironmentVariableW(wk, buf, cap);"); + sb_line(b, " if n > cap {"); + sb_line(b, " cap = n;"); + sb_line(b, " rt_free(buf);"); + sb_line(b, " buf = rt_malloc(2 * cap);"); + sb_line(b, " n = GetEnvironmentVariableW(wk, buf, cap);"); + sb_line(b, " }"); + sb_line(b, " rt_free(wk);"); + sb_line(b, " if n == 0 && GetLastError() == 203 {"); + sb_line(b, " rt_free(buf);"); + sb_line(b, " return 0;"); + sb_line(b, " }"); + sb_line(b, " let v = win_narrow(buf, n);"); + sb_line(b, " rt_free(buf);"); + sb_line(b, " return v;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn env_get(key: i64) -> i64 {"); + sb_line(b, " if key == 0 {"); + sb_line(b, " return rt_dup_n(\"\", 0);"); + sb_line(b, " }"); + sb_line(b, " let v = rt_getenv(key);"); + sb_line(b, " if v == 0 {"); + sb_line(b, " return rt_dup_n(\"\", 0);"); + sb_line(b, " }"); + sb_line(b, " return v;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn env_exists(key: i64) -> i64 {"); + sb_line(b, " if key != 0 {"); + sb_line(b, " let v = rt_getenv(key);"); + sb_line(b, " if v != 0 {"); + sb_line(b, " rt_free(v);"); + sb_line(b, " return 1;"); + sb_line(b, " }"); + sb_line(b, " }"); + sb_line(b, " return 0;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "// system(3) with cmd.exe: `cmd.exe /c cmd`; the exit code, -1 when the"); + sb_line(b, "// process could not start."); + sb_line(b, "fn sys_exec(cmd: i64) -> i64 {"); + sb_line(b, " if cmd == 0 {"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " rt_flush();"); + sb_line(b, " let line = str_concat(\"cmd.exe /c \", cmd);"); + sb_line(b, " let wl = win_wide(line);"); + sb_line(b, " let si = rt_malloc(104);"); + sb_line(b, " rt_zero(si, 104);"); + sb_line(b, " store64(si, 104);"); + sb_line(b, " let pi = rt_malloc(24);"); + sb_line(b, " rt_zero(pi, 24);"); + sb_line(b, " let ok = CreateProcessW(0, wl, 0, 0, 1, 0, 0, 0, si, pi);"); + sb_line(b, " rt_free(wl);"); + sb_line(b, " if ok == 0 {"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " let hp = load64(pi);"); + sb_line(b, " WaitForSingleObject(hp, 4294967295);"); + sb_line(b, " store64(ws(0), 0);"); + sb_line(b, " GetExitCodeProcess(hp, ws(0));"); + sb_line(b, " CloseHandle(hp);"); + sb_line(b, " CloseHandle(load64(pi + 8));"); + sb_line(b, " return load64(ws(0)) & 4294967295;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn process_spawn(cmd: i64) -> i64 { return sys_exec(cmd); }"); + sb_line(b, ""); + sb_line(b, "fn clock_ms() -> i64 {"); + sb_line(b, " QueryPerformanceFrequency(ws(0));"); + sb_line(b, " QueryPerformanceCounter(ws(8));"); + sb_line(b, " let f = load64(ws(0));"); + sb_line(b, " let t = load64(ws(8));"); + sb_line(b, " return t / f * 1000 + (t % f) * 1000 / f;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "// ---------------------------------------------------------- kernel calls"); + sb_line(b, ""); + sb_line(b, "fn win_handle(fd: i64) -> i64 {"); + sb_line(b, " if fd >= 0 && fd <= 2 {"); + sb_line(b, " return GetStdHandle(-10 - fd);"); + sb_line(b, " }"); + sb_line(b, " return fd;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "// open(2) flags -> CreateFileW; a HANDLE or -2 (ENOENT)."); + sb_line(b, "fn win_open(path: i64, flags: i64) -> i64 {"); + sb_line(b, " let mode = flags & 3;"); + sb_line(b, " let mut access: i64 = 2147483648; // GENERIC_READ"); + sb_line(b, " if mode == 1 {"); + sb_line(b, " access = 1073741824; // GENERIC_WRITE"); + sb_line(b, " } else if mode == 2 {"); + sb_line(b, " access = 3221225472;"); + sb_line(b, " }"); + sb_line(b, " let mut disp: i64 = 3; // OPEN_EXISTING"); + sb_line(b, " if (flags & 64) != 0 {"); + sb_line(b, " disp = 4; // OPEN_ALWAYS"); + sb_line(b, " if (flags & 512) != 0 {"); + sb_line(b, " disp = 2; // CREATE_ALWAYS"); + sb_line(b, " }"); + sb_line(b, " } else if (flags & 512) != 0 {"); + sb_line(b, " disp = 5; // TRUNCATE_EXISTING"); + sb_line(b, " }"); + sb_line(b, " let wp = win_wide(path);"); + sb_line(b, " let h = CreateFileW(wp, access, 7, 0, disp, 128, 0);"); + sb_line(b, " rt_free(wp);"); + sb_line(b, " if h == -1 || h == 0 {"); + sb_line(b, " return -2;"); + sb_line(b, " }"); + sb_line(b, " if (flags & 1024) != 0 {"); + sb_line(b, " SetFilePointerEx(h, 0, 0, 2);"); + sb_line(b, " }"); + sb_line(b, " return h;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn win_stat(path: i64, st: i64) -> i64 {"); + sb_line(b, " let wp = win_wide(path);"); + sb_line(b, " let ok = GetFileAttributesExW(wp, 0, RT_BASE + WS_STAT);"); + sb_line(b, " rt_free(wp);"); + sb_line(b, " if ok == 0 {"); + sb_line(b, " return -2;"); + sb_line(b, " }"); + sb_line(b, " let attrs = load64(RT_BASE + WS_STAT) & 4294967295;"); + sb_line(b, " let hi = load64(RT_BASE + WS_STAT + 28) & 4294967295;"); + sb_line(b, " let lo = load64(RT_BASE + WS_STAT + 32) & 4294967295;"); + sb_line(b, " rt_zero(st, 144);"); + sb_line(b, " if (attrs & 16) != 0 {"); + sb_line(b, " store64(st + 24, 16877); // S_IFDIR | 0755"); + sb_line(b, " } else {"); + sb_line(b, " store64(st + 24, 33188); // S_IFREG | 0644"); + sb_line(b, " }"); + sb_line(b, " store64(st + 48, (hi << 32) | lo);"); + sb_line(b, " return 0;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "// The `syscall6` calls of the portable runtime modules, by Linux number;"); + sb_line(b, "// -38 (ENOSYS) for the ones Windows has no counterpart for here."); + sb_line(b, "fn os_syscall(nr: i64, a: i64, b: i64, d: i64, e: i64, f: i64) -> i64 {"); + sb_line(b, " if nr == 0 || nr == 1 {"); + sb_line(b, " store64(ws(0), 0);"); + sb_line(b, " let mut ok: i64 = 0;"); + sb_line(b, " if nr == 0 {"); + sb_line(b, " ok = ReadFile(win_handle(a), b, d, ws(0), 0);"); + sb_line(b, " } else {"); + sb_line(b, " ok = WriteFile(win_handle(a), b, d, ws(0), 0);"); + sb_line(b, " }"); + sb_line(b, " if ok == 0 {"); + sb_line(b, " let why = GetLastError();"); + sb_line(b, " if nr == 0 && (why == 109 || why == 38) {"); + sb_line(b, " return 0; // broken pipe / end of file"); + sb_line(b, " }"); + sb_line(b, " if why == 998 {"); + sb_line(b, " return -14; // EFAULT"); + sb_line(b, " }"); + sb_line(b, " return -5;"); + sb_line(b, " }"); + sb_line(b, " return load64(ws(0)) & 4294967295;"); + sb_line(b, " }"); + sb_line(b, " if nr == 2 {"); + sb_line(b, " return win_open(a, b);"); + sb_line(b, " }"); + sb_line(b, " if nr == 3 {"); + sb_line(b, " if a > 2 && CloseHandle(a) == 0 {"); + sb_line(b, " return -9;"); + sb_line(b, " }"); + sb_line(b, " return 0;"); + sb_line(b, " }"); + sb_line(b, " if nr == 4 {"); + sb_line(b, " return win_stat(a, b);"); + sb_line(b, " }"); + sb_line(b, " if nr == 8 {"); + sb_line(b, " if SetFilePointerEx(win_handle(a), b, ws(0), d) == 0 {"); + sb_line(b, " return -29; // ESPIPE"); + sb_line(b, " }"); + sb_line(b, " return load64(ws(0));"); + sb_line(b, " }"); + sb_line(b, " if nr == 9 {"); + sb_line(b, " let p = VirtualAlloc(a, b, 12288, 4); // MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE"); + sb_line(b, " if p == 0 {"); + sb_line(b, " return -12;"); + sb_line(b, " }"); + sb_line(b, " return p;"); + sb_line(b, " }"); + sb_line(b, " if nr == 11 {"); + sb_line(b, " VirtualFree(a, 0, 32768); // MEM_RELEASE"); + sb_line(b, " return 0;"); + sb_line(b, " }"); + sb_line(b, " if nr == 25 {"); + sb_line(b, " let q = VirtualAlloc(0, d, 12288, 4);"); + sb_line(b, " if q == 0 {"); + sb_line(b, " return -12;"); + sb_line(b, " }"); + sb_line(b, " let mut n = b;"); + sb_line(b, " if d < n {"); + sb_line(b, " n = d;"); + sb_line(b, " }"); + sb_line(b, " rt_copy(q, a, n);"); + sb_line(b, " VirtualFree(a, 0, 32768);"); + sb_line(b, " return q;"); + sb_line(b, " }"); + sb_line(b, " if nr == 28 || nr == 91 {"); + sb_line(b, " return 0; // madvise, fchmod"); + sb_line(b, " }"); + sb_line(b, " if nr == 22 {"); + sb_line(b, " if CreatePipe(ws(0), ws(8), 0, 0) == 0 {"); + sb_line(b, " return -24;"); + sb_line(b, " }"); + sb_line(b, " store64(a, (load64(ws(0)) & 4294967295) | (load64(ws(8)) << 32));"); + sb_line(b, " return 0;"); + sb_line(b, " }"); + sb_line(b, " if nr == 21 {"); + sb_line(b, " let wp = win_wide(a);"); + sb_line(b, " let attrs = GetFileAttributesW(wp);"); + sb_line(b, " rt_free(wp);"); + sb_line(b, " if attrs == 4294967295 {"); + sb_line(b, " return -2;"); + sb_line(b, " }"); + sb_line(b, " return 0;"); + sb_line(b, " }"); + sb_line(b, " if nr == 87 {"); + sb_line(b, " // POSIX semantics: the name goes now even while handles are open"); + sb_line(b, " let wp = win_wide(a);"); + sb_line(b, " let mut ok: i64 = 0;"); + sb_line(b, " let h = CreateFileW(wp, 65536, 7, 0, 3, 33554432, 0); // DELETE, OPEN_EXISTING, BACKUP_SEMANTICS"); + sb_line(b, " if h != -1 && h != 0 {"); + sb_line(b, " store64(ws(0), 3); // FILE_DISPOSITION_DELETE | POSIX_SEMANTICS"); + sb_line(b, " ok = SetFileInformationByHandle(h, 21, ws(0), 4);"); + sb_line(b, " CloseHandle(h);"); + sb_line(b, " }"); + sb_line(b, " if ok == 0 {"); + sb_line(b, " ok = DeleteFileW(wp);"); + sb_line(b, " }"); + sb_line(b, " rt_free(wp);"); + sb_line(b, " if ok == 0 {"); + sb_line(b, " return -2;"); + sb_line(b, " }"); + sb_line(b, " return 0;"); + sb_line(b, " }"); + sb_line(b, " if nr == 39 {"); + sb_line(b, " return GetCurrentProcessId();"); + sb_line(b, " }"); + sb_line(b, " if nr == 62 {"); + sb_line(b, " ExitProcess(128 + b); // a signal: die with 128 + signo"); + sb_line(b, " return 0;"); + sb_line(b, " }"); + sb_line(b, " if nr == 228 {"); + sb_line(b, " QueryPerformanceFrequency(ws(0));"); + sb_line(b, " QueryPerformanceCounter(ws(8));"); + sb_line(b, " let fr = load64(ws(0));"); + sb_line(b, " let t = load64(ws(8));"); + sb_line(b, " store64(b, t / fr);"); + sb_line(b, " store64(b + 8, (t % fr) * 1000000000 / fr);"); + sb_line(b, " return 0;"); + sb_line(b, " }"); + sb_line(b, " if nr == 231 || nr == 60 {"); + sb_line(b, " ExitProcess(a);"); + sb_line(b, " return 0;"); + sb_line(b, " }"); + sb_line(b, " return -38;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "// ------------------------------------------------------------------ files"); + sb_line(b, "//"); + sb_line(b, "// A file handle is a runtime record [HANDLE]; 0 when the open failed."); + sb_line(b, ""); + sb_line(b, "const O_RDONLY = 0;"); + sb_line(b, "const O_WRONLY_CREAT_TRUNC = 577;"); + sb_line(b, "const O_WRONLY_CREAT_APPEND = 1089;"); + sb_line(b, "const O_RDWR = 2;"); + sb_line(b, ""); + sb_line(b, "fn rt_open_flags(mode: i64) -> i64 {"); + sb_line(b, " let m = load8(mode);"); + sb_line(b, " let plus = rt_find(mode, \"+\") >= 0;"); + sb_line(b, " if m == 114 {"); + sb_line(b, " if plus {"); + sb_line(b, " return O_RDWR;"); + sb_line(b, " }"); + sb_line(b, " return O_RDONLY;"); + sb_line(b, " }"); + sb_line(b, " if m == 119 {"); + sb_line(b, " if plus {"); + sb_line(b, " return 578;"); + sb_line(b, " }"); + sb_line(b, " return O_WRONLY_CREAT_TRUNC;"); + sb_line(b, " }"); + sb_line(b, " if m == 97 {"); + sb_line(b, " if plus {"); + sb_line(b, " return 1090;"); + sb_line(b, " }"); + sb_line(b, " return O_WRONLY_CREAT_APPEND;"); + sb_line(b, " }"); + sb_line(b, " return -1;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn file_open(path: i64, mode: i64) -> i64 {"); + sb_line(b, " if path == 0 || mode == 0 {"); + sb_line(b, " return 0;"); + sb_line(b, " }"); + sb_line(b, " let flags = rt_open_flags(mode);"); + sb_line(b, " if flags < 0 {"); + sb_line(b, " return 0;"); + sb_line(b, " }"); + sb_line(b, " let fd = win_open(path, flags);"); + sb_line(b, " if fd < 0 {"); + sb_line(b, " return 0;"); + sb_line(b, " }"); + sb_line(b, " let h = rt_malloc(8);"); + sb_line(b, " store64(h, fd);"); + sb_line(b, " return h;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn file_close(h: i64) -> i64 {"); + sb_line(b, " if h != 0 {"); + sb_line(b, " CloseHandle(load64(h));"); + sb_line(b, " rt_free(h);"); + sb_line(b, " }"); + sb_line(b, " return 0;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "// Everything from `fd` to end of file; \"\" on error."); + sb_line(b, "fn rt_read_fd(fd: i64) -> i64 {"); + sb_line(b, " let mut cap: i64 = 4096;"); + sb_line(b, " let end = os_syscall(8, fd, 0, 2, 0, 0);"); + sb_line(b, " if end >= 0 {"); + sb_line(b, " if os_syscall(8, fd, 0, 0, 0, 0) < 0 {"); + sb_line(b, " return rt_dup_n(\"\", 0);"); + sb_line(b, " }"); + sb_line(b, " cap = end + 1;"); + sb_line(b, " }"); + sb_line(b, " let mut buf = rt_malloc(cap + 1);"); + sb_line(b, " let mut got: i64 = 0;"); + sb_line(b, " let mut going = true;"); + sb_line(b, " while going {"); + sb_line(b, " if got == cap {"); + sb_line(b, " cap = cap * 2;"); + sb_line(b, " buf = rt_realloc(buf, cap + 1);"); + sb_line(b, " }"); + sb_line(b, " let r = os_syscall(0, fd, buf + got, cap - got, 0, 0);"); + sb_line(b, " if r <= 0 {"); + sb_line(b, " going = false;"); + sb_line(b, " } else {"); + sb_line(b, " got = got + r;"); + sb_line(b, " }"); + sb_line(b, " }"); + sb_line(b, " store8(buf + got, 0);"); + sb_line(b, " return buf;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn file_read_all(h: i64) -> i64 {"); + sb_line(b, " if h == 0 {"); + sb_line(b, " return rt_dup_n(\"\", 0);"); + sb_line(b, " }"); + sb_line(b, " return rt_read_fd(load64(h));"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn file_write(h: i64, content: i64) -> i64 {"); + sb_line(b, " if h == 0 || content == 0 {"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " return rt_write_all(load64(h), content, rt_strlen(content));"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn file_exists(path: i64) -> i64 {"); + sb_line(b, " if path != 0 && os_syscall(21, path, 0, 0, 0, 0) == 0 {"); + sb_line(b, " return 1;"); + sb_line(b, " }"); + sb_line(b, " return 0;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn file_remove(path: i64) -> i64 {"); + sb_line(b, " if path != 0 && os_syscall(87, path, 0, 0, 0, 0) == 0 {"); + sb_line(b, " return 0;"); + sb_line(b, " }"); + sb_line(b, " return -1;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn file_size(path: i64) -> i64 {"); + sb_line(b, " let st = RT_BASE + RS_STAT;"); + sb_line(b, " if path == 0 || win_stat(path, st) != 0 {"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " return load64(st + 48);"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn dir_exists(path: i64) -> bool {"); + sb_line(b, " let st = RT_BASE + RS_STAT;"); + sb_line(b, " if path == 0 || win_stat(path, st) != 0 {"); + sb_line(b, " return false;"); + sb_line(b, " }"); + sb_line(b, " return (load64(st + 24) & 61440) == 16384;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn file_copy(src: i64, dst: i64) -> i64 {"); + sb_line(b, " if src == 0 || dst == 0 {"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " let content = track_file_read(src);"); + sb_line(b, " if file_exists(src) == 0 {"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " let fd = win_open(dst, O_WRONLY_CREAT_TRUNC);"); + sb_line(b, " if fd < 0 {"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " rt_write_all(fd, content, rt_strlen(content));"); + sb_line(b, " CloseHandle(fd);"); + sb_line(b, " return 0;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn track_file_read(path: i64) -> i64 {"); + sb_line(b, " if path == 0 {"); + sb_line(b, " return rt_dup_n(\"\", 0);"); + sb_line(b, " }"); + sb_line(b, " let fd = win_open(path, O_RDONLY);"); + sb_line(b, " if fd < 0 {"); + sb_line(b, " return rt_dup_n(\"\", 0);"); + sb_line(b, " }"); + sb_line(b, " let out = rt_read_fd(fd);"); + sb_line(b, " CloseHandle(fd);"); + sb_line(b, " return out;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn track_file_write_all(path: i64, content: i64) -> i64 {"); + sb_line(b, " if path == 0 {"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " let fd = win_open(path, O_WRONLY_CREAT_TRUNC);"); + sb_line(b, " if fd < 0 {"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " let mut status: i64 = -1;"); + sb_line(b, " if content != 0 {"); + sb_line(b, " status = rt_write_all(fd, content, rt_strlen(content));"); + sb_line(b, " }"); + sb_line(b, " if CloseHandle(fd) == 0 {"); + sb_line(b, " status = -1;"); + sb_line(b, " }"); + sb_line(b, " return status;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "// ---------------------------------------------------------------- network"); + sb_line(b, "//"); + sb_line(b, "// Not yet on Windows (Winsock): every call fails."); + sb_line(b, ""); + sb_line(b, "fn net_socket_tcp_listen(port: i64) -> i64 { return -1; }"); + sb_line(b, "fn net_socket_accept(server_fd: i64) -> i64 { return -1; }"); + sb_line(b, "fn net_socket_connect(host: i64, port: i64) -> i64 { return -1; }"); + sb_line(b, "fn net_socket_send(fd: i64, data: i64, len: i64) -> i64 { return -1; }"); + sb_line(b, "fn net_socket_recv(fd: i64, buf: i64, max_len: i64) -> i64 { return -1; }"); + sb_line(b, "fn net_socket_close(fd: i64) -> i64 { return 0; }"); + return 0; +} + +fn rt_module_source_6(b: i64) -> i64 { sb_line(b, "// libc.trk — the few libc entry points trackc's ELF writer (elf.trk)"); sb_line(b, "// calls by their libc names, so the Rust bootstrap compiler can link them"); sb_line(b, "// from libc. With the Track runtime (--rt=track, --native) these"); @@ -2176,5 +2885,6 @@ fn rt_module_source(i: i64) -> i64 { if i == 3 { rt_module_source_3(b); } if i == 4 { rt_module_source_4(b); } if i == 5 { rt_module_source_5(b); } + if i == 6 { rt_module_source_6(b); } return sb_text(b); } diff --git a/docs/native.md b/docs/native.md index 2cd0ef4..23d9988 100644 --- a/docs/native.md +++ b/docs/native.md @@ -1,8 +1,9 @@ # The native backend and the Track runtime -`trackc` compiles `compiler/src/*.trk` straight to a Linux x86-64 -executable, with no C compiler and no C source in the chain. Track targets -x86-64 Linux only. Two halves: +`trackc` compiles `compiler/src/*.trk` straight to a native executable, +with no C compiler and no C source in the chain: a static ELF for +x86_64-linux, a PE32+ console executable for x86_64-windows (see +"Targets"). Two halves: - **the runtime written in Track** (`compiler/rt/*.trk`), which needs no libc; @@ -14,6 +15,87 @@ itself, and `scripts/selfhost.sh` rebuilds trackc that way with no program reachable (docs/bootstrap.md). The C backend and the C runtime (`runtime/track_runtime.c`) that once stood beside them are gone (card NOC). +## Targets + +`trackc build|run|check --target -` (also `--target=` or +`TRACKC_TARGET=`) picks the target; the default is the host. Arch is +`x86_64` or `aarch64`, OS is `linux`, `macos` or `windows`; any other +pair is an error (exit 2). `check` accepts every known pair; `build` +generates code for: + +| target | output | status | +|---|---|---| +| x86_64-linux | static ELF, Linux syscalls | default; output byte-identical to earlier trackc | +| x86_64-windows | PE32+ console .exe, kernel32 imports | builds and runs (tested under wine); trackc.exe self-hosts | +| aarch64-linux, x86_64/aarch64-macos, aarch64-windows | | "not supported yet" | + +`run` only runs host-target programs. The target picks the OS layer: +trackc loads `rt/os/.trk` with the portable rt modules and passes +the OS to ngen (`generate_native_for`, NG_TARGET). + +### The OS layer + +Every `compiler/rt/os/.trk` defines this interface (the names the +other rt modules, ngen and the checker builtins call): + +- process: `os_args_count`, `os_arg`, `env_get`, `env_exists`, + `sys_exec`, `process_spawn`, `clock_ms`; +- files: `file_open`, `file_close`, `file_read_all`, `file_write`, + `file_exists`, `file_remove`, `file_size`, `dir_exists`, `file_copy`, + `track_file_read`, `track_file_write_all`; +- network: `net_socket_tcp_listen`, `_accept`, `_connect`, `_send`, + `_recv`, `_close`; +- off Linux only: `os_start()` (the entry; builds argc/argv and calls + `rt_start`) and `os_syscall(nr, a, b, c, d, e)`. + +The portable modules (`mem`, `io`, `libc`) still make their few kernel +calls with `syscall6` and Linux numbers (read, write, open, close, stat, +lseek, mmap, munmap, mremap, madvise, pipe, access, getpid, kill, unlink, +clock_gettime, exit_group, fchmod). On Linux that is the `syscall` +instruction; on any other target ngen lowers `syscall6(nr, a..f)` to a +call of the OS layer's `os_syscall(nr, a..e)` (the runtime never passes +a sixth argument), which maps each number to the OS. This keeps +x86_64-linux output byte-identical: every rt function is emitted in load +order, so moving Linux code between files would change every binary. + +### Imported functions (`extern`) + +```track +extern "kernel32.dll" fn WriteFile(h: i64, buf: i64, n: i64, done: i64, ov: i64) -> i32; +``` + +declares a function in a system library (`extern` is contextual: only +`extern` followed by a string starts one). Calls type-check like any +function; arguments are words. The return type picks the result width: +`i32` sign-extends `eax`, `u32`/`bool` zero-extends it (Win32 `BOOL` and +`DWORD`), anything else keeps `rax`. + +The backend (`ffi.trk`) records an import table, (library, symbol) +pairs, and per call site a fixup (code position, import id); the image +writer lays out the table and fills the fixups. For x86_64-windows each +call is `call [rip + IAT slot]` with the Win64 ABI: arguments 1-4 in +rcx, rdx, r8, r9, the rest on the stack above 32 bytes of shadow space, +rsp 16-byte aligned (`ffi_win64_call`); pe.trk writes one import +descriptor per library. A macOS writer (dyld binding to libSystem, SysV +ABI) or aarch64-windows reuses the two tables and adds its own call +sequence next to `ffi_win64_call`. On a target without import support a +call to an `extern` function is an error. + +### PE32+ layout (`pe.trk`) + +DOS header and stub, COFF header (AMD64, relocations stripped), PE32+ +optional header (console subsystem, image base 0x140000000, 256 MiB +stack reserve and 16 MiB committed: ngen frames may skip guard pages), +then `.text` (RVA 0x1000, entry at its first byte), `.data` (ngen pads +the code to a page for this target so rip-relative data references hold) +and `.idata`. The Windows entry aligns the stack and calls `os_start`; +`sys_exit` ends in `ExitProcess`. File descriptors are HANDLEs, 0-2 the +standard handles; paths and arguments are UTF-8 in Track and UTF-16 at +the kernel32 boundary. + +Not yet on Windows: sockets (Winsock) and `track_trap_div` dies with exit +code 136 rather than a signal. + ## Machine builtins Registered in `checker.trk` (`register_builtins`) and lowered inline by @@ -39,7 +121,8 @@ calls; `store64`/`store8` must not be reordered across `syscall6`. | `io.trk` | `rt_start`, `sys_exit`, buffered stdout, stderr, `print*`, `track_out`/`track_err`, `read_line`, `track_abort`, `track_trap_div`, int formatting | | `str.trk` | `str_*`, `int_to_str`, `track_str_bytes`, `char_*`, `path_*` | | `vec.trk` | `vec_*`, `track_i64_collection_*`, `track_sb_*`, `track_array_*`, `array_len`, `track_bad_field`, `math_*`, `add`/`sum`/`sub` | -| `sys.trk` | argv, `env_*`, `sys_exec`/`process_spawn` (fork + execve `/bin/sh -c` + wait4), `clock_ms`, `file_*`, `track_file_*`, `dir_exists`, `net_socket_*` | +| `os/linux.trk` | the Linux OS layer: argv, `env_*`, `sys_exec`/`process_spawn` (fork + execve `/bin/sh -c` + wait4), `clock_ms`, `file_*`, `track_file_*`, `dir_exists`, `net_socket_*` | +| `os/windows.trk` | the Windows OS layer (kernel32 through `extern`): the same interface, plus `os_start` and `os_syscall` | | `libc.trk` | `open64`, `write`, `fchmod`, `close`, `memset`: the libc names `elf.trk` calls, written in Track | The runtime keeps the word-ABI behaviour of the retired C runtime diff --git a/scripts/embed_runtime.sh b/scripts/embed_runtime.sh index c32bd25..0ec2971 100755 --- a/scripts/embed_runtime.sh +++ b/scripts/embed_runtime.sh @@ -12,7 +12,7 @@ set -eu root=$(cd "$(dirname "$0")/.." && pwd) out="$root/compiler/src/runtime_trk.trk" tmp="${out}.tmp.$$" -modules="mem io str vec sys libc" +modules="mem io str vec os/linux os/windows libc" { echo "// runtime_trk.trk — GENERATED by scripts/embed_runtime.sh from" diff --git a/tests/sh/ids.txt b/tests/sh/ids.txt index fa5c02c..d353c1e 100644 --- a/tests/sh/ids.txt +++ b/tests/sh/ids.txt @@ -92,3 +92,12 @@ tools/nvim_headless_filetype_and_syntax tools/nvim_headless_lua_syntax_ok tools/nvim_devicon_svg_not_needed_headless tools/nvim_syntax_highlight_sample_headless +xplat/xplat_unknown_target_is_a_clear_error +xplat/xplat_unsupported_target_says_so +xplat/xplat_linux_target_is_the_default_output +xplat/xplat_windows_build_is_a_pe32plus_image +xplat/xplat_extern_needs_an_import_target +xplat/xplat_windows_hello_runs_under_wine +xplat/xplat_windows_extern_call_under_wine +xplat/xplat_windows_examples_print_their_goldens +xplat/xplat_windows_trackc_builds_hello diff --git a/tests/sh/xplat.sh b/tests/sh/xplat.sh new file mode 100644 index 0000000..a2c7bc8 --- /dev/null +++ b/tests/sh/xplat.sh @@ -0,0 +1,124 @@ +# Cross-platform targets (`--target`, docs/native.md "Targets"): target +# parsing, x86_64-linux output unchanged by the target machinery, and +# x86_64-windows PE executables run under wine (skipped without wine). +# Commands run from the repository root. + +# wine with a quiet log; WINEPREFIX may point at a scratch prefix. +win_run() { + (cd "$1" && shift && WINEDEBUG=-all timeout 120 wine "$@") >"$T/.out" 2>"$T/.err" + RC=$? + OUT=$(cat "$T/.out") + ERR=$(cat "$T/.err") + return 0 +} + +need_wine() { + have wine || skip "wine not found" +} + +t_xplat_unknown_target_is_a_clear_error() { + in_repo "$TRACKC" build --target sparc-plan9 examples/hello.trk -o "$T/x" + rc_is 2 "exit code" + has "$ERR" "unknown target 'sparc-plan9'" "message" + has "$ERR" "x86_64 or aarch64" "hint" + in_repo env TRACKC_TARGET=x86_64-beos "$TRACKC" check examples/hello.trk + rc_is 2 "TRACKC_TARGET is read" +} + +t_xplat_unsupported_target_says_so() { + in_repo "$TRACKC" build --target aarch64-macos examples/hello.trk -o "$T/x" + rc_is 2 "exit code" + has "$ERR" "not supported yet" "message" + in_repo "$TRACKC" check --target aarch64-macos examples/hello.trk + rc_ok "check works for any known target" +} + +t_xplat_linux_target_is_the_default_output() { + in_repo "$TRACKC" build examples/hello.trk -o "$T/a" + rc_ok "default build" + in_repo "$TRACKC" build --target x86_64-linux examples/hello.trk -o "$T/b" + rc_ok "--target build" + in_repo env TRACKC_TARGET=x86_64-linux "$TRACKC" build examples/hello.trk -o "$T/c" + rc_ok "TRACKC_TARGET build" + same_file "$T/a" "$T/b" "--target x86_64-linux" + same_file "$T/a" "$T/c" "TRACKC_TARGET=x86_64-linux" +} + +t_xplat_windows_build_is_a_pe32plus_image() { + in_repo "$TRACKC" build --target x86_64-windows examples/hello.trk -o "$T/hello.exe" + rc_ok "build" + eq "$(head -c 2 "$T/hello.exe")" "MZ" "DOS magic" + eq "$(dd if="$T/hello.exe" bs=1 skip=128 count=4 2>/dev/null | od -An -c | tr -d ' ')" 'PE\0\0' "PE signature" + eq "$(dd if="$T/hello.exe" bs=1 skip=152 count=2 2>/dev/null | od -An -tx1 | tr -d ' ')" '0b02' "PE32+ magic" + grep -q 'kernel32.dll' "$T/hello.exe" || fail "no kernel32.dll import" +} + +t_xplat_extern_needs_an_import_target() { + cat >"$T/ext.trk" <<'EOF' +extern "kernel32.dll" fn GetCurrentProcessId() -> u32; +fn main() -> i64 { return GetCurrentProcessId(); } +EOF + trackc check "$T/ext.trk" + rc_ok "check accepts extern" + trackc build "$T/ext.trk" -o "$T/ext" + rc_fail "linux build of an import" + has "$ERR" "needs --target x86_64-windows" "message" +} + +t_xplat_windows_hello_runs_under_wine() { + need_wine + in_repo "$TRACKC" build --target x86_64-windows examples/hello.trk -o "$T/hello.exe" + rc_ok "build" + win_run "$T" "$T/hello.exe" + rc_ok "run" + eq "$OUT" "42" "stdout" +} + +t_xplat_windows_extern_call_under_wine() { + need_wine + cat >"$T/ext.trk" <<'EOF' +extern "kernel32.dll" fn GetStdHandle(which: i64) -> i64; +extern "kernel32.dll" fn WriteFile(h: i64, buf: i64, n: i64, done: i64, ov: i64) -> i32; +extern "kernel32.dll" fn MulDiv(a: i64, b: i64, c: i64) -> i32; +fn main() -> i64 { + WriteFile(GetStdHandle(-11), "via WriteFile\n", 14, 0, 0); + print(MulDiv(-7, 6, 2)); + return 3; +} +EOF + trackc build --target x86_64-windows "$T/ext.trk" -o "$T/ext.exe" + rc_ok "build" + win_run "$T" "$T/ext.exe" + rc_is 3 "exit code" + eq "$OUT" "via WriteFile +-21" "stdout" +} + +# The examples print their goldens under wine, arguments and files +# included; net_demo needs sockets (not on Windows yet). +t_xplat_windows_examples_print_their_goldens() { + need_wine + local e n=0 g="$ROOT/tests/cases/examples" + for e in arithmetic borrow generics hello linear_auto_free macro_test slice_and_types stdlib_demo structs_arrays union_enum_test use_test v030_features_demo v040_features_demo; do + n=$((n + 1)) + in_repo "$TRACKC" build --target x86_64-windows "examples/$e.trk" -o "$T/$e.exe" + rc_ok "$e: build" + win_run "$ROOT/examples" "$T/$e.exe" + out_is "$g/$e.out" "$e: output" + rc_is "$(cat "$g/$e.code")" "$e: exit code" + done + [ "$n" -ge 13 ] || fail "only $n inputs" +} + +# trackc.exe, built for Windows, builds hello.exe identical to the one +# the Linux trackc builds. +t_xplat_windows_trackc_builds_hello() { + need_wine + in_repo "$TRACKC" build --target x86_64-windows compiler/src/main.trk -o "$T/trackc.exe" + rc_ok "trackc.exe build" + in_repo "$TRACKC" build --target x86_64-windows examples/hello.trk -o "$T/h1.exe" + rc_ok "hello.exe build" + win_run "$ROOT" "$T/trackc.exe" build --target x86_64-windows examples/hello.trk -o "$T/h2.exe" + rc_ok "trackc.exe builds hello.exe" + same_file "$T/h1.exe" "$T/h2.exe" "hello.exe from both compilers" +}