From 76a2b1b6a88d0c53c4d5d75514f6fcbed627d453 Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Tue, 13 Oct 2026 16:55:03 +0100 Subject: [PATCH] Self step 2b: Link, Elf and X64 in raz, tested against the seed's self/Link.raz, self/Elf.raz and self/X64.raz (encoder, assembler, listing). Link and Elf write the same executable from the same chunks, static, dynamic and stripped; X64's encoders give the same bytes and listing on a script, and its assembler the same bytes, listing and messages on a long run of every instruction and a file for each of its errors (test/genasm.py). Scan.regrab is shared by them. README lists what the port found. Co-Authored-By: Claude Sonnet 5.5 --- diff --git a/PLAN.md b/PLAN.md index 09e6a33..f9d628e 100644 --- a/PLAN.md +++ b/PLAN.md @@ -31,7 +31,7 @@ 1. `diag` and `scan` (done): the trial. Measure `scan`'s speed against the seed's and list what `Sys` and the library lacked. Stop for review: if the cost is too high, mend the code generator first. -2. `chunk`, `sym` (2a, done); `link`, `elf`, `x64` (2b). +2. `chunk`, `sym` (2a, done); `link`, `elf`, `x64` (2b, done). 3. `gen`, `item`. 4. `parse`, `raz`: the first compiler that builds. 5. Fixpoint: the seed builds `self`, that builds `self`, that builds diff --git a/self/Chunk.raz b/self/Chunk.raz index a83cdaa..3078ac5 100644 --- a/self/Chunk.raz +++ b/self/Chunk.raz @@ -17,7 +17,7 @@ Exported variables can't be set from outside, so the setters at the end do what the seed's other units do to these. *) module Chunk; -import Mem, Heap, Fmt, Diag, Scan; +import Fmt, Diag, Scan; type Section* = (secText, secRodata, secBss); @@ -27,7 +27,7 @@ start*, size*, align*: INT; (* in its section's buffer *) firstFix*, numFix*: INT; (* its fixups: text's in fixups, rodata's in dataFixups *) home*, name*: INT; (* its module and its name, for the symbol table; -1 if none *) - adr*: I64; (* its address, set by the linker *) + adr*: INT; (* its address, set by the linker *) live*: BOOL; (* reached from the entry point *) ext*: BOOL; (* bss: the address of a C symbol, its name *) reals*: BOOL; (* code: computes with reals, first at realsAt *) @@ -81,21 +81,11 @@ codeCap, roCap, chunkCap, fixCap, dataFixCap, lineCap, noteCap: INT; -(* p, which holds used bytes, moved to a block of size bytes *) -proc grown(p: ^U8; used, size: INT): ^U8; -var q: ^U8; -begin - q := Scan.grab(size); - COPY(q[0..used], p[0..used]); - Mem.free(Heap.heap, p); - return q; -end; - (* Room for n more bytes of code *) proc room(n: INT); begin if pc + n > codeCap then - text := grown(text, pc, codeCap * 2 + n); + text := Scan.regrab(text, pc, codeCap * 2 + n); codeCap := codeCap * 2 + n; end; end; @@ -157,7 +147,7 @@ var c: ^Chunk; begin if numChunks = chunkCap then - chunks := ^Chunk(grown(^U8(chunks), numChunks * SIZE(Chunk), chunkCap * 2 * SIZE(Chunk))); + chunks := ^Chunk(Scan.regrab(^U8(chunks), numChunks * SIZE(Chunk), chunkCap * 2 * SIZE(Chunk))); chunkCap := chunkCap * 2; end; c := ADR(chunks[numChunks]); @@ -194,7 +184,7 @@ proc setData*(c: INT; p: ^U8; n, align: INT); begin if rolen + n > roCap then - rodata := grown(rodata, rolen, roCap * 2 + n); + rodata := Scan.regrab(rodata, rolen, roCap * 2 + n); roCap := roCap * 2 + n; end; COPY(rodata[rolen..rolen + n], p[0..n]); @@ -222,7 +212,7 @@ return; end; if numLines = lineCap then - lines := ^Line(grown(^U8(lines), numLines * SIZE(Line), lineCap * 2 * SIZE(Line))); + lines := ^Line(Scan.regrab(^U8(lines), numLines * SIZE(Line), lineCap * 2 * SIZE(Line))); lineCap := lineCap * 2; end; lines[numLines].at := pc; @@ -250,7 +240,7 @@ proc addFixup*(at, chunk, addend: INT); begin if numFixups = fixCap then - fixups := ^Fixup(grown(^U8(fixups), numFixups * SIZE(Fixup), fixCap * 2 * SIZE(Fixup))); + fixups := ^Fixup(Scan.regrab(^U8(fixups), numFixups * SIZE(Fixup), fixCap * 2 * SIZE(Fixup))); fixCap := fixCap * 2; end; fixups[numFixups].at := at; @@ -264,7 +254,7 @@ proc addDataFixup*(c, at, chunk, addend: INT); begin if numDataFixups = dataFixCap then - dataFixups := ^Fixup(grown(^U8(dataFixups), numDataFixups * SIZE(Fixup), dataFixCap * 2 * SIZE(Fixup))); + dataFixups := ^Fixup(Scan.regrab(^U8(dataFixups), numDataFixups * SIZE(Fixup), dataFixCap * 2 * SIZE(Fixup))); dataFixCap := dataFixCap * 2; end; dataFixups[numDataFixups].at := at; @@ -277,7 +267,7 @@ proc noteVar*(chunk, name, off, kind: INT); begin if numVarNotes = noteCap then - varNotes := ^VarNote(grown(^U8(varNotes), numVarNotes * SIZE(VarNote), noteCap * 2 * SIZE(VarNote))); + varNotes := ^VarNote(Scan.regrab(^U8(varNotes), numVarNotes * SIZE(VarNote), noteCap * 2 * SIZE(VarNote))); noteCap := noteCap * 2; end; varNotes[numVarNotes].chunk := chunk; @@ -321,7 +311,7 @@ chunks[c].live := true; end; -proc setAdr*(c: INT; a: I64); +proc setAdr*(c: INT; a: INT); begin chunks[c].adr := a; end; diff --git a/self/Elf.raz b/self/Elf.raz new file mode 100644 index 0000000..19defdb --- /dev/null +++ b/self/Elf.raz @@ -0,0 +1,431 @@ +(* Elf: the executable file. + + Writes an ELF64 executable for x86-64 Linux: the ELF header, the + program headers, the linked text and rodata, and section headers + with a symbol table, so that objdump and gdb can name each procedure + and variable. For gdb's line numbers there is DWARF 4: a line table + (.debug_line), and the one compile unit that points to it + (.debug_info, .debug_abbrev). There are no types or variables. + + A program that uses C is linked dynamically, in the least way the + loader accepts: it names its loader and libraries, and each C symbol + it uses is a quadword the loader fills in with the symbol's address + (a GLOB_DAT relocation), which the code calls or reads through. + There is no PLT and no lazy binding, and the program exports nothing. + + Depends on: Link for the images and addresses, Chunk for the chunks, + Scan for names and memory, Diag for errors, Sys and Files to write + the file. + Leaves out: position independent executables, symbol versions, the + rest of DWARF. + + Exported variables can't be set from outside, so needLib, setMainPath + and setStripped do it. *) +module Elf; +import Sys, Files, Fmt, Diag, Scan, Chunk, Link; + +var + needed: [32]INT; (* the libraries to load, names interned *) + numNeeded*: INT; (* none: a static program *) + mainPath: []U8; (* the main module's file, for gdb *) + stripped*: BOOL; (* -s: no symbols and no line numbers; the sections are there, empty *) + + buf: ^U8; + len, cap: INT; + +(* The library name, to be loaded, unless it is already: false if there + are too many *) +proc needLib*(name: INT): BOOL; +var i: INT; +begin + for i := 0 to numNeeded - 1 do + if needed[i] = name then return true; end; + end; + if numNeeded = 32 then return false; end; + needed[numNeeded] := name; + INC(numNeeded); + return true; +end; + +(* A static program again *) +proc noLibs*; +begin + numNeeded := 0; +end; + +proc setMainPath*(path: []U8); +begin + mainPath := path; +end; + +proc setStripped*(yes: BOOL); +begin + stripped := yes; +end; + +proc room(n: INT); +begin + if len + n > cap then + buf := Scan.regrab(buf, len, cap * 2 + n); + cap := cap * 2 + n; + end; +end; + +(* The n low bytes of v, least significant first *) +proc putN(v: INT; n: INT); +var i: INT; +begin + room(n); + for i := 0 to n - 1 do + buf[len] := U8(v & 0FFH); + v := v shr 8; + INC(len); + end; +end; + +proc putBytes(p: ^U8; n: INT); +begin + room(n); + if n > 0 then COPY(buf[len..len + n], p[0..n]); end; + len := len + n; +end; + +proc padTo(off: INT); +begin + while len < off do putN(0, 1); end; +end; + +proc patch(at: INT; v: INT; n: INT); +var i: INT; +begin + for i := 0 to n - 1 do + buf[at + i] := U8(v & 0FFH); + v := v shr 8; + end; +end; + +proc phdr(typ, flags: INT; off, adr, filesz, memsz, align: INT); +begin + putN(typ, 4); + putN(flags, 4); + putN(off, 8); + putN(adr, 8); + putN(adr, 8); + putN(filesz, 8); + putN(memsz, 8); + putN(align, 8); +end; + +const + (* the section names, in .shstrtab; a section header names its own *) + ShNames = "\0.text\0.rodata\0.bss\0.symtab\0.strtab\0.shstrtab\0.dynamic\0.dynstr\0.dynsym\0.debug_line\0.debug_info\0.debug_abbrev\0"; + +(* Where in ShNames the name is: the byte after a zero that starts it and + is followed by one; the empty name, found nowhere, is 0 *) +proc nameAt(name: []U8): INT; +var i, k: INT; same: BOOL; +begin + for i := 1 to LEN(ShNames) - LEN(name) - 1 do + if ShNames[i - 1] = 0 then + same := ShNames[i + LEN(name)] = 0; + for k := 0 to LEN(name) - 1 do + if ShNames[i + k] # name[k] then same := false; end; + end; + if same and (LEN(name) > 0) then return i; end; + end; + end; + return 0; +end; + +(* A section header. Its name is stored as its offset in ShNames. *) +proc shdr(name: []U8; typ: INT; flags, adr, off, size: INT; lnk, info: INT; align, entsize: INT); +begin + putN(nameAt(name), 4); putN(typ, 4); putN(flags, 8); putN(adr, 8); + putN(off, 8); putN(size, 8); putN(lnk, 4); putN(info, 4); + putN(align, 8); putN(entsize, 8); +end; + +proc putStr(s: []U8); +begin + putBytes(ADR(s[0]), LEN(s)); + putN(0, 1); +end; + +(* LEB128, unsigned *) +proc putU(v: INT); +begin + while v >= 80H do + putN(v & 7FH | 80H, 1); + v := v shr 7; + end; + putN(v, 1); +end; + +(* The compile unit, which names the line table, and its abbreviation; + the table itself is in the places, in rodata (Link). Section + offsets go in off, sizes in size: line, info, abbrev. *) +proc putDebug(off, size: []INT); +var cwd: []U8; err: INT; +begin + off[0] := Chunk.chunks[Link.placesChunk].adr - Link.roAdr + Link.roOff + Link.linesOff; + size[0] := Link.linesSize; + off[1] := len; + putN(0, 4); putN(4, 2); putN(0, 4); putN(8, 1); (* length, version, abbrev, address size *) + putU(1); + putStr(mainPath); + cwd, err := Sys.workDir(); + if err # 0 then cwd := ""; end; + putStr(cwd); + putStr("raz"); + putN(0, 4); (* the line table, at 0 *) + putN(Link.Base + Link.textOff, 8); putN(Link.textSize, 8); (* the code, all of it *) + patch(off[1], len - off[1] - 4, 4); + size[1] := len - off[1]; + + off[2] := len; + putU(1); putU(11H); putN(0, 1); (* 1: a compile unit, no children *) + putU(03H); putU(08H); (* name, a string *) + putU(1BH); putU(08H); (* comp_dir, a string *) + putU(25H); putU(08H); (* producer, a string *) + putU(10H); putU(17H); (* stmt_list, a section offset *) + putU(11H); putU(01H); (* low_pc, an address *) + putU(12H); putU(07H); (* high_pc, a length in 8 bytes *) + putN(0, 2); putN(0, 1); + size[2] := len - off[2]; +end; + +const + Interp = "/lib64/ld-linux-x86-64.so.2"; + (* program header types *) + PtLoad = 1; PtDynamic = 2; PtInterp = 3; PtGnuStack = 6474E551H; + +var + (* in the room at the end of rodata: where each of the loader's + tables starts, from extraAdr *) + symAt, relaAt, hashAt, strAt: INT; + nsym, strLen: INT; + +(* Whether chunk c is a C symbol the program uses *) +proc isExt(c: INT): BOOL; +begin + return Chunk.chunks[c].live and Chunk.chunks[c].ext; +end; + +(* The sizes of the loader's tables: what linkAll must leave room for. *) +proc sizeTables(roExtra, dynSize: ^INT); +var c, i: INT; +begin + nsym := 1; + strLen := 1; + for i := 0 to numNeeded - 1 do strLen := strLen + LEN(Scan.nameOf(needed[i])) + 1; end; + for c := 0 to Chunk.numChunks - 1 do + if isExt(c) then + INC(nsym); + strLen := strLen + LEN(Scan.nameOf(Chunk.chunks[c].name)) + 1; + end; + end; + symAt := (LEN(Interp) + 1 + 7) div 8 * 8; + relaAt := symAt + nsym * 24; + hashAt := relaAt + (nsym - 1) * 24; + strAt := hashAt + 4 * (3 + nsym); + roExtra^ := strAt + strLen; + dynSize^ := (numNeeded + 10) * 16; +end; + +(* The loader's tables in the room at the end of rodata, which the + buffer already holds as zeros: the loader's name; the symbols, one + for each C symbol used; a GLOB_DAT relocation for each, at its + quadword; a hash table of one bucket; and their names. *) +proc putTables; +var c, k, i, at, name: INT; +begin + len := Link.extraAdr - Link.roAdr + Link.roOff; + putStr(Interp); + padTo(Link.extraAdr - Link.roAdr + Link.roOff + symAt); + putN(0, 24); + name := strLen; + for c := Chunk.numChunks - 1 to 0 by -1 do (* names go last in the string table *) + if isExt(c) then name := name - LEN(Scan.nameOf(Chunk.chunks[c].name)) - 1; end; + end; + for c := 0 to Chunk.numChunks - 1 do + if isExt(c) then + putN(name, 4); putN(10H, 1); putN(0, 1); putN(0, 2); (* global, undefined *) + putN(0, 8); putN(0, 8); + name := name + LEN(Scan.nameOf(Chunk.chunks[c].name)) + 1; + end; + end; + k := 1; + for c := 0 to Chunk.numChunks - 1 do + if isExt(c) then + putN(Chunk.chunks[c].adr, 8); + putN((k shl 32) | 6, 8); (* R_X86_64_GLOB_DAT *) + putN(0, 8); + INC(k); + end; + end; + putN(1, 4); putN(nsym, 4); putN(nsym - 1, 4); (* the bucket chains every symbol *) + putN(0, 4); + for i := 1 to nsym - 1 do putN(i - 1, 4); end; + putN(0, 1); + for i := 0 to numNeeded - 1 do putStr(Scan.nameOf(needed[i])); end; + for c := 0 to Chunk.numChunks - 1 do + if isExt(c) then putStr(Scan.nameOf(Chunk.chunks[c].name)); end; + end; + len := Link.roOff + Link.roSize; + + (* the dynamic table, at the start of the writable segment *) + padTo(Link.bssOff); + at := 1; + for i := 0 to numNeeded - 1 do + putN(1, 8); putN(at, 8); (* DT_NEEDED *) + at := at + LEN(Scan.nameOf(needed[i])) + 1; + end; + putN(4, 8); putN(Link.extraAdr + hashAt, 8); (* DT_HASH *) + putN(5, 8); putN(Link.extraAdr + strAt, 8); (* DT_STRTAB *) + putN(6, 8); putN(Link.extraAdr + symAt, 8); (* DT_SYMTAB *) + putN(10, 8); putN(strLen, 8); (* DT_STRSZ *) + putN(11, 8); putN(24, 8); (* DT_SYMENT *) + putN(7, 8); putN(Link.extraAdr + relaAt, 8); (* DT_RELA *) + putN(8, 8); putN((nsym - 1) * 24, 8); (* DT_RELASZ *) + putN(9, 8); putN(24, 8); (* DT_RELAENT *) + putN(21, 8); putN(0, 8); (* DT_DEBUG, for gdb *) + putN(0, 16); (* DT_NULL *) +end; + +proc writeElf*(path: []U8; entry: INT); +var + nph, nsh, c, nsyms, sec, strsCap: INT; + roExtra, dynSize, symOff, strOff, shstrOff, shOff, strsLen: INT; + dbgOff, dbgSize: [3]INT; + strs: ^U8; + s: []U8; + dyn: BOOL; +begin + cap := 1 shl 16; + buf := Scan.grab(cap); + len := 0; + dyn := numNeeded > 0; + roExtra := 0; dynSize := 0; + if dyn then sizeTables(ADR(roExtra), ADR(dynSize)); end; + (* room for the most program headers either kind of program has *) + Link.linkAll(64 + 6 * 56, roExtra, dynSize); + if dyn then + nph := 6; + else + nph := 2; + if Link.roSize > 0 then INC(nph); end; + if Link.bssSize > 0 then INC(nph); end; + end; + + (* ELF header *) + putN(464C457FH, 4); (* #127 'ELF' *) + putN(2, 1); putN(1, 1); putN(1, 1); putN(0, 9); (* 64-bit, little-endian, version 1 *) + putN(2, 2); (* ET_EXEC *) + putN(62, 2); (* EM_X86_64 *) + putN(1, 4); + putN(Chunk.chunks[entry].adr, 8); + putN(64, 8); (* program headers follow *) + putN(0, 8); (* section headers: patched below *) + putN(0, 4); + nsh := 10; + if dyn then nsh := 13; end; + putN(64, 2); putN(56, 2); putN(nph, 2); + putN(64, 2); putN(nsh, 2); putN(6, 2); (* .shstrtab is section 6 *) + + (* flags: 4 read, 5 read and run, 6 read and write *) + if dyn then + phdr(PtInterp, 4, Link.extraAdr - Link.roAdr + Link.roOff, Link.extraAdr, LEN(Interp) + 1, LEN(Interp) + 1, 1); + end; + (* the first segment maps the headers too, so text can follow them *) + phdr(PtLoad, 5, 0, Link.Base, Link.textOff + Link.textSize, Link.textOff + Link.textSize, Link.Page); + if Link.roSize > 0 then phdr(PtLoad, 4, Link.roOff, Link.roAdr, Link.roSize, Link.roSize, Link.Page); end; + if dyn then + phdr(PtLoad, 6, Link.bssOff, Link.bssAdr, dynSize, Link.bssSize, Link.Page); + phdr(PtDynamic, 6, Link.bssOff, Link.bssAdr, dynSize, dynSize, 8); + elsif Link.bssSize > 0 then + phdr(PtLoad, 6, 0, Link.bssAdr, 0, Link.bssSize, Link.Page); + end; + phdr(PtGnuStack, 6, 0, 0, 0, 0, 16); (* a stack that can't run code *) + + padTo(Link.textOff); + putBytes(Link.textImg, Link.textSize); + padTo(Link.roOff); (* even when empty, so that every section lies in the file *) + putBytes(Link.roImg, Link.roSize); + if dyn then putTables; end; + + (* the symbol table: one local symbol for each named live chunk *) + padTo((len + 7) div 8 * 8); + symOff := len; + strsCap := 1 shl 16; + strs := Scan.grab(strsCap); + strsLen := 1; + strs[0] := 0; + putN(0, 24); + nsyms := 1; + for c := 0 to Chunk.numChunks - 1 do + if not stripped and Chunk.chunks[c].live and (Chunk.chunks[c].name >= 0) and not Chunk.chunks[c].ext then + s := Chunk.chunkName(c); + if strsLen + LEN(s) + 1 > strsCap then + strs := Scan.regrab(strs, strsLen, strsLen * 2 + 256); + strsCap := strsLen * 2 + 256; + end; + COPY(strs[strsLen..strsLen + LEN(s)], s); + strs[strsLen + LEN(s)] := 0; + if Chunk.chunks[c].sec = Chunk.secText then (* the section's index in the headers below *) + sec := 1; + elsif Chunk.chunks[c].sec = Chunk.secRodata then + sec := 2; + else + sec := 3; + end; + putN(strsLen, 4); + if sec = 1 then putN(2, 1); else putN(1, 1); end; (* STT_FUNC, STT_OBJECT *) + putN(0, 1); + putN(sec, 2); + putN(Chunk.chunks[c].adr, 8); + putN(Chunk.chunks[c].size, 8); + strsLen := strsLen + LEN(s) + 1; + INC(nsyms); + end; + end; + strOff := len; + putBytes(strs, strsLen); + shstrOff := len; + putBytes(ADR(ShNames[0]), LEN(ShNames)); + if stripped or (Link.placesChunk < 0) then + for c := 0 to 2 do dbgOff[c] := len; dbgSize[c] := 0; end; + else + putDebug(dbgOff, dbgSize); + end; + + padTo((len + 7) div 8 * 8); + shOff := len; + patch(40, shOff, 8); + (* types: 1 PROGBITS, 2 SYMTAB, 3 STRTAB, 6 DYNAMIC, 8 NOBITS, 11 DYNSYM; + flags: 2 ALLOC, 3 WRITE+ALLOC, 6 ALLOC+EXECINSTR. A symbol table's + link is its string table's index: 5 .strtab, 8 .dynstr. The order + here is the index the code above relies on. *) + shdr("", 0, 0, 0, 0, 0, 0, 0, 0, 0); + shdr(".text", 1, 6, Link.Base + Link.textOff, Link.textOff, Link.textSize, 0, 0, 16, 0); + shdr(".rodata", 1, 2, Link.roAdr, Link.roOff, Link.roSize, 0, 0, 16, 0); + shdr(".bss", 8, 3, Link.bssAdr + dynSize, Link.roOff + Link.roSize, Link.bssSize - dynSize, 0, 0, 16, 0); + shdr(".symtab", 2, 0, 0, symOff, nsyms * 24, 5, nsyms, 8, 24); + shdr(".strtab", 3, 0, 0, strOff, strsLen, 0, 0, 1, 0); + shdr(".shstrtab", 3, 0, 0, shstrOff, LEN(ShNames), 0, 0, 1, 0); + if dyn then (* the loader's tables, for readelf and objdump *) + shdr(".dynamic", 6, 3, Link.bssAdr, Link.bssOff, dynSize, 8, 0, 8, 16); + shdr(".dynstr", 3, 2, Link.extraAdr + strAt, Link.extraAdr + strAt - Link.roAdr + Link.roOff, strLen, 0, 0, 1, 0); + shdr(".dynsym", 11, 2, Link.extraAdr + symAt, Link.extraAdr + symAt - Link.roAdr + Link.roOff, nsym * 24, 8, 1, 8, 24); + end; + shdr(".debug_line", 1, 0, 0, dbgOff[0], dbgSize[0], 0, 0, 1, 0); + shdr(".debug_info", 1, 0, 0, dbgOff[1], dbgSize[1], 0, 0, 1, 0); + shdr(".debug_abbrev", 1, 0, 0, dbgOff[2], dbgSize[2], 0, 0, 1, 0); + + if not Files.write(path, buf[0..len]) or (Sys.chmod(path, 1EDH) < 0) then + Diag.fatal(Diag.say("can't write {}", [Fmt.str(path)])); + end; +end; + +begin + mainPath := ""; +end Elf. diff --git a/self/Link.raz b/self/Link.raz new file mode 100644 index 0000000..c93cc31 --- /dev/null +++ b/self/Link.raz @@ -0,0 +1,381 @@ +(* Link: tree shaking, layout and patching. + + Starting from the entry chunk, marks every chunk the program can + reach through fixups; the rest is left out. Then gives each live + chunk its address and builds the images of text and rodata, with + every fixup patched. + + The file is laid out so that each section can be mapped as it lies: + text right after the headers, rodata on the next page, then a + writable page that starts with the table the dynamic loader reads + (none in a static program) and goes on as bss, in memory only. The + loader's other tables come at the end of rodata; Elf writes them + in the room left there. + + Depends on: Chunk for chunks and fixups, Scan for names and memory, + Diag for errors and paths. + Leaves out: the file format; that is Elf. *) +module Link; +import Fmt, Diag, Scan, Chunk; + +const + Base* = 400000H; + Page* = 4096; + +var + textOff*, textSize*: INT; (* file offset and size of text, at Base + textOff *) + roOff*, roSize*: INT; (* rodata, the room for the loader's tables included *) + roAdr*: INT; (* where rodata is loaded *) + extraAdr*: INT; (* that room *) + bssAdr*, bssSize*: INT; (* the writable segment, the loader's table first *) + bssOff*: INT; (* the file offset of that table *) + textImg*, roImg*: ^U8; + placesChunk*: INT; (* the rodata chunk of the places, made by the caller *) + linesOff*, linesSize*: INT; (* the line table, in the places: .debug_line *) + +proc setPlaces*(c: INT); +begin + placesChunk := c; +end; + +(* Marks live each chunk reached from entry through the fixups. *) +proc markLive*(entry: INT); +var stack: ^INT; sp, c, f, t: INT; fx: ^Chunk.Fixup; +begin + stack := ^INT(Scan.grab(Chunk.numChunks * SIZE(INT))); + Chunk.setLive(entry); + stack[0] := entry; + sp := 1; + while sp > 0 do + DEC(sp); + c := stack[sp]; + if Chunk.chunks[c].size < 0 then + Diag.fatal(Diag.say("{} is declared but never defined", [Fmt.str(Chunk.chunkName(c))])); + end; + (* code and constants have fixups; variables start at zero, holding + no addresses *) + fx := nil; + if Chunk.chunks[c].sec = Chunk.secText then + fx := Chunk.fixups; + elsif Chunk.chunks[c].sec = Chunk.secRodata then + fx := Chunk.dataFixups; + end; + if fx # nil then + for f := Chunk.chunks[c].firstFix to Chunk.chunks[c].firstFix + Chunk.chunks[c].numFix - 1 do + t := fx[f].chunk; + if not Chunk.chunks[t].live then + Chunk.setLive(t); + stack[sp] := t; + INC(sp); + end; + end; + end; + end; +end; + +(* Gives the live chunks of one section their places, from start; + returns the end. *) +proc place(sec: Chunk.Section; start: INT): INT; +var c, a: INT; +begin + a := start; + for c := 0 to Chunk.numChunks - 1 do + if Chunk.chunks[c].live and (Chunk.chunks[c].sec = sec) then + a := (a + Chunk.chunks[c].align - 1) div Chunk.chunks[c].align * Chunk.chunks[c].align; + Chunk.setAdr(c, a); + a := a + Chunk.chunks[c].size; + end; + end; + return a; +end; + +(* The line table, DWARF 4's line program, which gdb reads as + .debug_line and Rt to say where code comes from: one sequence for + each live procedure with lines, a row for each place noted, its + address, file, line and column. A row whose address and line move a + little is one byte, a special opcode; the others are made of the + standard ones. Made in lp, lpLen bytes long. *) +const + LineBase = -5; LineRange = 14; OpcodeBase = 13; (* the special opcodes' *) + +var + lp: ^U8; + lpLen, lpCap: INT; + +proc putB(v: INT); +begin + if lpLen = lpCap then + lp := Scan.regrab(lp, lpLen, lpCap * 2 + 256); + lpCap := lpCap * 2 + 256; + end; + lp[lpLen] := U8(v & 0FFH); + INC(lpLen); +end; + +(* The n low bytes of v, least significant first *) +proc putN(v: INT; n: INT); +var i: INT; +begin + for i := 1 to n do putB(v); v := v shr 8; end; +end; + +(* LEB128, unsigned and signed *) +proc putU(v: INT); +begin + while v >= 80H do putB(v & 7FH | 80H); v := v shr 7; end; + putB(v); +end; + +proc putS(v: INT); +begin + while (v < -64) or (v >= 64) do putB(v & 7FH | 80H); v := v shr 7; end; + putB(v & 7FH); +end; + +(* v as the four bytes at at in p *) +proc patch4(p: ^U8; at, v: INT); +var i: INT; +begin + for i := 0 to 3 do p[at + i] := U8((v shr (8 * i)) & 0FFH); end; +end; + +(* v as the eight bytes at at in p *) +proc patch8(p: ^U8; at, v: INT); +var i: INT; +begin + for i := 0 to 7 do p[at + i] := U8((v shr (8 * i)) & 0FFH); end; +end; + +(* Whether the standard opcode i takes an operand *) +proc takesOperand(i: INT): BOOL; +begin + return (i = 2) or (i = 3) or (i = 4) or (i = 5) or (i = 9) or (i = 12); +end; + +(* The line program of the files paths, nfiles of them, numbered from + 1, as they are written in the table *) +proc makeLines(paths: ^INT; nfiles: INT); +var i, f, c, cf, cl, cc, op, at, da, dl: INT; s: []U8; +begin + lpLen := 0; + putN(0, 4); (* unit_length, patched below *) + putN(4, 2); (* version *) + putN(0, 4); (* header_length, patched below *) + putB(1); putB(1); (* minimum_instruction_length, maximum_operations *) + putB(1); (* default_is_stmt *) + putB(LineBase); putB(LineRange); putB(OpcodeBase); + for i := 1 to OpcodeBase - 1 do + if takesOperand(i) then putB(1); else putB(0); end; (* their operands *) + end; + putB(0); (* no include directories *) + for f := 0 to nfiles - 1 do + s := Diag.shownPath(Scan.nameOf(paths[f])); + for i := 0 to LEN(s) - 1 do putB(INT(s[i])); end; + putN(0, 4); (* its end, directory, time, length *) + end; + putB(0); + patch4(lp, 6, lpLen - 10); + i := 0; + while i < Chunk.numLines do + c := Chunk.lines[i].chunk; + if not Chunk.chunks[c].live then + INC(i); + else + putB(0); putU(9); putB(2); (* DW_LNE_set_address *) + putN(Chunk.chunks[c].adr + Chunk.lines[i].at - Chunk.chunks[c].start, 8); + at := Chunk.lines[i].at; cf := 1; cl := 1; cc := 0; + while (i < Chunk.numLines) and (Chunk.lines[i].chunk = c) do + f := 1; + while paths[f - 1] # Chunk.lines[i].path do INC(f); end; + if f # cf then putB(4); putU(f); cf := f; end; (* DW_LNS_set_file *) + if Chunk.lines[i].col # cc then putB(5); putU(Chunk.lines[i].col); cc := Chunk.lines[i].col; end; (* DW_LNS_set_column *) + da := Chunk.lines[i].at - at; + dl := Chunk.lines[i].line - cl; + op := (dl - LineBase) + LineRange * da + OpcodeBase; + if (dl >= LineBase) and (dl < LineBase + LineRange) and (op <= 255) then + putB(op); (* a special opcode: a row *) + else + if da > 0 then putB(2); putU(da); end; (* DW_LNS_advance_pc *) + if dl # 0 then putB(3); putS(dl); end; (* DW_LNS_advance_line *) + putB(1); (* DW_LNS_copy: a row *) + end; + at := Chunk.lines[i].at; cl := Chunk.lines[i].line; + INC(i); + end; + putB(2); putU(Chunk.chunks[c].start + Chunk.chunks[c].size - at); + putB(0); putU(1); putB(1); (* DW_LNE_end_sequence *) + end; + end; + patch4(lp, 0, lpLen - 4); +end; + +var + buf: ^U8; (* the places, being made *) + at, names, poolAt: INT; (* where the next number goes, the next name, the pool's start *) + +(* The name s, in the pool, and its offset from the pool's start, at at *) +proc putName(s: []U8); +begin + patch4(buf, at, names - poolAt); + COPY(buf[names..names + LEN(s)], s); + buf[names + LEN(s)] := 0; + names := names + LEN(s) + 1; + at := at + 4; +end; + +(* Whether chunk c is a live procedure, whose places Rt knows *) +proc isProc(c: INT): BOOL; +begin + return Chunk.chunks[c].live and (Chunk.chunks[c].sec = Chunk.secText) and (Chunk.chunks[c].home >= 0); +end; + +(* The places that Rt reads to say where a failed check or a signal + was, and what calls were under way: where the line table is in them, + where text starts and stops, the numbers of procedures and of their + variables (I64s); for each live procedure where it starts and stops, + the offset of its name, its first variable and how many it has, and + the registers of variables it saves, as bits of Gen's VarRegs, and + the frame offset they are saved at (U32s); for each variable the + offset of its name, its place in the frame and its kind, as + Parse's VarKind (U32s); then the names, each ending in a zero + byte; then the line table (makeLines), at linesOff. They are in no + order, since Rt looks at them only as the program stops. *) +proc makePlaces(start, stop: INT); +var + files, first, count: ^INT; + i, f, nfiles, np, nv, c, v: INT; +begin + files := ^INT(Scan.grab(Chunk.numLines * SIZE(INT) + SIZE(INT))); + first := ^INT(Scan.grab(Chunk.numChunks * SIZE(INT))); + count := ^INT(Scan.grab(Chunk.numChunks * SIZE(INT))); + for c := 0 to Chunk.numChunks - 1 do first[c] := 0; count[c] := 0; end; + for v := Chunk.numVarNotes - 1 to 0 by -1 do + first[Chunk.varNotes[v].chunk] := v; + INC(count[Chunk.varNotes[v].chunk]); + end; + nfiles := 0; poolAt := 0; np := 0; nv := 0; + for i := 0 to Chunk.numLines - 1 do + if Chunk.chunks[Chunk.lines[i].chunk].live then + f := 0; + while (f < nfiles) and (files[f] # Chunk.lines[i].path) do INC(f); end; + if f = nfiles then + files[f] := Chunk.lines[i].path; + INC(nfiles); + end; + end; + end; + makeLines(files, nfiles); + for c := 0 to Chunk.numChunks - 1 do + if isProc(c) then + INC(np); + poolAt := poolAt + LEN(Chunk.chunkName(c)) + 1; + for v := first[c] to first[c] + count[c] - 1 do + poolAt := poolAt + LEN(Scan.nameOf(Chunk.varNotes[v].name)) + 1; + end; + nv := nv + count[c]; + end; + end; + buf := Scan.grab(40 + 28 * np + 12 * nv + poolAt + lpLen); + (* the pool of names starts at poolAt, the line table after it *) + poolAt := 40 + 28 * np + 12 * nv; + names := poolAt; + at := 40; + v := 0; + for c := 0 to Chunk.numChunks - 1 do + if isProc(c) then + patch4(buf, at, Chunk.chunks[c].adr); + patch4(buf, at + 4, Chunk.chunks[c].adr + Chunk.chunks[c].size); + at := at + 8; + putName(Chunk.chunkName(c)); + patch4(buf, at, v); + patch4(buf, at + 4, count[c]); + patch4(buf, at + 8, Chunk.chunks[c].saveMask); + patch4(buf, at + 12, Chunk.chunks[c].saveAt); + at := at + 16; + v := v + count[c]; + end; + end; + for c := 0 to Chunk.numChunks - 1 do + if isProc(c) then + for v := first[c] to first[c] + count[c] - 1 do + putName(Scan.nameOf(Chunk.varNotes[v].name)); + patch4(buf, at, Chunk.varNotes[v].off); + patch4(buf, at + 4, Chunk.varNotes[v].kind); + at := at + 8; + end; + end; + end; + linesOff := names; + linesSize := lpLen; + COPY(buf[names..names + lpLen], lp[0..lpLen]); + patch8(buf, 0, linesOff); + patch8(buf, 8, start); + patch8(buf, 16, stop); + patch8(buf, 24, np); + patch8(buf, 32, nv); + Chunk.setData(placesChunk, buf, names + lpLen, 8); +end; + +(* Places the live chunks, leaving roExtra bytes at the end of rodata + and dynSize at the start of the writable segment. The segments follow + each other in the file with no padding, and each is loaded a page + further from its file offset than the one before: rodata at Base + + Page + roOff, the writable segment at Base + 2 * Page + bssOff. So an + address and its offset agree within a page, as the loader needs, and + no two segments, with their different permissions, share a page. + The bss of a program without the loader's table has no bytes in the + file, and starts on a page of its own. *) +proc linkAll*(headerSize, roExtra, dynSize: INT); +var c, f, at, p, e, v: INT; +begin + textOff := (headerSize + 31) div 32 * 32; (* as each code chunk is *) + e := place(Chunk.secText, Base + textOff); + textSize := e - (Base + textOff); + if placesChunk >= 0 then makePlaces(Base + textOff, e); end; + roOff := (textOff + textSize + 31) div 32 * 32; + roAdr := Base + Page + roOff; + e := place(Chunk.secRodata, roAdr); + extraAdr := (e + 7) div 8 * 8; + if roExtra > 0 then e := extraAdr + roExtra; end; + roSize := e - roAdr; + bssOff := (roOff + roSize + 31) div 32 * 32; + if dynSize > 0 then + bssAdr := Base + 2 * Page + bssOff; + else + bssAdr := (roAdr + roSize + Page - 1) div Page * Page; + end; + e := place(Chunk.secBss, bssAdr + dynSize); + bssSize := e - bssAdr; + + textImg := Scan.grab(textSize + 1); + (* the gaps between code chunks are int3, a trap if ever run *) + for p := 0 to textSize do textImg[p] := 0CCH; end; + roImg := Scan.grab(roSize + 1); + for p := 0 to roSize do roImg[p] := 0; end; + for c := 0 to Chunk.numChunks - 1 do + if Chunk.chunks[c].live then + if Chunk.chunks[c].sec = Chunk.secText then + p := Chunk.chunks[c].adr - (Base + textOff); + COPY(textImg[p..p + Chunk.chunks[c].size], Chunk.text[Chunk.chunks[c].start..Chunk.chunks[c].start + Chunk.chunks[c].size]); + for f := Chunk.chunks[c].firstFix to Chunk.chunks[c].firstFix + Chunk.chunks[c].numFix - 1 do + at := Chunk.fixups[f].at - Chunk.chunks[c].start; + (* rel32: from the end of the field to the target *) + v := Chunk.chunks[Chunk.fixups[f].chunk].adr + Chunk.fixups[f].addend + - (Chunk.chunks[c].adr + at + 4); + patch4(textImg, p + at, v); + end; + elsif Chunk.chunks[c].sec = Chunk.secRodata then + p := Chunk.chunks[c].adr - roAdr; + COPY(roImg[p..p + Chunk.chunks[c].size], Chunk.rodata[Chunk.chunks[c].start..Chunk.chunks[c].start + Chunk.chunks[c].size]); + for f := Chunk.chunks[c].firstFix to Chunk.chunks[c].firstFix + Chunk.chunks[c].numFix - 1 do + patch8(roImg, p + Chunk.dataFixups[f].at, + Chunk.chunks[Chunk.dataFixups[f].chunk].adr + Chunk.dataFixups[f].addend); + end; + end; + end; + end; +end; + +begin + placesChunk := -1; +end Link. diff --git a/self/README.md b/self/README.md index 1eb0893..9154cfe 100644 --- a/self/README.md +++ b/self/README.md @@ -15,7 +15,13 @@ pseudo-random script of calls on its side and prints all it made or answered (`Sym` also ends, as an argument says, in the error of a name declared twice or of too many scopes): the output, the messages and -the status must be the same. +the status must be the same. `Link` and `Elf` are tested by +`test/LinkDump`, which makes a program of chunks by a script and writes +it as a static, a dynamic and a stripped executable, which must be the +same file; `X64` by `test/X64Dump`, every encoder with operands from a +script, bytes, fixups and listing, and by `test/AsmDump` on the files +`test/genasm.py` makes: a long run of every instruction the assembler +knows, and a file for each of its errors. `check.sh` builds a dumper for each side, `test/ScanDump.pas` over the seed's units and `test/ScanDump.raz` over these, and has both read the @@ -59,6 +65,21 @@ `setAdr`, `setReals`, `setSaves`, `setCurFile`, and `rewindTo` for gen's `Redo` and `Rewind`), and `Sym` has `setCurModule`. `Scan.grab` is exported for the memory they all take. +- **No `continue`.** The seed's loops that skip to the next round + (`MarkLive`, the line program, the assembler's statements) have the + rest of the body in an `else`, or in a procedure of its own. +- **`X64`.** `code` of `Chunk` being reserved, its text is `Chunk.text`; + `Say` and the rest of the encoder keep their names, in lower case. + `ConstFn`, the parser's reader of a constant, returns an `ERROR` too, + and `assemble` returns what it passes up. `mem` marks an offset beyond + 32 bits and goes on, since an operand has nowhere to return an error + to; the compile ends with the message shown. The listing's text is + made by `Diag.say`, which keeps it, and only when `-S` asks for it. +- **`Link` and `Elf`.** What `raz.pas` set there has a setter each: + `Link.setPlaces`, `Elf.needLib`, `noLibs`, `setMainPath`, + `setStripped` and `X64.setListing`. The file is written by + `Files.write` and made executable by `Sys.chmod`, in place of one + `open` with mode 755 (which the umask would trim). - **No bit cast.** A real's bits and back go through a pointer. - **Speed.** On the 348,025 lines of `test/genbench.py`, 7.6 MB, the seed's scanner takes 75 ms and this one 74. It took 121 at first. diff --git a/self/Scan.raz b/self/Scan.raz index 570b8d4..a12becf 100644 --- a/self/Scan.raz +++ b/self/Scan.raz @@ -120,6 +120,16 @@ return p; end; +(* p, which holds used bytes, moved to a block of size bytes *) +proc regrab*(p: ^U8; used, size: INT): ^U8; +var q: ^U8; +begin + q := grab(size); + COPY(q[0..used], p[0..used]); + Mem.free(Heap.heap, p); + return q; +end; + (* n zeroed words *) proc words64(n: INT): ^INT; var p: ^INT; i: INT; diff --git a/self/X64.raz b/self/X64.raz new file mode 100644 index 0000000..a9a28bd --- /dev/null +++ b/self/X64.raz @@ -0,0 +1,1472 @@ +(* X64: machine code for x86-64. + + The encoder writes the instructions the code generator needs, and + no others, into the text of Chunk. Registers are numbered as the + hardware numbers them. Jumps within a procedure are patched here, as + soon as their target is known. + + Depends on: Scan, for errors and the assembler's symbols; Diag, for + positions; Chunk for the code buffer and fixups. + Leaves out: choosing instructions; that is Gen. + + The seed's `Mem` that is too large an offset is marked and the code + goes on, since a function that makes an operand has no place to give + an error back from; the compile ends with the error shown. *) +module X64; +import Out, Fmt, Heap, Buf, Str, Diag, Scan, Chunk; + +const + RAX* = 0; RCX* = 1; RDX* = 2; RBX* = 3; RSP* = 4; RBP* = 5; RSI* = 6; RDI* = 7; + R8* = 8; R9* = 9; R10* = 10; R11* = 11; R12* = 12; R13* = 13; R14* = 14; R15* = 15; + RIP* = -1; (* a base meaning rip-relative, to a chunk *) + NoIndex* = -1; + + (* condition codes *) + ccB* = 2; ccAE* = 3; ccE* = 4; ccNE* = 5; ccBE* = 6; ccA* = 7; ccS* = 8; + ccP* = 10; ccNP* = 11; ccL* = 12; ccGE* = 13; ccLE* = 14; ccG* = 15; + + (* group 1 operations, the /digit of 81 and 83 *) + aluAdd* = 0; aluOr* = 1; aluAnd* = 4; aluSub* = 5; aluXor* = 6; aluCmp* = 7; + + (* the /digit of D3 and C1 *) + shShl* = 4; shShr* = 5; shSar* = 7; + + NoLabel* = -1; + +type + Mem* = record + base*: INT; (* a register, or RIP *) + index*: INT; (* a register, or NoIndex *) + scale*: INT; (* 1, 2, 4 or 8 *) + disp*: INT; + chunk*: INT; (* with RIP: the chunk addressed *) + end; + + (* The parser's reader of an integer constant in a code procedure: a + whole expression, or, when whole is false, a single factor *) + ConstFn* = proc(whole: BOOL): (I64, ERROR); + + (* The text of the instruction that starts at at, for the listing *) + Said = record + at: INT; + text: []U8; + end; + +var + listing*: BOOL; (* -S: each instruction's text is kept, for list *) + said: ^Said; + numSaid, saidCap: INT; + +proc setListing*(yes: BOOL); +begin + listing := yes; +end; + +(* Operands *) + +proc mem*(base: INT; disp: I64): Mem; +var m: Mem; +begin + if (disp < -2147483648) or (disp > 2147483647) then + _ := Scan.mark("an offset beyond 32 bits"); + end; + m.base := base; m.index := NoIndex; m.scale := 1; + m.disp := INT(disp); m.chunk := -1; + return m; +end; + +proc memRip*(chunk: INT; disp: INT): Mem; +var m: Mem; +begin + m.base := RIP; m.index := NoIndex; m.scale := 1; + m.disp := disp; m.chunk := chunk; + return m; +end; + +proc memIdx*(base, index, scale: INT; disp: I64): Mem; +var m: Mem; +begin + m := mem(base, disp); + m.index := index; + m.scale := scale; + return m; +end; + +(* The address of the code about to be written, as an operand *) +proc here*: Mem; +begin + return memRip(Chunk.curChunk, Chunk.pc - Chunk.chunks[Chunk.curChunk].start); +end; + +(* Encoding. An instruction is: a legacy prefix, REX, the opcode, ModRM, + SIB and displacement. Opcodes of more than one byte are given with + their first byte in the low eight bits. *) + +proc opcode(op: INT); +begin + repeat + Chunk.put1(op & 0FFH); + op := op shr 8; + until op = 0; +end; + +(* The legacy prefix pfx, if any, and REX: wide is REX.W; byte4 says + a byte register of 4 to 7 is used, spl to dil, which exist only with + a REX prefix. *) +proc prefix(pfx: INT; w: BOOL; reg, index, base: INT; byte4: BOOL); +var rex: INT; +begin + if pfx # 0 then Chunk.put1(pfx); end; + rex := 0; + if w then rex := rex | 8; end; + if reg >= 8 then rex := rex | 4; end; + if index >= 8 then rex := rex | 2; end; + if base >= 8 then rex := rex | 1; end; + if (rex # 0) or byte4 then Chunk.put1(40H | rex); end; +end; + +(* op reg, [mem] *) +proc opM(pfx: INT; w: BOOL; op, reg: INT; m: Mem; byteReg: BOOL); +var md, b, sc: INT; +begin + byteReg := byteReg and (reg >= 4) and (reg <= 7); + if m.base = RIP then + prefix(pfx, w, reg, NoIndex, 0, byteReg); + else + prefix(pfx, w, reg, m.index, m.base, byteReg); + end; + opcode(op); + reg := reg & 7; + if m.base = RIP then + Chunk.put1((reg shl 3) | 5); + (* mod 00 with r/m 101 is rip + disp32. The displacement counts + from the end of the instruction, and the fixup takes it to end + with these four bytes: an instruction with an immediate after + them, aluMI's or storeI's, takes the immediate's size off disp + first (the assembler can't name a chunk). *) + Chunk.addFixup(Chunk.pc, m.chunk, m.disp); + Chunk.put4(0); + return; + end; + b := m.base & 7; + (* mod 00 takes no displacement, but with r/m 101 (RBP or R13) it means + rip-relative, or disp32 under a SIB byte, so those bases take a + zero disp8 *) + if (m.disp = 0) and (b # RBP) then + md := 0; + elsif (m.disp >= -128) and (m.disp <= 127) then + md := 1; + else + md := 2; + end; + (* r/m 100 (RSP or R12) means a SIB byte follows, so those bases need + one, with index 100 meaning none *) + if (m.index # NoIndex) or (b = RSP) then + Chunk.put1((md shl 6) | (reg shl 3) | 4); + if m.scale = 1 then sc := 0; elsif m.scale = 2 then sc := 1; elsif m.scale = 4 then sc := 2; else sc := 3; end; + if m.index = NoIndex then + Chunk.put1((sc shl 6) | (4 shl 3) | b); + else + Chunk.put1((sc shl 6) | ((m.index & 7) shl 3) | b); + end; + else + Chunk.put1((md shl 6) | (reg shl 3) | b); + end; + if md = 1 then + Chunk.put1(m.disp); + elsif md = 2 then + Chunk.put4(m.disp); + end; +end; + +(* op reg, rm (both registers) *) +proc opR(pfx: INT; w: BOOL; op, reg, rm: INT; byteReg: BOOL); +begin + prefix(pfx, w, reg, NoIndex, rm, byteReg and (((reg >= 4) and (reg <= 7)) or ((rm >= 4) and (rm <= 7)))); + opcode(op); + Chunk.put1(0C0H | ((reg & 7) shl 3) | (rm & 7)); +end; + +(* The listing: the text of each instruction, as it is made *) + +(* How many instructions the listing has, and back to n of them, for + code made again *) +proc saidCount*: INT; +begin + return numSaid; +end; + +proc unsay*(n: INT); +begin + numSaid := n; +end; + +proc sayAt*(at: INT; s: []U8); +begin + if not listing then return; end; + if numSaid = saidCap then + said := ^Said(Scan.regrab(^U8(said), numSaid * SIZE(Said), (saidCap * 2 + 1024) * SIZE(Said))); + saidCap := saidCap * 2 + 1024; + end; + said[numSaid].at := at; + said[numSaid].text := s; + INC(numSaid); +end; + +(* The text of the instruction about to be written *) +proc say*(s: []U8); +begin + sayAt(Chunk.pc, s); +end; + +(* The text of the instruction at at, said again, as when its operand is + patched *) +proc restate*(at: INT; s: []U8); +var i: INT; +begin + i := numSaid - 1; + while (i >= 0) and (said[i].at # at) do DEC(i); end; + if i >= 0 then said[i].text := s; end; +end; + +const + RegNames: [4][16][]U8 = [ + ["rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", + "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"], + ["eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", + "r8d", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d"], + ["ax", "cx", "dx", "bx", "sp", "bp", "si", "di", + "r8w", "r9w", "r10w", "r11w", "r12w", "r13w", "r14w", "r15w"], + ["al", "cl", "dl", "bl", "spl", "bpl", "sil", "dil", + "r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b"]]; + CondNames*: [16][]U8 = ["o", "no", "b", "ae", "e", "ne", "be", "a", "s", "ns", "p", "np", "l", "ge", "le", "g"]; + AluNames: [8][]U8 = ["add", "or", "adc", "sbb", "and", "sub", "xor", "cmp"]; + ShiftNames: [8][]U8 = ["rol", "ror", "rcl", "rcr", "shl", "shr", "sal", "sar"]; + UnaryNames: [8][]U8 = ["", "", "not", "neg", "mul", "imul", "div", "idiv"]; (* from 2 *) + +(* The name of register r, of size bytes *) +proc rnSized(r, size: INT): []U8; +begin + if size = 1 then return RegNames[3][r]; end; + if size = 2 then return RegNames[2][r]; end; + if size = 4 then return RegNames[1][r]; end; + return RegNames[0][r]; +end; + +proc rn(r: INT): []U8; +begin + return RegNames[0][r]; +end; + +proc xn(x: INT): []U8; +begin + return Diag.say("xmm{}", [Fmt.int(x)]); +end; + +(* A memory operand, with the size of what it holds, as the assembler + reads it *) +proc mnSized(m: Mem; size: INT): []U8; +var b: ^Buf.Buf; +begin + b := ^Buf.Buf(Scan.grab(SIZE(Buf.Buf))); + Buf.init(b, Heap.heap); + if size = 1 then Buf.str(b, "byte "); + elsif size = 2 then Buf.str(b, "word "); + elsif size = 4 then Buf.str(b, "dword "); + elsif size = 8 then Buf.str(b, "qword "); + end; + Buf.str(b, "["); + if m.base = RIP then Buf.str(b, Chunk.chunkName(m.chunk)); else Buf.str(b, rn(m.base)); end; + if m.index # NoIndex then Fmt.write(b, " + {} * {}", [Fmt.str(rn(m.index)), Fmt.int(m.scale)]); end; + if m.disp > 0 then + Fmt.write(b, " + {}", [Fmt.int(m.disp)]); + elsif m.disp < 0 then + Fmt.write(b, " - {}", [Fmt.int(-m.disp)]); + end; + Buf.str(b, "]"); + return Buf.bytes(b); +end; + +proc mn(m: Mem): []U8; +begin + return mnSized(m, 0); +end; + +(* "op a, b" and "op a" *) +proc text2(op, a, b: []U8): []U8; +begin + return Diag.say("{} {}, {}", [Fmt.str(op), Fmt.str(a), Fmt.str(b)]); +end; + +proc text1(op, a: []U8): []U8; +begin + return Diag.say("{} {}", [Fmt.str(op), Fmt.str(a)]); +end; + +(* v in decimal *) +proc num(v: INT): []U8; +begin + return Diag.say("{}", [Fmt.int(v)]); +end; + +proc movRR*(dst, src: INT); +begin + if listing then say(text2("mov", rn(dst), rn(src))); end; + opR(0, true, 89H, src, dst, false); +end; + +(* The operand-size prefix a size of 2 bytes takes *) +proc pfx16(size: INT): INT; +begin + if size = 2 then return 66H; end; + return 0; +end; + +(* The immediate of n bytes that ends an instruction *) +proc putImm(v, n: INT); +begin + if n = 4 then + Chunk.put4(v); + else + Chunk.put1(v & 0FFH); + if n = 2 then Chunk.put1((v shr 8) & 0FFH); end; + end; +end; + +(* op [m], v, on size bytes; v fits in them, or in 32 bits for 8 *) +proc aluMI*(op: INT; m: Mem; v, size: INT); +var n: INT; +begin + if listing then say(text2(AluNames[op], mnSized(m, size), num(v))); end; + if (size = 1) or ((v >= -128) and (v <= 127)) then + n := 1; + elsif size = 2 then + n := 2; + else + n := 4; + end; + if m.base = RIP then m.disp := m.disp - n; end; + if size = 1 then + opM(0, false, 80H, op, m, false); + elsif n = 1 then + opM(pfx16(size), size = 8, 83H, op, m, false); + else + opM(pfx16(size), size = 8, 81H, op, m, false); + end; + putImm(v, n); +end; + +(* mov [m], v, of size bytes; v fits in them, or in 32 bits for 8 *) +proc storeI*(m: Mem; v, size: INT); +var n: INT; +begin + if listing then say(text2("mov", mnSized(m, size), num(v))); end; + n := size; + if n > 4 then n := 4; end; + if m.base = RIP then m.disp := m.disp - n; end; + if size = 1 then + opM(0, false, 0C6H, 0, m, false); + else + opM(pfx16(size), size = 8, 0C7H, 0, m, false); + end; + putImm(v, n); +end; + +proc movRI*(r: INT; v: I64); +begin + if listing then + if v = 0 then + say(text2("xor", rnSized(r, 4), rnSized(r, 4))); + else + say(text2("mov", rn(r), Diag.say("{}", [Fmt.int(v)]))); + end; + end; + if (v >= -2147483648) and (v <= 2147483647) then + if v = 0 then + opR(0, false, 31H, r, r, false); (* xor r32, r32 *) + elsif v > 0 then (* mov r32, imm32 *) + prefix(0, false, 0, NoIndex, r, false); Chunk.put1(0B8H + (r & 7)); Chunk.put4(INT(v)); + else + opR(0, true, 0C7H, 0, r, false); Chunk.put4(INT(v)); (* sign-extended imm32 *) + end; + elsif (v > 0) and (v <= 0FFFFFFFFH) then + prefix(0, false, 0, NoIndex, r, false); Chunk.put1(0B8H + (r & 7)); Chunk.put4(INT(v)); + else + prefix(0, true, 0, NoIndex, r, false); Chunk.put1(0B8H + (r & 7)); Chunk.put8(v); + end; +end; + +proc load*(r: INT; m: Mem; size: INT; signed: BOOL); +begin + if listing then + if size = 8 then + say(text2("mov", rn(r), mn(m))); + elsif (size = 4) and not signed then + say(text2("mov", rnSized(r, 4), mn(m))); + elsif size = 4 then + say(text2("movsxd", rn(r), mnSized(m, 4))); + elsif signed then + say(text2("movsx", rn(r), mnSized(m, size))); + else + say(text2("movzx", rnSized(r, 4), mnSized(m, size))); + end; + end; + if size = 1 then + if signed then opM(0, true, 0BE0FH, r, m, false); else opM(0, false, 0B60FH, r, m, false); end; + elsif size = 2 then + if signed then opM(0, true, 0BF0FH, r, m, false); else opM(0, false, 0B70FH, r, m, false); end; + elsif size = 4 then + if signed then opM(0, true, 63H, r, m, false); else opM(0, false, 8BH, r, m, false); end; + else + opM(0, true, 8BH, r, m, false); + end; +end; + +proc store*(m: Mem; r: INT; size: INT); +begin + if listing then say(text2("mov", mn(m), rnSized(r, size))); end; + if size = 1 then + opM(0, false, 88H, r, m, true); + elsif size = 2 then + opM(66H, false, 89H, r, m, false); + elsif size = 4 then + opM(0, false, 89H, r, m, false); + else + opM(0, true, 89H, r, m, false); + end; +end; + +proc lea*(r: INT; m: Mem); +begin + if listing then say(text2("lea", rn(r), mn(m))); end; + opM(0, true, 8DH, r, m, false); +end; + +proc alu*(op, dst, src: INT); +begin + if listing then say(text2(AluNames[op], rn(dst), rn(src))); end; + opR(0, true, (op shl 3) | 1, src, dst, false); +end; + +proc aluI*(op, r: INT; v: INT); +begin + if listing then say(text2(AluNames[op], rn(r), num(v))); end; + if (v >= -128) and (v <= 127) then + opR(0, true, 83H, op, r, false); Chunk.put1(v); + else + opR(0, true, 81H, op, r, false); Chunk.put4(v); + end; +end; + +(* op r, [m] *) +proc aluM*(op, r: INT; m: Mem); +begin + if listing then say(text2(AluNames[op], rn(r), mn(m))); end; + opM(0, true, (op shl 3) | 3, r, m, false); +end; + +proc imul*(dst, src: INT); +begin + if listing then say(text2("imul", rn(dst), rn(src))); end; + opR(0, true, 0AF0FH, dst, src, false); +end; + +proc imulI*(r: INT; v: INT); +begin + if listing then say(Diag.say("imul {}, {}, {}", [Fmt.str(rn(r)), Fmt.str(rn(r)), Fmt.int(v)])); end; + opR(0, true, 69H, r, r, false); + Chunk.put4(v); +end; + +proc shift*(op, r: INT); +begin + if listing then say(text2(ShiftNames[op], rn(r), "cl")); end; + opR(0, true, 0D3H, op, r, false); +end; + +proc shiftI*(op, r, n: INT); +begin + if listing then say(text2(ShiftNames[op], rn(r), num(n))); end; + opR(0, true, 0C1H, op, r, false); + Chunk.put1(n); +end; + +(* F7 /ext: 2 not, 3 neg, 6 div, 7 idiv *) +proc unary*(ext, r: INT); +begin + if listing then say(text1(UnaryNames[ext], rn(r))); end; + opR(0, true, 0F7H, ext, r, false); +end; + +proc cqo*; +begin + if listing then say("cqo"); end; + Chunk.put1(48H); Chunk.put1(99H); +end; + +(* Brings a value of size bytes in r to 64 bits, by its sign or zeros. *) +proc extend*(r, size: INT; signed: BOOL); +begin + if listing then + if size = 4 then + if signed then + say(text2("movsxd", rn(r), rnSized(r, 4))); + else + say(text2("mov", rnSized(r, 4), rnSized(r, 4))); + end; + elsif signed then + say(text2("movsx", rn(r), rnSized(r, size))); + else + say(text2("movzx", rnSized(r, 4), rnSized(r, size))); + end; + end; + if size = 1 then + if signed then opR(0, true, 0BE0FH, r, r, true); else opR(0, false, 0B60FH, r, r, true); end; + elsif size = 2 then + if signed then opR(0, true, 0BF0FH, r, r, false); else opR(0, false, 0B70FH, r, r, false); end; + elsif size = 4 then + if signed then opR(0, true, 63H, r, r, false); else opR(0, false, 89H, r, r, false); end; + end; +end; + +(* r := 1 if the condition holds, else 0 *) +proc setCC*(cc, r: INT); +begin + if listing then say(text1(Diag.say("set{}", [Fmt.str(CondNames[cc])]), rnSized(r, 1))); end; + opR(0, false, 900FH + (cc shl 8), 0, r, true); + if listing then say(text2("movzx", rnSized(r, 4), rnSized(r, 1))); end; + opR(0, false, 0B60FH, r, r, true); +end; + +proc testRR*(a, b: INT); +begin + if listing then say(text2("test", rn(a), rn(b))); end; + opR(0, true, 85H, b, a, false); +end; + +proc push*(r: INT); +begin + if listing then say(text1("push", rn(r))); end; + if r >= 8 then Chunk.put1(41H); end; + Chunk.put1(50H + (r & 7)); +end; + +proc pop*(r: INT); +begin + if listing then say(text1("pop", rn(r))); end; + if r >= 8 then Chunk.put1(41H); end; + Chunk.put1(58H + (r & 7)); +end; + +proc callChunk*(c: INT); +begin + if listing then say(text1("call", Chunk.chunkName(c))); end; + Chunk.put1(0E8H); + Chunk.addFixup(Chunk.pc, c, 0); + Chunk.put4(0); +end; + +proc callBack*(target: INT); +begin + if listing then say("call"); end; + Chunk.put1(0E8H); + Chunk.put4(target - (Chunk.pc + 4)); +end; + +proc callR*(r: INT); +begin + if listing then say(text1("call", rn(r))); end; + opR(0, false, 0FFH, 2, r, false); +end; + +proc jmpR*(r: INT); +begin + if listing then say(text1("jmp", rn(r))); end; + opR(0, false, 0FFH, 4, r, false); +end; + +proc callM*(m: Mem); +begin + if listing then say(text1("call", mn(m))); end; + opM(0, false, 0FFH, 2, m, false); +end; + +proc ret*; +begin + if listing then say("ret"); end; + Chunk.put1(0C3H); +end; + +proc leave*; +begin + say("leave"); Chunk.put1(0C9H); +end; + +proc syscall*; +begin + say("syscall"); Chunk.put1(0FH); Chunk.put1(05H); +end; + +proc mfence*; +begin + say("mfence"); Chunk.put1(0FH); Chunk.put1(0AEH); Chunk.put1(0F0H); +end; + +proc ud2*; +begin + say("ud2"); Chunk.put1(0FH); Chunk.put1(0BH); +end; + +(* Code made up to a multiple of n bytes with no-ops, the fewest: the + long forms of nop, of up to 8 bytes, that x86 decodes as one *) +proc align*(n: INT); +const + Nops: [8][]U8 = ["\x90", "\x66\x90", "\x0F\x1F\x00", "\x0F\x1F\x40\x00", + "\x0F\x1F\x44\x00\x00", "\x66\x0F\x1F\x44\x00\x00", "\x0F\x1F\x80\x00\x00\x00\x00", + "\x0F\x1F\x84\x00\x00\x00\x00\x00"]; +var k, i: INT; +begin + while Chunk.pc mod n # 0 do + k := n - Chunk.pc mod n; + if k > 8 then k := 8; end; + say("nop"); + for i := 0 to k - 1 do Chunk.put1(INT(Nops[k - 1][i])); end; + end; +end; + +proc repMovsb*; +begin + say("rep movsb"); Chunk.put1(0F3H); Chunk.put1(0A4H); +end; + +(* the direction flag, which has rep movsb go down, and back up *) +proc std*; +begin + say("std"); Chunk.put1(0FDH); +end; + +proc cld*; +begin + say("cld"); Chunk.put1(0FCH); +end; + +proc repStosb*; +begin + say("rep stosb"); Chunk.put1(0F3H); Chunk.put1(0AAH); +end; + +proc repeCmpsb*; +begin + say("repe cmpsb"); Chunk.put1(0F3H); Chunk.put1(0A6H); +end; + +proc lockCmpxchg*(m: Mem; r: INT); +begin + if listing then say(text2("lock cmpxchg", mn(m), rn(r))); end; + Chunk.put1(0F0H); + opM(0, true, 0B10FH, r, m, false); +end; + +proc xchg*(m: Mem; r: INT); +begin + if listing then say(text2("xchg", mn(m), rn(r))); end; + opM(0, true, 87H, r, m, false); +end; + +proc lockXadd*(m: Mem; r: INT); +begin + if listing then say(text2("lock xadd", mn(m), rn(r))); end; + Chunk.put1(0F0H); + opM(0, true, 0C10FH, r, m, false); +end; + +proc movqXR*(x, r: INT); +begin + if listing then say(text2("movq", xn(x), rn(r))); end; + opR(66H, true, 6E0FH, x, r, false); +end; + +proc movqRX*(r, x: INT); +begin + if listing then say(text2("movq", rn(r), xn(x))); end; + opR(66H, true, 7E0FH, x, r, false); +end; + +(* movaps: all of xmm y to xmm x, the shortest move between two *) +proc movX*(x, y: INT); +begin + if listing then say(text2("movaps", xn(x), xn(y))); end; + opR(0, false, 280FH, x, y, false); +end; + +(* The prefix of a real instruction, and the end of its name: sd, or ss for single *) +proc realPfx(single: BOOL): INT; +begin + if single then return 0F3H; end; + return 0F2H; +end; + +proc realEnd(single: BOOL): []U8; +begin + if single then return "ss"; end; + return "sd"; +end; + +(* The real instructions take single: F32 (ss) rather than F64 (sd) *) +proc movsXM*(x: INT; m: Mem; single: BOOL); +begin + if listing then say(text2(Diag.say("movs{}", [Fmt.str(realEnd(single)[1..2])]), xn(x), mn(m))); end; + opM(realPfx(single), false, 100FH, x, m, false); +end; + +proc movsMX*(m: Mem; x: INT; single: BOOL); +begin + if listing then say(text2(Diag.say("movs{}", [Fmt.str(realEnd(single)[1..2])]), mn(m), xn(x))); end; + opM(realPfx(single), false, 110FH, x, m, false); +end; + +proc sseName(op: INT; single: BOOL): []U8; +begin + if op = 58H then return Diag.say("add{}", [Fmt.str(realEnd(single))]); end; + if op = 59H then return Diag.say("mul{}", [Fmt.str(realEnd(single))]); end; + if op = 5CH then return Diag.say("sub{}", [Fmt.str(realEnd(single))]); end; + if op = 5EH then return Diag.say("div{}", [Fmt.str(realEnd(single))]); end; + return Diag.say("cvt{}2{}", [Fmt.str(realEnd(single)), Fmt.str(realEnd(not single))]); +end; + +(* 58 add, 59 mul, 5C sub, 5E div, 5A convert *) +proc sse*(op, x, y: INT; single: BOOL); +begin + if listing then say(text2(sseName(op, single), xn(x), xn(y))); end; + opR(realPfx(single), false, 0FH | (op shl 8), x, y, false); +end; + +(* The same, its right operand in memory: addsd x, [m] *) +proc sseM*(op, x: INT; m: Mem; single: BOOL); +begin + if listing then say(text2(sseName(op, single), xn(x), mn(m))); end; + opM(realPfx(single), false, 0FH | (op shl 8), x, m, false); +end; + +proc ucomis*(x, y: INT; single: BOOL); +begin + if listing then say(text2(Diag.say("ucomi{}", [Fmt.str(realEnd(single))]), xn(x), xn(y))); end; + if single then opR(0, false, 2E0FH, x, y, false); else opR(66H, false, 2E0FH, x, y, false); end; +end; + +proc cvtsi2s*(x, r: INT; single: BOOL); +begin + if listing then say(text2(Diag.say("cvtsi2{}", [Fmt.str(realEnd(single))]), xn(x), rn(r))); end; + opR(realPfx(single), true, 2A0FH, x, r, false); +end; + +proc cvtts2si*(r, x: INT; single: BOOL); +begin + if listing then say(text2(Diag.say("cvtt{}2si", [Fmt.str(realEnd(single))]), rn(r), xn(x))); end; + opR(realPfx(single), true, 2C0FH, r, x, false); +end; + +proc btc*(r, bit: INT); +begin + if listing then say(text2("btc", rn(r), num(bit))); end; + opR(0, true, 0BA0FH, 7, r, false); + Chunk.put1(bit); +end; + +(* Jumps. A label not yet placed is the chain of the jumps to it, each + rel32 field holding the position of the one before, NoLabel ending + it. Placing the label walks the chain and patches each. *) + +proc jmp*(var L: INT); +begin + if listing then say("jmp"); end; + Chunk.put1(0E9H); + Chunk.put4(L); + L := Chunk.pc - 4; +end; + +proc jcc*(cc: INT; var L: INT); +begin + if listing then say(Diag.say("j{}", [Fmt.str(CondNames[cc])])); end; + Chunk.put1(0FH); Chunk.put1(80H + cc); + Chunk.put4(L); + L := Chunk.pc - 4; +end; + +proc jmpBack*(target: INT); +begin + if listing then say("jmp"); end; + Chunk.put1(0E9H); + Chunk.put4(target - (Chunk.pc + 4)); +end; + +proc jccBack*(cc, target: INT); +begin + if listing then say(Diag.say("j{}", [Fmt.str(CondNames[cc])])); end; + Chunk.put1(0FH); Chunk.put1(80H + cc); + Chunk.put4(target - (Chunk.pc + 4)); +end; + +proc fixLinkTo*(L, target: INT); +var next: INT; +begin + while L # NoLabel do + next := Chunk.get4At(L); + Chunk.put4At(L, target - (L + 4)); + L := next; + end; +end; + +proc fixLink*(L: INT); +begin + fixLinkTo(L, Chunk.pc); +end; + +(* If the last instruction made is a jmp to L, it is taken back, since L + is to be placed just after it: a return at the end of a procedure + needn't jump to the code that returns. L is the place of the latest + jump's 4-byte field, so the last instruction is that jump when L is + 4 bytes back and an E9 byte (jmp) is before it; a jcc's field follows + the bytes 0F 8x, never E9. L then becomes the next jump on the chain, + which the field held. The caller must place L next, before anything + can have noted where the jmp ended. *) +proc dropJumpTo*(var L: INT); +begin + if (L = NoLabel) or (L # Chunk.pc - 4) or (Chunk.text[L - 1] # 0E9H) then return; end; + L := Chunk.get4At(L); + Chunk.takeBack(5); + if listing and (numSaid > 0) and (said[numSaid - 1].at = Chunk.pc) then DEC(numSaid); end; +end; + +(* The jumps of chains L1 and L2, as one chain: each jump's field holds + the next one's place until it is fixed, the last NoLabel *) +proc joinLinks*(L1, L2: INT): INT; +var L: INT; +begin + if L2 = NoLabel then return L1; end; + if L1 # NoLabel then + L := L2; + while Chunk.get4At(L) # NoLabel do L := Chunk.get4At(L); end; + Chunk.put4At(L, L1); + end; + return L2; +end; + +(* The assembler, for code procedures: x86-64 in Intel's syntax as NASM + writes it (report, appendix A). It reads instructions with the + scanner up to end, and encodes them with opM and opR; constants are + read by the parser's constExpr. *) + +const + NoBase = -3; (* a memory operand's base, not yet read *) + +type + OpKind = (oReg, oXmm, oMem, oImm); + Operand = record + kind: OpKind; + r, size: INT; (* oReg, oXmm: the register and its size; oMem: its size, or 0 *) + m: Mem; + v: I64; (* oImm *) + end; + +(* The current symbol as a word: an identifier, or a reserved word that + is also an instruction *) +proc asmWord: []U8; +begin + match Scan.tok of + | sIdent: return Scan.nameOf(Scan.id); + | sAnd: return "and"; + | sOr: return "or"; + | sXor: return "xor"; + | sNot: return "not"; + | sDiv: return "div"; + | sShl: return "shl"; + | sShr: return "shr"; + | else: return ""; + end; +end; + +(* Whether w names a register: rax, eax, ax, al and so on, or xmm0 to + xmm15 (size 16); r and size are set if so *) +proc isReg(w: []U8; r, size: ^INT): BOOL; +const Sizes: [4]INT = [8, 4, 2, 1]; +var i, j, n, d: INT; +begin + for i := 0 to 3 do + for j := 0 to 15 do + if RegNames[i][j] = w then r^ := j; size^ := Sizes[i]; return true; end; + end; + end; + size^ := 16; + if not Str.hasPrefix(w, "xmm") or (LEN(w) <= 3) then return false; end; + (* the seed read the two bytes after xmm as a number, whatever follows *) + n := LEN(w) - 3; + if n > 2 then n := 2; end; + r^ := 0; + for i := 0 to n - 1 do + d := INT(w[3 + i]) - 48; + if (d < 0) or (d > 9) then return false; end; + r^ := r^ * 10 + d; + end; + return r^ <= 15; +end; + +(* Which word of list, a list of words each with a space either side, + w is, from 0; -1 if none *) +proc wordIndex(w: []U8; list: []U8): INT; +var i, n, start: INT; +begin + n := 0; + start := 1; + for i := 1 to LEN(list) - 1 do + if list[i] = ' ' then + if (i - start = LEN(w)) and (list[start..i] = w) then return n; end; + INC(n); + start := i + 1; + end; + end; + return -1; +end; + +(* w from byte from on, at most n bytes of it, as copy does *) +proc part(w: []U8; from, n: INT): []U8; +var e: INT; +begin + e := from + n; + if e > LEN(w) then e := LEN(w); end; + if from >= e then return ""; end; + return w[from..e]; +end; + +(* The condition a name ends in: e of je, nz of jnz *) +proc cond(w: []U8): INT; +const + Alias: [12][]U8 = ["c", "nae", "nc", "nb", "z", "nz", "na", "nbe", "nge", "nl", "ng", "nle"]; + AliasCc: [12]INT = [2, 2, 3, 3, 4, 5, 6, 7, 12, 13, 14, 15]; +var i: INT; +begin + for i := 0 to 15 do + if CondNames[i] = w then return i; end; + end; + for i := 0 to 11 do + if Alias[i] = w then return AliasCc[i]; end; + end; + return -1; +end; + +proc operand(o: ^Operand; constExpr: ConstFn): ERROR; +var w: []U8; r, size, sz: INT; st: Scan.State; v: I64; isR, wasMinus: BOOL; +begin + o^ := {}; + w := asmWord(); + sz := 0; + if w = "byte" then sz := 1; + elsif w = "word" then sz := 2; + elsif w = "dword" then sz := 4; + elsif w = "qword" then sz := 8; + end; + if sz # 0 then Scan.next; w := asmWord(); end; + if Scan.tok = Scan.sLbrak then + (* [base + index * scale + disp], the displacement last *) + Scan.next; + o^.kind := oMem; o^.size := sz; + o^.m := mem(NoBase, 0); + repeat + if isReg(asmWord(), ADR(r), ADR(size)) and (size = 8) then + Scan.next; + (* the scale is a single number or constant: a whole expression + would take in the displacement after it, as 4 + 16 in + [rdi + rsi * 4 + 16] *) + if Scan.tok = Scan.sTimes then + Scan.next; + o^.m.index := r; + v := try constExpr(false); + o^.m.scale := INT(v); + elsif o^.m.base = NoBase then + o^.m.base := r; + else + o^.m.index := r; o^.m.scale := 1; + end; + else + v := try constExpr(true); + o^.m.disp := o^.m.disp + INT(v); + end; + if (Scan.tok # Scan.sPlus) and (Scan.tok # Scan.sMinus) then break; end; + wasMinus := Scan.tok = Scan.sMinus; + Scan.saveScan(st); + Scan.next; + isR := isReg(asmWord(), ADR(r), ADR(size)); + if not isR and wasMinus then Scan.restoreScan(st); end; + until false; + if (Scan.tok # Scan.sRbrak) or (o^.m.base = NoBase) + or not ((o^.m.scale = 1) or (o^.m.scale = 2) or (o^.m.scale = 4) or (o^.m.scale = 8)) then + return Scan.mark("expected a memory operand, [base + index * scale + disp]"); + end; + Scan.next; + elsif isReg(w, ADR(o^.r), ADR(o^.size)) then + if o^.size = 16 then o^.kind := oXmm; else o^.kind := oReg; end; + Scan.next; + else + o^.kind := oImm; + o^.v := try constExpr(true); + end; + return nil; +end; + +(* op with register reg and the register or memory operand o *) +proc rm(pfx: INT; w: BOOL; op, reg: INT; o: Operand; byteReg: BOOL); +begin + if o.kind = oMem then opM(pfx, w, op, reg, o.m, byteReg); else opR(pfx, w, op, reg, o.r, byteReg); end; +end; + +proc putImmV(v: I64; size: INT); +begin + if size = 1 then + Chunk.put1(INT(v & 0FFH)); + elsif size = 2 then + Chunk.put1(INT(v & 0FFH)); Chunk.put1(INT((v shr 8) & 0FFH)); + else + Chunk.put4(INT(v & 0FFFFFFFFH)); + end; +end; + +const + Alus = " add or adc sbb and sub xor cmp "; + Unaries = " not neg mul imul div idiv "; + Shifts = " rol ror rcl rcr shl shr sal sar "; + SseOps = " sqrt add mul sub min div max "; + SseCodes: [7]INT = [51H, 58H, 59H, 5CH, 5DH, 5EH, 5FH]; + (* SSE2 integer instructions that work on 16 bytes at a time: 66 0F code, + xmm and xmm or memory (pshufd also takes a byte) *) + PackedOps = " punpcklbw punpcklwd pcmpeqb pshufd pand pandn por pxor paddb psubb "; + PackedCodes: [10]INT = [60H, 61H, 74H, 70H, 0DBH, 0DFH, 0EBH, 0EFH, 0FCH, 0F8H]; + (* bit scans and counts: reg, reg or memory, with the prefix and code that tell them *) + BitOps = " bsf bsr tzcnt lzcnt popcnt "; + BitPfx: [5]INT = [0, 0, 0F3H, 0F3H, 0F3H]; + BitCodes: [5]INT = [0BC0FH, 0BD0FH, 0BC0FH, 0BD0FH, 0B80FH]; + Plain: [15][]U8 = ["ret", "leave", "syscall", "cpuid", "rdtsc", + "pause", "nop", "ud2", "int3", "hlt", "cqo", "cdq", "mfence", "lfence", "sfence"]; + PlainOp: [15]INT = [0C3H, 0C9H, 050FH, 0A20FH, 310FH, + 90F3H, 90H, 0B0FH, 0CCH, 0F4H, 9948H, 99H, 0F0AE0FH, 0E8AE0FH, 0F8AE0FH]; + +var + (* the instruction being assembled *) + aw: []U8; (* its word *) + ao: [3]Operand; (* its operands *) + an: INT; (* how many *) + asize, apfx: INT; + awide, abyte: BOOL; + aat: Diag.Pos; (* where it starts *) + (* the labels of the procedure *) + lnames, lplaces, lchains: [64]INT; + lusedAt: [64]Diag.Pos; + numLabels: INT; + +(* The label called n, entered if new *) +proc lab(n: INT): (INT, ERROR); +var i: INT; +begin + for i := 0 to numLabels - 1 do + if lnames[i] = n then return i, nil; end; + end; + if numLabels > 63 then return 0, Scan.mark("more than 64 labels"); end; + lnames[numLabels] := n; lplaces[numLabels] := -1; lchains[numLabels] := NoLabel; + lusedAt[numLabels] := Scan.tokPos(); + numLabels := numLabels + 1; + return numLabels - 1, nil; +end; + +proc bad: ERROR; +begin + return Scan.markAt(aat, Diag.say("can't assemble {} with these operands", [Fmt.str(aw)])); +end; + +(* an instruction of two operands: a register or memory, and a + register (opcode toRM), the other way (fromRM), or an immediate + (opImm /digit, or none if opImm < 0) *) +proc two(toRM, fromRM, opImm, digit: INT): ERROR; +var b: INT; +begin + b := 0; + if abyte then b := 1; end; + if an # 2 then return bad(); end; + if ao[1].kind = oImm then + if (ao[0].kind = oImm) or (opImm < 0) then return bad(); end; + if (opImm = 81H) and not abyte and (ao[1].v >= -128) and (ao[1].v <= 127) then + rm(apfx, awide, 83H, digit, ao[0], false); (* a byte, sign-extended *) + Chunk.put1(INT(ao[1].v & 0FFH)); + else + rm(apfx, awide, opImm - b, digit, ao[0], false); + putImmV(ao[1].v, asize); + end; + elsif (ao[1].kind = oReg) and ((ao[0].kind = oReg) or (ao[0].kind = oMem)) then + rm(apfx, awide, toRM - b, ao[1].r, ao[0], abyte); + elsif (ao[0].kind = oReg) and (ao[1].kind = oMem) then + rm(apfx, awide, fromRM - b, ao[0].r, ao[1], abyte); + else + return bad(); + end; + return nil; +end; + +(* whether operand i is an xmm register or a memory operand *) +proc isXM(i: INT): BOOL; +begin + return (ao[i].kind = oXmm) or (ao[i].kind = oMem); +end; + +(* whether operand i is a general register or a memory operand, for an + xmm register's partner *) +proc isRMem(i: INT): BOOL; +begin + return (ao[i].kind = oReg) or (ao[i].kind = oMem); +end; + +(* b as 1 for true *) +proc bit(f: BOOL): INT; +begin + if f then return 1; end; + return 0; +end; + +(* The instruction w with its operands, in ao and an, apart from the + jumps to labels and db, which assemble does *) +proc instruction(): ERROR; +var k: INT; +begin + if wordIndex(aw, Alus) >= 0 then + k := wordIndex(aw, Alus); + return two(k * 8 + 1, k * 8 + 3, 81H, k); + elsif aw = "mov" then + if (an = 2) and (ao[0].kind = oReg) and (ao[1].kind = oImm) and (asize >= 4) then + if awide then + movRI(ao[0].r, ao[1].v); + else + prefix(0, false, 0, NoIndex, ao[0].r, false); Chunk.put1(0B8H + (ao[0].r & 7)); Chunk.put4(INT(ao[1].v & 0FFFFFFFFH)); + end; + return nil; + end; + return two(89H, 8BH, 0C7H, 0); + elsif aw = "test" then + return two(85H, 85H, 0F7H, 0); + elsif aw = "xchg" then + return two(87H, 87H, -1, 0); + elsif (aw = "cmpxchg") or (aw = "xadd") then + if (an # 2) or (ao[1].kind # oReg) then return bad(); end; + if aw = "xadd" then k := 0C10FH; else k := 0B10FH; end; + rm(apfx, awide, k - (bit(abyte) shl 8), ao[1].r, ao[0], abyte); + elsif aw = "lea" then + if (an # 2) or (ao[0].kind # oReg) or (ao[1].kind # oMem) then return bad(); end; + rm(apfx, awide, 8DH, ao[0].r, ao[1], false); + elsif (aw = "movzx") or (aw = "movsx") or (aw = "movsxd") then + if (an # 2) or (ao[0].kind # oReg) or (ao[1].kind = oImm) then return bad(); end; + if aw = "movsxd" then + k := 63H; + elsif ao[1].size = 1 then + k := 0B60FH; + elsif ao[1].size = 2 then + k := 0B70FH; + else + return bad(); + end; + if aw = "movsx" then k := k + 0800H; end; + rm(apfx, awide, k, ao[0].r, ao[1], ao[1].size = 1); + elsif ((wordIndex(aw, Unaries) >= 0) and (an = 1)) or (aw = "inc") or (aw = "dec") then + if ao[0].kind = oImm then return bad(); end; + if aw = "inc" then + rm(apfx, awide, 0FFH - bit(abyte), 0, ao[0], abyte); + elsif aw = "dec" then + rm(apfx, awide, 0FFH - bit(abyte), 1, ao[0], abyte); + else + rm(apfx, awide, 0F7H - bit(abyte), wordIndex(aw, Unaries) + 2, ao[0], abyte); + end; + elsif aw = "imul" then + if (an < 2) or (ao[0].kind # oReg) or (ao[1].kind = oImm) then return bad(); end; + if an = 2 then + rm(apfx, awide, 0AF0FH, ao[0].r, ao[1], false); + else + rm(apfx, awide, 69H, ao[0].r, ao[1], false); + putImmV(ao[2].v, asize); + end; + elsif wordIndex(aw, Shifts) >= 0 then + k := wordIndex(aw, Shifts); + if k = 6 then k := 4; end; (* sal is shl *) + if (an # 2) or (ao[0].kind = oImm) then return bad(); end; + if ao[1].kind = oImm then + rm(apfx, awide, 0C1H - bit(abyte), k, ao[0], abyte); + Chunk.put1(INT(ao[1].v & 0FFH)); + elsif (ao[1].kind = oReg) and (ao[1].r = RCX) and (ao[1].size = 1) then + rm(apfx, awide, 0D3H - bit(abyte), k, ao[0], abyte); + else + return bad(); + end; + elsif (aw = "push") or (aw = "pop") then + if (an # 1) or (ao[0].kind # oReg) or not awide then return bad(); end; + if aw = "push" then push(ao[0].r); else pop(ao[0].r); end; + elsif (aw = "call") or (aw = "jmp") then + if (an # 1) or (ao[0].kind = oImm) then return bad(); end; + if aw = "call" then rm(0, false, 0FFH, 2, ao[0], false); else rm(0, false, 0FFH, 4, ao[0], false); end; + elsif Str.hasPrefix(aw, "set") and (cond(part(aw, 3, 3)) >= 0) then + if (an # 1) or (ao[0].kind = oImm) or (asize # 1) then return bad(); end; + rm(0, false, 900FH + (cond(part(aw, 3, 3)) shl 8), 0, ao[0], true); + elsif Str.hasPrefix(aw, "cmov") and (cond(part(aw, 4, 3)) >= 0) then + if (an # 2) or (ao[0].kind # oReg) or (ao[1].kind = oImm) then return bad(); end; + rm(apfx, awide, 400FH + (cond(part(aw, 4, 3)) shl 8), ao[0].r, ao[1], false); + elsif (LEN(aw) > 2) and (wordIndex(aw[0..LEN(aw) - 2], SseOps) >= 0) + and ((aw[LEN(aw) - 2..LEN(aw)] = "sd") or (aw[LEN(aw) - 2..LEN(aw)] = "ss")) then + (* sqrtsd, addss and the like: xmm, xmm or memory *) + if (an # 2) or (ao[0].kind # oXmm) or not isXM(1) then return bad(); end; + k := 0FH | (SseCodes[wordIndex(aw[0..LEN(aw) - 2], SseOps)] shl 8); + rm(realPfx(aw[LEN(aw) - 1] = 's'), false, k, ao[0].r, ao[1], false); + elsif wordIndex(aw, PackedOps) >= 0 then + if (an < 2) or (ao[0].kind # oXmm) or not isXM(1) then return bad(); end; + k := wordIndex(aw, PackedOps); + rm(66H, false, 0FH | (PackedCodes[k] shl 8), ao[0].r, ao[1], false); + if aw = "pshufd" then + if (an # 3) or (ao[2].kind # oImm) then return bad(); end; + Chunk.put1(INT(ao[2].v & 0FFH)); + elsif an # 2 then + return bad(); + end; + elsif (aw = "movdqu") or (aw = "movdqa") then + (* the load is 6F and the store 7F; movdqu is F3, movdqa 66 *) + if aw = "movdqu" then k := 0F3H; else k := 66H; end; + if (an = 2) and (ao[0].kind = oXmm) and isXM(1) then + rm(k, false, 6F0FH, ao[0].r, ao[1], false); + elsif (an = 2) and (ao[0].kind = oMem) and (ao[1].kind = oXmm) then + rm(k, false, 7F0FH, ao[1].r, ao[0], false); + else + return bad(); + end; + elsif aw = "pmovmskb" then + if (an # 2) or (ao[0].kind # oReg) or (ao[1].kind # oXmm) then return bad(); end; + rm(66H, false, 0D70FH, ao[0].r, ao[1], false); + elsif wordIndex(aw, BitOps) >= 0 then + if (an # 2) or (ao[0].kind # oReg) or (ao[1].kind = oImm) or (asize < 4) then return bad(); end; + k := wordIndex(aw, BitOps); + rm(BitPfx[k], awide, BitCodes[k], ao[0].r, ao[1], false); + elsif (aw = "movsd") or (aw = "movss") then + if aw = "movsd" then k := 0F2H; else k := 0F3H; end; + if (an = 2) and (ao[0].kind = oXmm) and isXM(1) then + rm(k, false, 100FH, ao[0].r, ao[1], false); + elsif (an = 2) and (ao[0].kind = oMem) and (ao[1].kind = oXmm) then + rm(k, false, 110FH, ao[1].r, ao[0], false); + else + return bad(); + end; + elsif (aw = "movq") or (aw = "movd") then + if (an = 2) and (ao[0].kind = oXmm) and isRMem(1) then + rm(66H, aw = "movq", 6E0FH, ao[0].r, ao[1], false); + elsif (an = 2) and (ao[1].kind = oXmm) and isRMem(0) then + rm(66H, aw = "movq", 7E0FH, ao[1].r, ao[0], false); + else + return bad(); + end; + elsif (aw = "ucomisd") or (aw = "ucomiss") then + if (an # 2) or (ao[0].kind # oXmm) or not isXM(1) then return bad(); end; + if aw = "ucomisd" then + rm(66H, false, 2E0FH, ao[0].r, ao[1], false); + else + rm(0, false, 2E0FH, ao[0].r, ao[1], false); + end; + elsif (aw = "cvtsi2sd") or (aw = "cvtsi2ss") then + if (an # 2) or (ao[0].kind # oXmm) or not isRMem(1) then return bad(); end; + rm(realPfx(aw = "cvtsi2ss"), ao[1].size # 4, 2A0FH, ao[0].r, ao[1], false); + elsif (aw = "cvttsd2si") or (aw = "cvttss2si") then + if (an # 2) or (ao[0].kind # oReg) or not isXM(1) then return bad(); end; + rm(realPfx(aw = "cvttss2si"), awide, 2C0FH, ao[0].r, ao[1], false); + elsif (aw = "cvtsd2ss") or (aw = "cvtss2sd") then + if (an # 2) or (ao[0].kind # oXmm) or not isXM(1) then return bad(); end; + rm(realPfx(aw = "cvtss2sd"), false, 5A0FH, ao[0].r, ao[1], false); + else + k := 0; + while (k <= 14) and (Plain[k] # aw) do INC(k); end; + if (k > 14) or (an # 0) then + return Scan.markAt(aat, Diag.say("unknown instruction {}", [Fmt.str(aw)])); + end; + opcode(PlainOp[k]); + end; + return nil; +end; + +(* One instruction or label, as assemble reads it *) +proc statement(constExpr: ConstFn): ERROR; +var + i, k, cc, first: INT; wasListing: BOOL; start: Diag.Pos; v: I64; +begin + aat := Scan.tokPos(); + aw := asmWord(); + if LEN(aw) = 0 then return Scan.mark("expected an instruction"); end; + Scan.next; + if Scan.tok = Scan.sColon then + sayAt(Chunk.pc, Diag.say("{}:", [Fmt.str(aw)])); + k := try lab(Scan.intern(ADR(aw[0]), LEN(aw))); + if lplaces[k] >= 0 then + return Scan.markAt(aat, Diag.say("label {} is defined twice", [Fmt.str(aw)])); + end; + lplaces[k] := Chunk.pc; + fixLink(lchains[k]); + Scan.next; + return nil; + end; + first := Chunk.pc; + wasListing := listing; + listing := false; (* the instruction is said as it is written *) + if aw = "lock" then + Chunk.put1(0F0H); + aw := asmWord(); + Scan.next; + end; + cc := -1; + if aw = "db" then + repeat + start := Scan.tokPos(); + v := try constExpr(true); + if (v < -128) or (v > 255) then + return Scan.markAt(Scan.spanFrom(start), Diag.say("expected a byte from 0 to 255, found {}", [Fmt.int(v)])); + end; + Chunk.put1(INT(v & 0FFH)); + if Scan.tok # Scan.sComma then break; end; + Scan.next; + until false; + elsif (aw[0] = 'j') and ((aw = "jmp") or (cond(part(aw, 1, 3)) >= 0)) and (Scan.tok = Scan.sIdent) then + (* a jump to a label *) + k := try lab(Scan.id); + Scan.next; + if aw # "jmp" then cc := cond(part(aw, 1, 3)); end; + if lplaces[k] >= 0 then + if cc < 0 then jmpBack(lplaces[k]); else jccBack(cc, lplaces[k]); end; + elsif cc < 0 then + jmp(lchains[k]); + else + jcc(cc, lchains[k]); + end; + else + an := 0; + if Scan.tok # Scan.sSemicolon then + repeat + if an > 2 then return Scan.mark("too many operands"); end; + try operand(ADR(ao[an]), constExpr); + INC(an); + if Scan.tok # Scan.sComma then break; end; + Scan.next; + until false; + end; + (* the size: a register's, or what the memory operand says *) + asize := 8; + for i := an - 1 to 0 by -1 do + if (ao[i].kind = oReg) or ((ao[i].kind = oMem) and (ao[i].size # 0)) then asize := ao[i].size; end; + end; + if an > 0 then + if (ao[0].kind = oReg) or ((ao[0].kind = oMem) and (ao[0].size # 0)) then asize := ao[0].size; end; + end; + awide := asize = 8; + abyte := asize = 1; + if asize = 2 then apfx := 66H; else apfx := 0; end; + try instruction(); + end; + if Scan.tok # Scan.sSemicolon then return Scan.mark("expected \";\""); end; + listing := wasListing; + sayAt(first, Diag.source(Scan.spanFrom(aat))); + Scan.next; + return nil; +end; + +proc assemble*(constExpr: ConstFn): ERROR; +var k: INT; +begin + numLabels := 0; + while (Scan.tok # Scan.sEnd) and (Scan.tok # Scan.sEof) do + if Scan.tok = Scan.sSemicolon then + Scan.next; + else + try statement(constExpr); + end; + end; + for k := 0 to numLabels - 1 do + if lplaces[k] < 0 then + return Scan.markAt(lusedAt[k], Diag.say("label {} isn't defined", [Fmt.str(Scan.nameOf(lnames[k]))])); + end; + end; + return nil; +end; + +(* Whether s holds a space *) +proc hasSpace(s: []U8): BOOL; +var i: INT; +begin + for i := 0 to LEN(s) - 1 do + if s[i] = ' ' then return true; end; + end; + return false; +end; + +(* n, in decimal, at least w wide, as write(n: w) *) +proc padded(n, w: INT); +var s: []U8; i: INT; +begin + s := Diag.say("{}", [Fmt.int(n)]); + for i := LEN(s) to w - 1 do Out.str(" "); end; + Out.str(s); +end; + +(* The listing, raz -S: each live procedure of the module in the order + it was made, each line of source it comes from, and under it the + instructions made for it, at their offsets in the procedure; a jump + within it says where to by its offset too. *) +proc list*(home: INT); +var order: ^INT; n, i, j, k, c, t, line: INT; text: []U8; +begin + order := ^INT(Scan.grab(Chunk.numChunks * SIZE(INT))); + n := 0; + for c := 0 to Chunk.numChunks - 1 do + if Chunk.chunks[c].live and (Chunk.chunks[c].sec = Chunk.secText) and (Chunk.chunks[c].home = home) then + i := n; + while (i > 0) and (Chunk.chunks[order[i - 1]].start > Chunk.chunks[c].start) do + order[i] := order[i - 1]; + DEC(i); + end; + order[i] := c; + INC(n); + end; + end; + i := 0; j := 0; + for k := 0 to n - 1 do + c := order[k]; + Out.ln; + Out.str(Chunk.chunkName(c)); Out.str(":\n"); + line := -1; + while (i < numSaid) and (said[i].at < Chunk.chunks[c].start) do INC(i); end; + while (i < numSaid) and (said[i].at < Chunk.chunks[c].start + Chunk.chunks[c].size) do + while (j < Chunk.numLines) and (Chunk.lines[j].at <= said[i].at) do + if (Chunk.lines[j].chunk = c) and (Chunk.lines[j].line # line) then + line := Chunk.lines[j].line; + padded(line, 6); + Out.str(" "); + Out.str(Diag.lineText(Scan.nameOf(Chunk.lines[j].path), line)); + Out.ln; + end; + INC(j); + end; + text := said[i].text; + t := said[i].at; + if (text = "jmp") or (text = "call") then + text := Diag.say("{} {}", [Fmt.str(text), Fmt.int(t + 5 + Chunk.get4At(t + 1) - Chunk.chunks[c].start)]); + elsif (text[0] = 'j') and not hasSpace(text) then + text := Diag.say("{} {}", [Fmt.str(text), Fmt.int(t + 6 + Chunk.get4At(t + 2) - Chunk.chunks[c].start)]); + end; + padded(t - Chunk.chunks[c].start, 14); + Out.str(" "); + Out.str(text); + Out.ln; + INC(i); + end; + end; +end; + +begin + listing := false; + numSaid := 0; + saidCap := 0; + said := nil; +end X64. diff --git a/self/check.sh b/self/check.sh index 2bd1d07..2d5ea2d 100755 --- a/self/check.sh +++ b/self/check.sh @@ -54,3 +54,40 @@ cmp $b/sym.seed.err $b/sym.self.err done echo "chunk and sym ok" + +# Link and Elf: a program of chunks made by a script, linked and written +# as a static, a dynamic and a stripped executable, which must be the +# same file from both sides +fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fusrc -o$b/linkdump.seed self/test/LinkDump.pas >/dev/null +./raz -Werror -I self -o $b/linkdump.self self/test/LinkDump.raz +for m in 0 1 2; do + $b/linkdump.seed $m $b/link.seed + $b/linkdump.self $m $b/link.self + cmp $b/link.seed $b/link.self +done +echo "link and elf ok" + +# X64: every encoder, then the assembler on a long run of instructions +# of every kind and a file for each error it makes; the bytes and the +# listing, or the message and status, must be the same +fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fusrc -o$b/x64dump.seed self/test/X64Dump.pas >/dev/null +./raz -Werror -I self -o $b/x64dump.self self/test/X64Dump.raz +$b/x64dump.seed >$b/x64.seed +$b/x64dump.self >$b/x64.self +cmp $b/x64.seed $b/x64.self +fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fusrc -o$b/asmdump.seed self/test/AsmDump.pas >/dev/null +./raz -Werror -I self -o $b/asmdump.self self/test/AsmDump.raz +mkdir -p $b/asm +python3 self/test/genasm.py $b/asm +n=0; bad=0 +for f in $b/asm/*.raz; do + s1=0; s2=0 + $b/asmdump.seed $f >$b/seed.out 2>$b/seed.err || s1=$? + $b/asmdump.self $f >$b/self.out 2>$b/self.err || s2=$? + n=$((n + 1)) + if [ $s1 != $s2 ] || ! cmp -s $b/seed.out $b/self.out || ! cmp -s $b/seed.err $b/self.err; then + echo "differs: $f (status $s1 and $s2)"; bad=$((bad + 1)) + fi +done +echo "x64: $n assembler files, $bad differ" +test $bad = 0 diff --git a/self/test/AsmDump.pas b/self/test/AsmDump.pas new file mode 100644 index 0000000..af7ee9d --- /dev/null +++ b/self/test/AsmDump.pas @@ -0,0 +1,46 @@ +{ Assembles the instructions in the file of the argument, as the body of + a code procedure that ends in end, and prints the bytes and the + listing: the seed's side of a test of the assembler in self/X64.raz, + whose AsmDump.raz does the same and prints the same. Constants are + numbers, with a minus sign, and sums of them. } +program asmdump; +{$mode objfpc}{$H-} +uses diag, scan, chunk, x64; +var i: longint; path: string; + +function ConstVal(whole: boolean): int64; +var neg: boolean; v: int64; +begin + neg := tok = sMinus; + if neg then Next; + if tok <> sInt then Mark('expected a number'); + v := ival; + Next; + if neg then v := -v; + while whole and (tok in [sPlus, sMinus]) do begin + neg := tok = sMinus; + Next; + if tok <> sInt then Mark('expected a number'); + if neg then v := v - ival else v := v + ival; + Next; + end; + ConstVal := v; +end; + +begin + if Open(ParamStr(1)) <> '' then Fatal('no file'); + path := 'lib/Rt.raz'; + curFile := Intern(@path[1], length(path)); + listing := true; + NewChunk(secText, 0, 0); + BeginChunk(0); + NoteLine(1, 1); + Next; + Assemble(@ConstVal); + EndChunk(0); + chunks^[0].live := true; + for i := 0 to pc - 1 do write(HexStr(code^[i], 2)); + writeln; + List(0); + Finish; +end. diff --git a/self/test/AsmDump.raz b/self/test/AsmDump.raz new file mode 100644 index 0000000..7f78f98 --- /dev/null +++ b/self/test/AsmDump.raz @@ -0,0 +1,55 @@ +(* Assembles the instructions in the file of the argument, as the body of + a code procedure that ends in end, and prints the bytes and the + listing: self/X64.raz's assembler's side of a test against the seed's, + AsmDump.pas, which prints the same. Constants are numbers, with a + minus sign, and sums of them. *) +module AsmDump; +import Out, Files, Diag, Scan, Chunk, X64; + +proc number(neg: BOOL): (I64, ERROR); +var v: I64; +begin + if Scan.tok # Scan.sInt then return 0, Scan.mark("expected a number"); end; + v := Scan.ival; + Scan.next; + if neg then v := -v; end; + return v, nil; +end; + +proc constant(whole: BOOL): (I64, ERROR); +var neg: BOOL; v, w: I64; +begin + neg := Scan.tok = Scan.sMinus; + if neg then Scan.next; end; + v := try number(neg); + while whole and ((Scan.tok = Scan.sPlus) or (Scan.tok = Scan.sMinus)) do + neg := Scan.tok = Scan.sMinus; + Scan.next; + w := try number(neg); + v := v + w; + end; + return v, nil; +end; + +proc main*; +var i: INT; path: []U8; err: ERROR; +begin + if LEN(Scan.open(Files.arg(1))) # 0 then Diag.fatal("no file"); end; + path := "lib/Rt.raz"; + Chunk.setCurFile(Scan.intern(ADR(path[0]), LEN(path))); + X64.setListing(true); + _ := Chunk.newChunk(Chunk.secText, 0, 0); + Chunk.beginChunk(0); + Chunk.noteLine(1, 1); + Scan.next; + err := X64.assemble(constant); + if err # nil then Diag.finish; end; + Chunk.endChunk(0); + Chunk.setLive(0); + for i := 0 to Chunk.pc - 1 do Out.hex(U64(Chunk.text[i]), 2); end; + Out.ln; + X64.list(0); + Diag.finish; +end; + +end AsmDump. diff --git a/self/test/LinkDump.pas b/self/test/LinkDump.pas new file mode 100644 index 0000000..47e1db4 --- /dev/null +++ b/self/test/LinkDump.pas @@ -0,0 +1,91 @@ +{ Makes a program of chunks by a fixed pseudo-random script, links it and + writes it as an executable to the file of the second argument, in the + way the first says (0 static, 1 dynamic, 2 stripped): the seed's side + of a test of self/Link.raz and self/Elf.raz, whose LinkDump.raz does + the same and writes the same file. } +program linkdump; +{$mode objfpc}{$H-} +uses diag, scan, chunk, link, elf; +const NumC = 200; +var + seed: int64; + names: array[0..7] of longint; + i, j, k, kind, n, x, y, z, mode: longint; + b: array[0..63] of byte; + +function Rnd(n: longint): longint; +begin + seed := (seed * 1103515245 + 12345) and $7FFFFFFF; + Rnd := (seed shr 8) mod n; +end; + +var c, e, line, col: longint; +begin + seed := 5; + mode := ord(ParamStr(1)[1]) - 48; + for i := 0 to 7 do begin b[0] := 97 + i; names[i] := Intern(@b[0], 1) end; + placesChunk := NewChunk(secRodata, -1, -1); + SetData(placesChunk, @b[0], 0, 8); + for i := 0 to NumC - 1 do begin + if i = 0 then kind := 0 else kind := Rnd(10); + x := Rnd(4); y := Rnd(8); + case kind of + 0..5: begin + c := NewChunk(secText, x - 1, y); + BeginChunk(c); + z := Rnd(3); curFile := names[z]; + line := Rnd(300); col := Rnd(60); + NoteLine(line, col); + if i = 0 then begin AddFixup(pc, placesChunk, 0); Put4(0) end; + n := 2 + Rnd(10); + for j := 1 to n do begin + z := Rnd(5); + if z <= 1 then begin + e := Rnd(NumC); y := Rnd(8); + AddFixup(pc, e, y); + Put4(0); + end else if z = 2 then begin + z := Rnd(3); curFile := names[z]; + line := Rnd(300); col := Rnd(60); + NoteLine(line, col); + end else begin x := Rnd(1 shl 30); Put4(x); x := Rnd(256); Put1(x) end; + end; + EndChunk(c); + n := Rnd(3); + for j := 1 to n do begin + x := Rnd(8); y := Rnd(200); z := Rnd(6); + NoteVar(c, names[x], y - 100, z); + end; + end; + 6, 7: begin + c := NewChunk(secRodata, x - 1, y); + n := 8 * (1 + Rnd(4)); + for j := 0 to n - 1 do b[j] := Rnd(256); + SetData(c, @b[0], n, 8); + for j := 0 to n div 8 - 1 do begin + z := Rnd(2); + if z = 0 then begin e := Rnd(NumC); y := Rnd(8); AddDataFixup(c, j * 8, e, y) end; + end; + end; + 8: begin + c := NewChunk(secBss, x - 1, y); + z := Rnd(200); e := Rnd(4); + SetBss(c, 1 + z, 1 shl e); + end; + 9: begin z := Rnd(8); c := ExternChunk(names[z]) end; + end; + end; + { every chunk a fixup names must exist, and be defined if it is reached } + while numChunks < NumC do begin c := NewChunk(secBss, -1, -1); SetBss(c, 8, 8) end; + for i := 0 to numChunks - 1 do + if chunks^[i].size < 0 then SetBss(i, 8, 8); + mainPath := 'some/main.raz'; + if mode = 1 then begin + numNeeded := 2; + needed[0] := names[0]; needed[1] := names[1]; + end; + stripped := mode = 2; + if mode = 2 then placesChunk := -1; + MarkLive(1); + WriteElf(ParamStr(2), 1); +end. diff --git a/self/test/LinkDump.raz b/self/test/LinkDump.raz new file mode 100644 index 0000000..961abd6 --- /dev/null +++ b/self/test/LinkDump.raz @@ -0,0 +1,103 @@ +(* Makes a program of chunks by a fixed pseudo-random script, links it + and writes it as an executable to the file of the second argument, + in the way the first says (0 static, 1 dynamic, 2 stripped): + self/Link.raz's and self/Elf.raz's side of a test against the seed's, + LinkDump.pas, which writes the same file. *) +module LinkDump; +import Files, Diag, Scan, Chunk, Link, Elf; + +const NumC = 200; + +var seed: I64; + +proc rnd(n: INT): INT; +begin + seed := (seed * 1103515245 + 12345) & 7FFFFFFFH; + return INT((seed shr 8) mod I64(n)); +end; + +(* a library that must be taken *) +proc ok(taken: BOOL); +begin + if not taken then Diag.fatal("too many libraries"); end; +end; + +proc main*; +var + names: [8]INT; b: [64]U8; arg: []U8; + i, j, kind, n, x, y, z, c, e, line, col, mode: INT; +begin + seed := 5; + arg := Files.arg(1); + mode := INT(arg[0]) - 48; + for i := 0 to 7 do b[0] := U8(97 + i); names[i] := Scan.intern(ADR(b[0]), 1); end; + Link.setPlaces(Chunk.newChunk(Chunk.secRodata, -1, -1)); + Chunk.setData(Link.placesChunk, ADR(b[0]), 0, 8); + for i := 0 to NumC - 1 do + if i = 0 then kind := 0; else kind := rnd(10); end; + x := rnd(4); y := rnd(8); + match kind of + | 0..5: + c := Chunk.newChunk(Chunk.secText, x - 1, y); + Chunk.beginChunk(c); + z := rnd(3); Chunk.setCurFile(names[z]); + line := rnd(300); col := rnd(60); + Chunk.noteLine(line, col); + if i = 0 then Chunk.addFixup(Chunk.pc, Link.placesChunk, 0); Chunk.put4(0); end; + n := 2 + rnd(10); + for j := 1 to n do + z := rnd(5); + if z <= 1 then + e := rnd(NumC); y := rnd(8); + Chunk.addFixup(Chunk.pc, e, y); + Chunk.put4(0); + elsif z = 2 then + z := rnd(3); Chunk.setCurFile(names[z]); + line := rnd(300); col := rnd(60); + Chunk.noteLine(line, col); + else + x := rnd(1 shl 30); Chunk.put4(x); x := rnd(256); Chunk.put1(x); + end; + end; + Chunk.endChunk(c); + n := rnd(3); + for j := 1 to n do + x := rnd(8); y := rnd(200); z := rnd(6); + Chunk.noteVar(c, names[x], y - 100, z); + end; + | 6, 7: + c := Chunk.newChunk(Chunk.secRodata, x - 1, y); + n := 8 * (1 + rnd(4)); + for j := 0 to n - 1 do b[j] := U8(rnd(256)); end; + Chunk.setData(c, ADR(b[0]), n, 8); + for j := 0 to n div 8 - 1 do + z := rnd(2); + if z = 0 then e := rnd(NumC); y := rnd(8); Chunk.addDataFixup(c, j * 8, e, y); end; + end; + | 8: + c := Chunk.newChunk(Chunk.secBss, x - 1, y); + z := rnd(200); e := rnd(4); + Chunk.setBss(c, 1 + z, 1 shl e); + | else: z := rnd(8); c := Chunk.externChunk(names[z]); + end; + end; + (* every chunk a fixup names must exist, and be defined if it is reached *) + while Chunk.numChunks < NumC do + c := Chunk.newChunk(Chunk.secBss, -1, -1); + Chunk.setBss(c, 8, 8); + end; + for i := 0 to Chunk.numChunks - 1 do + if Chunk.chunks[i].size < 0 then Chunk.setBss(i, 8, 8); end; + end; + Elf.setMainPath("some/main.raz"); + if mode = 1 then + ok(Elf.needLib(names[0])); + ok(Elf.needLib(names[1])); + end; + Elf.setStripped(mode = 2); + if mode = 2 then Link.setPlaces(-1); end; + Link.markLive(1); + Elf.writeElf(Files.arg(2), 1); +end; + +end LinkDump. diff --git a/self/test/X64Dump.pas b/self/test/X64Dump.pas new file mode 100644 index 0000000..7d44a09 --- /dev/null +++ b/self/test/X64Dump.pas @@ -0,0 +1,160 @@ +{ Writes every instruction the encoder makes, with operands drawn by a + fixed pseudo-random script, then prints the bytes, the fixups and the + listing (raz -S) of what it made: the seed's side of a test of + self/X64.raz, whose X64Dump.raz does the same and prints the same. } +program x64dump; +{$mode objfpc}{$H-} +uses diag, scan, chunk, x64; +var + seed: int64; + i, k, op, a, b, c, d, lab1, lab2: longint; + m: TMem; + path: string; + +function Rnd(n: longint): longint; +begin + seed := (seed * 1103515245 + 12345) and $7FFFFFFF; + Rnd := (seed shr 8) mod n; +end; + +{ a register, with the stack and base pointers and the high ones often enough } +function Reg: longint; +begin + Reg := Rnd(16); +end; + +{ a size of 1, 2, 4 or 8 bytes } +function Size: longint; +begin + Size := 1 shl Rnd(4); +end; + +{ a value that fits size bytes, of 8 as 32 bits } +function Imm(sz: longint): longint; +var x: longint; +begin + x := Rnd(1 shl 30); + case Rnd(3) of + 0: Imm := x mod 100 - 50; + 1: Imm := x - (1 shl 29); + else Imm := x mod 20000 - 10000; + end; + if sz = 1 then Imm := Imm mod 128 + else if sz = 2 then Imm := Imm mod 32768; +end; + +function RandMem: TMem; +var kind, base, idx, sc, disp, x: longint; +begin + kind := Rnd(6); + base := Reg; idx := Reg; sc := 1 shl Rnd(4); x := Rnd(5); + case x of + 0: disp := 0; + 1: disp := Rnd(250) - 125; + 2: disp := Rnd(1 shl 20) - (1 shl 19); + 3: disp := 127 + Rnd(3) - 1; + else disp := -128 + Rnd(3) - 1; + end; + case kind of + 0, 1: RandMem := Mem(base, disp); + 2: RandMem := MemRip(Rnd(5), disp); + 3, 4: RandMem := MemIdx(base, idx, sc, disp); + else RandMem := Mem(base, 0); + end; +end; + +begin + seed := 3; + path := 'lib/Rt.raz'; + if Open(path) <> '' then Fatal('no file'); + listing := true; + for i := 0 to 4 do NewChunk(secText, i - 1, i); + curFile := Intern(@path[1], length(path)); + BeginChunk(0); + lab1 := NoLabel; lab2 := NoLabel; + for k := 1 to 3000 do begin + if k mod 7 = 0 then begin a := Rnd(300); b := Rnd(60); NoteLine(1 + a, b) end; + op := Rnd(50); + case op of + 0: begin a := Reg; b := Reg; MovRR(a, b) end; + 1: begin + a := Reg; b := Rnd(6); c := Rnd(1 shl 30); + case b of + 0: MovRI(a, 0); + 1: MovRI(a, c); + 2: MovRI(a, -c); + 3: MovRI(a, int64(c) * 8 + 5); + 4: MovRI(a, int64(c) * 4096 * 4096 * 9 - 7); + else MovRI(a, 0); + end; + end; + 2: begin a := Rnd(8); m := RandMem; b := Size; c := Imm(b); AluMI(a, m, c, b) end; + 3: begin m := RandMem; b := Size; c := Imm(b); StoreI(m, c, b) end; + 4: begin a := Reg; m := RandMem; b := Size; c := Rnd(2); Load(a, m, b, c = 0) end; + 5: begin m := RandMem; a := Reg; b := Size; Store(m, a, b) end; + 6: begin a := Reg; m := RandMem; Lea(a, m) end; + 7: begin a := Rnd(8); b := Reg; c := Reg; Alu(a, b, c) end; + 8: begin a := Rnd(8); b := Reg; c := Imm(8); AluI(a, b, c) end; + 9: begin a := Rnd(8); b := Reg; m := RandMem; AluM(a, b, m) end; + 10: begin a := Reg; b := Reg; Imul(a, b) end; + 11: begin a := Reg; c := Imm(8); ImulI(a, c) end; + 12: begin a := Rnd(3); b := Reg; if a = 0 then a := shShl else if a = 1 then a := shShr else a := shSar; Shift(a, b) end; + 13: begin a := Rnd(3); b := Reg; c := Rnd(64); if a = 0 then a := shShl else if a = 1 then a := shShr else a := shSar; ShiftI(a, b, c) end; + 14: begin a := Rnd(4); b := Reg; if a < 2 then a := a + 2 else a := a + 4; Unary(a, b) end; + 15: Cqo; + 16: begin a := Reg; b := 1 shl Rnd(3); c := Rnd(2); Extend(a, b, c = 0) end; + 17: begin a := Rnd(16); b := Reg; SetCC(a, b) end; + 18: begin a := Reg; b := Reg; TestRR(a, b) end; + 19: begin a := Reg; Push(a) end; + 20: begin a := Reg; Pop(a) end; + 21: begin a := Rnd(5); CallChunk(a) end; + 22: begin a := Rnd(1000); CallBack(a) end; + 23: begin a := Reg; CallR(a) end; + 24: begin a := Reg; JmpR(a) end; + 25: begin m := RandMem; CallM(m) end; + 26: begin a := Rnd(5); case a of 0: Ret; 1: Leave; 2: Syscall; 3: Mfence; else Ud2 end end; + 27: begin a := 8 shl Rnd(3); Align(a) end; + 28: begin a := Rnd(5); case a of 0: RepMovsb; 1: Std; 2: Cld; 3: RepStosb; else RepeCmpsb end end; + 29: begin m := RandMem; a := Reg; LockCmpxchg(m, a) end; + 30: begin m := RandMem; a := Reg; Xchg(m, a) end; + 31: begin m := RandMem; a := Reg; LockXadd(m, a) end; + 32: begin a := Reg; b := Reg; MovqXR(a, b) end; + 33: begin a := Reg; b := Reg; MovqRX(a, b) end; + 34: begin a := Reg; b := Reg; MovX(a, b) end; + 35: begin a := Reg; m := RandMem; b := Rnd(2); MovsXM(a, m, b = 0) end; + 36: begin m := RandMem; a := Reg; b := Rnd(2); MovsMX(m, a, b = 0) end; + 37: begin + d := Rnd(5); a := Reg; b := Reg; c := Rnd(2); + case d of 0: d := $58; 1: d := $59; 2: d := $5C; 3: d := $5E; else d := $5A end; + Sse(d, a, b, c = 0); + end; + 38: begin + d := Rnd(5); a := Reg; m := RandMem; c := Rnd(2); + case d of 0: d := $58; 1: d := $59; 2: d := $5C; 3: d := $5E; else d := $5A end; + SseM(d, a, m, c = 0); + end; + 39: begin a := Reg; b := Reg; c := Rnd(2); Ucomis(a, b, c = 0) end; + 40: begin a := Reg; b := Reg; c := Rnd(2); Cvtsi2s(a, b, c = 0) end; + 41: begin a := Reg; b := Reg; c := Rnd(2); Cvtts2si(a, b, c = 0) end; + 42: begin a := Reg; b := Rnd(64); Btc(a, b) end; + 43: begin + a := Rnd(16); b := Rnd(2); + if b = 0 then Jmp(lab1) else Jcc(a, lab2); + end; + 44: begin a := Rnd(16); b := Rnd(2); c := pc - Rnd(200); if b = 0 then JmpBack(c) else JccBack(a, c) end; + 45: if Rnd(3) = 0 then begin FixLink(lab1); lab1 := NoLabel end + else begin FixLinkTo(lab2, pc - 20); lab2 := NoLabel end; + 46: begin Jmp(lab1); DropJumpTo(lab1) end; + 47: begin a := JoinLinks(lab1, lab2); lab1 := a; lab2 := NoLabel end; + else begin a := Rnd(256); Put1(a) end; + end; + end; + FixLink(lab1); FixLink(lab2); + EndChunk(0); + chunks^[0].live := true; + writeln('pc ', pc, ' fixups ', numFixups, ' lines ', numLines, ' said ', SaidCount); + for i := 0 to pc - 1 do write(HexStr(code^[i], 2)); + writeln; + for i := 0 to numFixups - 1 do writeln('F ', fixups^[i].at, ' ', fixups^[i].chunk, ' ', fixups^[i].addend); + List(-1); +end. diff --git a/self/test/X64Dump.raz b/self/test/X64Dump.raz new file mode 100644 index 0000000..6747ce6 --- /dev/null +++ b/self/test/X64Dump.raz @@ -0,0 +1,208 @@ +(* Writes every instruction the encoder makes, with operands drawn by a + fixed pseudo-random script, then prints the bytes, the fixups and the + listing (raz -S) of what it made: self/X64.raz's side of a test + against the seed's, X64Dump.pas, which prints the same. *) +module X64Dump; +import Out, Fmt, Diag, Scan, Chunk, X64; + +var seed: I64; + +proc rnd(n: INT): INT; +begin + seed := (seed * 1103515245 + 12345) & 7FFFFFFFH; + return INT((seed shr 8) mod I64(n)); +end; + +(* a register *) +proc reg: INT; +begin + return rnd(16); +end; + +(* a size of 1, 2, 4 or 8 bytes *) +proc size: INT; +begin + return 1 shl rnd(4); +end; + +(* a value that fits sz bytes, of 8 as 32 bits *) +proc imm(sz: INT): INT; +var x, r: INT; +begin + x := rnd(1 shl 30); + match rnd(3) of + | 0: r := x mod 100 - 50; + | 1: r := x - (1 shl 29); + | else: r := x mod 20000 - 10000; + end; + if sz = 1 then + r := r mod 128; + elsif sz = 2 then + r := r mod 32768; + end; + return r; +end; + +proc randMem: X64.Mem; +var kind, base, idx, sc, disp, x: INT; +begin + kind := rnd(6); + base := reg(); idx := reg(); sc := 1 shl rnd(4); x := rnd(5); + match x of + | 0: disp := 0; + | 1: disp := rnd(250) - 125; + | 2: disp := rnd(1 shl 20) - (1 shl 19); + | 3: disp := 127 + rnd(3) - 1; + | else: disp := -128 + rnd(3) - 1; + end; + match kind of + | 0, 1: return X64.mem(base, disp); + | 2: return X64.memRip(rnd(5), disp); + | 3, 4: return X64.memIdx(base, idx, sc, disp); + | else: return X64.mem(base, 0); + end; +end; + +proc main*; +var + i, k, op, a, b, c, d, lab1, lab2: INT; m: X64.Mem; path: []U8; +begin + seed := 3; + path := "lib/Rt.raz"; + if LEN(Scan.open(path)) # 0 then Diag.fatal("no file"); end; + X64.setListing(true); + for i := 0 to 4 do c := Chunk.newChunk(Chunk.secText, i - 1, i); end; + Chunk.setCurFile(Scan.intern(ADR(path[0]), LEN(path))); + Chunk.beginChunk(0); + lab1 := X64.NoLabel; lab2 := X64.NoLabel; + for k := 1 to 3000 do + if k mod 7 = 0 then a := rnd(300); b := rnd(60); Chunk.noteLine(1 + a, b); end; + op := rnd(50); + match op of + | 0: a := reg(); b := reg(); X64.movRR(a, b); + | 1: + a := reg(); b := rnd(6); c := rnd(1 shl 30); + match b of + | 0: X64.movRI(a, 0); + | 1: X64.movRI(a, c); + | 2: X64.movRI(a, -c); + | 3: X64.movRI(a, I64(c) * 8 + 5); + | 4: X64.movRI(a, I64(c) * 4096 * 4096 * 9 - 7); + | else: X64.movRI(a, 0); + end; + | 2: a := rnd(8); m := randMem(); b := size(); c := imm(b); X64.aluMI(a, m, c, b); + | 3: m := randMem(); b := size(); c := imm(b); X64.storeI(m, c, b); + | 4: a := reg(); m := randMem(); b := size(); c := rnd(2); X64.load(a, m, b, c = 0); + | 5: m := randMem(); a := reg(); b := size(); X64.store(m, a, b); + | 6: a := reg(); m := randMem(); X64.lea(a, m); + | 7: a := rnd(8); b := reg(); c := reg(); X64.alu(a, b, c); + | 8: a := rnd(8); b := reg(); c := imm(8); X64.aluI(a, b, c); + | 9: a := rnd(8); b := reg(); m := randMem(); X64.aluM(a, b, m); + | 10: a := reg(); b := reg(); X64.imul(a, b); + | 11: a := reg(); c := imm(8); X64.imulI(a, c); + | 12: + a := rnd(3); b := reg(); + if a = 0 then a := X64.shShl; elsif a = 1 then a := X64.shShr; else a := X64.shSar; end; + X64.shift(a, b); + | 13: + a := rnd(3); b := reg(); c := rnd(64); + if a = 0 then a := X64.shShl; elsif a = 1 then a := X64.shShr; else a := X64.shSar; end; + X64.shiftI(a, b, c); + | 14: + a := rnd(4); b := reg(); + if a < 2 then a := a + 2; else a := a + 4; end; + X64.unary(a, b); + | 15: X64.cqo; + | 16: a := reg(); b := 1 shl rnd(3); c := rnd(2); X64.extend(a, b, c = 0); + | 17: a := rnd(16); b := reg(); X64.setCC(a, b); + | 18: a := reg(); b := reg(); X64.testRR(a, b); + | 19: a := reg(); X64.push(a); + | 20: a := reg(); X64.pop(a); + | 21: a := rnd(5); X64.callChunk(a); + | 22: a := rnd(1000); X64.callBack(a); + | 23: a := reg(); X64.callR(a); + | 24: a := reg(); X64.jmpR(a); + | 25: m := randMem(); X64.callM(m); + | 26: + a := rnd(5); + match a of + | 0: X64.ret; + | 1: X64.leave; + | 2: X64.syscall; + | 3: X64.mfence; + | else: X64.ud2; + end; + | 27: a := 8 shl rnd(3); X64.align(a); + | 28: + a := rnd(5); + match a of + | 0: X64.repMovsb; + | 1: X64.std; + | 2: X64.cld; + | 3: X64.repStosb; + | else: X64.repeCmpsb; + end; + | 29: m := randMem(); a := reg(); X64.lockCmpxchg(m, a); + | 30: m := randMem(); a := reg(); X64.xchg(m, a); + | 31: m := randMem(); a := reg(); X64.lockXadd(m, a); + | 32: a := reg(); b := reg(); X64.movqXR(a, b); + | 33: a := reg(); b := reg(); X64.movqRX(a, b); + | 34: a := reg(); b := reg(); X64.movX(a, b); + | 35: a := reg(); m := randMem(); b := rnd(2); X64.movsXM(a, m, b = 0); + | 36: m := randMem(); a := reg(); b := rnd(2); X64.movsMX(m, a, b = 0); + | 37: + d := rnd(5); a := reg(); b := reg(); c := rnd(2); + match d of + | 0: d := 58H; + | 1: d := 59H; + | 2: d := 5CH; + | 3: d := 5EH; + | else: d := 5AH; + end; + X64.sse(d, a, b, c = 0); + | 38: + d := rnd(5); a := reg(); m := randMem(); c := rnd(2); + match d of + | 0: d := 58H; + | 1: d := 59H; + | 2: d := 5CH; + | 3: d := 5EH; + | else: d := 5AH; + end; + X64.sseM(d, a, m, c = 0); + | 39: a := reg(); b := reg(); c := rnd(2); X64.ucomis(a, b, c = 0); + | 40: a := reg(); b := reg(); c := rnd(2); X64.cvtsi2s(a, b, c = 0); + | 41: a := reg(); b := reg(); c := rnd(2); X64.cvtts2si(a, b, c = 0); + | 42: a := reg(); b := rnd(64); X64.btc(a, b); + | 43: + a := rnd(16); b := rnd(2); + if b = 0 then X64.jmp(lab1); else X64.jcc(a, lab2); end; + | 44: + a := rnd(16); b := rnd(2); c := Chunk.pc - rnd(200); + if b = 0 then X64.jmpBack(c); else X64.jccBack(a, c); end; + | 45: + a := rnd(3); + if a = 0 then + X64.fixLink(lab1); lab1 := X64.NoLabel; + else + X64.fixLinkTo(lab2, Chunk.pc - 20); lab2 := X64.NoLabel; + end; + | 46: X64.jmp(lab1); X64.dropJumpTo(lab1); + | 47: a := X64.joinLinks(lab1, lab2); lab1 := a; lab2 := X64.NoLabel; + | else: a := rnd(256); Chunk.put1(a); + end; + end; + X64.fixLink(lab1); X64.fixLink(lab2); + Chunk.endChunk(0); + Chunk.setLive(0); + Fmt.print("pc {} fixups {} lines {} said {}\n", [Fmt.int(Chunk.pc), Fmt.int(Chunk.numFixups), + Fmt.int(Chunk.numLines), Fmt.int(X64.saidCount())]); + for i := 0 to Chunk.pc - 1 do Out.hex(U64(Chunk.text[i]), 2); end; + Out.ln; + for i := 0 to Chunk.numFixups - 1 do + Fmt.print("F {} {} {}\n", [Fmt.int(Chunk.fixups[i].at), Fmt.int(Chunk.fixups[i].chunk), Fmt.int(Chunk.fixups[i].addend)]); + end; + X64.list(-1); +end; + +end X64Dump. diff --git a/self/test/genasm.py b/self/test/genasm.py new file mode 100644 index 0000000..5749c55 --- /dev/null +++ b/self/test/genasm.py @@ -0,0 +1,244 @@ +#!/usr/bin/env python3 +"""Writes the files the assembler of X64 is tested on, into the directory +given: valid.raz, a long run of instructions of every kind the assembler +knows, and one small file for each error it reports. Each ends in `end`, +as a code procedure's body does. Fixed seed: the same files each run.""" +import random, sys, os + +random.seed(7) +out = sys.argv[1] +os.makedirs(out, exist_ok=True) + +R64 = "rax rcx rdx rbx rsp rbp rsi rdi r8 r9 r10 r11 r12 r13 r14 r15".split() +R32 = "eax ecx edx ebx esp ebp esi edi r8d r9d r10d r11d r12d r13d r14d r15d".split() +R16 = "ax cx dx bx sp bp si di r8w r9w r10w r11w r12w r13w r14w r15w".split() +R8 = "al cl dl bl spl bpl sil dil r8b r9b r10b r11b r12b r13b r14b r15b".split() +BY = {8: R64, 4: R32, 2: R16, 1: R8} +PRE = {8: "qword ", 4: "dword ", 2: "word ", 1: "byte "} +XM = ["xmm%d" % i for i in range(16)] +CC = "o no b ae e ne be a s ns p np l ge le g c nae nc nb z nz na nbe nge nl ng nle".split() + + +def reg(size=8): + return random.choice(BY[size]) + + +def mem(size=0): + k = random.randrange(8) + b = random.choice(R64) + i = random.choice([r for r in R64 if r != "rsp"]) + d = random.choice([0, 8, -8, 127, -128, 128, 4096, -4096, 100000]) + s = random.choice([1, 2, 4, 8]) + p = PRE[size] if size else "" + if k == 0: + t = "[%s]" % b + elif k == 1: + t = "[%s + %d]" % (b, abs(d)) if d >= 0 else "[%s - %d]" % (b, -d) + elif k == 2: + t = "[%s + %s * %d]" % (b, i, s) + elif k == 3: + t = "[%s + %s * %d + %d]" % (b, i, s, abs(d)) if d >= 0 else "[%s + %s * %d - %d]" % (b, i, s, -d) + elif k == 4: + t = "[%s + %s]" % (b, i) + elif k == 5: + t = "[%s + 0]" % b + elif k == 6: + t = "[rsp + %d]" % abs(d) + else: + t = "[%s - %d]" % (b, abs(d) + 1) + return p + t + + +def imm(size): + if size == 1: + return str(random.choice([0, 1, -1, 127, 255, -128, 77])) + if size == 2: + return str(random.choice([0, 1, -1, 300, 32767, -32768, 255, 65535])) + return str(random.choice([0, 1, -1, 127, 128, -128, -129, 100000, -100000, 2147483647, -2147483648, 4294967295])) + + +def size(): + return random.choice([1, 2, 4, 8]) + + +lines = [] + + +def emit(s): + lines.append(" " + s + ";") + + +for n in range(900): + k = random.randrange(40) + sz = size() + if k < 6: + op = random.choice("add or adc sbb and sub xor cmp".split()) + f = random.randrange(5) + if f == 0: + emit("%s %s, %s" % (op, reg(sz), reg(sz))) + elif f == 1: + emit("%s %s, %s" % (op, reg(sz), mem(sz if random.random() < .5 else 0))) + elif f == 2: + emit("%s %s, %s" % (op, mem(sz if random.random() < .5 else 0), reg(sz))) + elif f == 3: + emit("%s %s, %s" % (op, reg(sz), imm(sz))) + else: + emit("%s %s, %s" % (op, mem(sz), imm(sz))) + elif k < 10: + f = random.randrange(5) + if f == 0: + emit("mov %s, %s" % (reg(sz), reg(sz))) + elif f == 1: + emit("mov %s, %s" % (reg(sz), mem())) + elif f == 2: + emit("mov %s, %s" % (mem(), reg(sz))) + elif f == 3: + v = random.choice([0, 5, -5, 2147483647, 4294967295, 4294967296, -2147483649, 123456789012345]) + emit("mov %s, %d" % (reg(8 if sz >= 4 else sz) if sz >= 4 else reg(sz), v if sz == 8 else (v % 65536 if sz == 2 else v % 256 if sz == 1 else v % 4294967296))) + else: + emit("mov %s, %s" % (mem(sz), imm(sz))) + elif k == 10: + emit("test %s, %s" % (reg(sz), random.choice([reg(sz), imm(sz) if sz != 1 else "1"]))) + elif k == 11: + emit("xchg %s, %s" % (random.choice([reg(sz), mem()]), reg(sz))) + elif k == 12: + emit("%slock %s %s, %s" % ("", random.choice(["cmpxchg", "xadd"]), mem(), reg(sz))) + elif k == 13: + emit("lea %s, %s" % (reg(random.choice([2, 4, 8])), mem())) + elif k == 14: + op = random.choice(["movzx", "movsx"]) + emit("%s %s, %s" % (op, reg(random.choice([2, 4, 8])), random.choice([mem(random.choice([1, 2])), reg(random.choice([1, 2]))]))) + elif k == 15: + emit("movsxd %s, %s" % (reg(8), random.choice([mem(4), reg(4)]))) + elif k == 16: + emit("%s %s" % (random.choice("not neg mul imul div idiv inc dec".split()), random.choice([reg(sz), mem(sz)]))) + elif k == 17: + emit("imul %s" % ", ".join([reg(sz if sz > 1 else 4), random.choice([reg(sz if sz > 1 else 4)] * 1 + [mem()])] + ([imm(sz if sz > 1 else 4)] if random.random() < .4 else [])).replace("%", "%")) + elif k == 18: + op = random.choice("rol ror rcl rcr shl shr sal sar".split()) + emit("%s %s, %s" % (op, random.choice([reg(sz), mem(sz)]), random.choice([str(random.randrange(64)), "cl"]))) + elif k == 19: + emit("%s %s" % (random.choice(["push", "pop"]), reg(8))) + elif k == 20: + op = random.choice(["call", "jmp"]) + emit("%s %s" % (op, random.choice([reg(8), mem()]) if op == "call" else mem())) + elif k == 21: + emit("set%s %s" % (random.choice(CC), random.choice([reg(1), mem(1)]))) + elif k == 22: + emit("cmov%s %s, %s" % (random.choice(CC), reg(random.choice([2, 4, 8])), random.choice([reg(8), mem()]))) + elif k == 23: + op = random.choice("sqrt add mul sub min div max".split()) + random.choice(["sd", "ss"]) + emit("%s %s, %s" % (op, random.choice(XM), random.choice([random.choice(XM), mem()]))) + elif k == 24: + op = random.choice("punpcklbw punpcklwd pcmpeqb pand pandn por pxor paddb psubb".split()) + emit("%s %s, %s" % (op, random.choice(XM), random.choice([random.choice(XM), mem()]))) + elif k == 25: + emit("pshufd %s, %s, %d" % (random.choice(XM), random.choice([random.choice(XM), mem()]), random.randrange(256))) + elif k == 26: + op = random.choice(["movdqu", "movdqa"]) + if random.random() < .5: + emit("%s %s, %s" % (op, random.choice(XM), random.choice([random.choice(XM), mem()]))) + else: + emit("%s %s, %s" % (op, mem(), random.choice(XM))) + elif k == 27: + emit("pmovmskb %s, %s" % (reg(4), random.choice(XM))) + elif k == 28: + emit("%s %s, %s" % (random.choice("bsf bsr tzcnt lzcnt popcnt".split()), reg(random.choice([4, 8])), random.choice([reg(8), mem()]))) + elif k == 29: + op = random.choice(["movsd", "movss"]) + if random.random() < .5: + emit("%s %s, %s" % (op, random.choice(XM), random.choice([random.choice(XM), mem()]))) + else: + emit("%s %s, %s" % (op, mem(), random.choice(XM))) + elif k == 30: + op = random.choice(["movq", "movd"]) + if random.random() < .5: + emit("%s %s, %s" % (op, random.choice(XM), random.choice([reg(8), mem()]))) + else: + emit("%s %s, %s" % (op, random.choice([reg(8), mem()]), random.choice(XM))) + elif k == 31: + emit("%s %s, %s" % (random.choice(["ucomisd", "ucomiss"]), random.choice(XM), random.choice([random.choice(XM), mem()]))) + elif k == 32: + emit("%s %s, %s" % (random.choice(["cvtsi2sd", "cvtsi2ss"]), random.choice(XM), random.choice([reg(random.choice([4, 8])), mem(random.choice([4, 8]))]))) + elif k == 33: + emit("%s %s, %s" % (random.choice(["cvttsd2si", "cvttss2si"]), reg(random.choice([4, 8])), random.choice([random.choice(XM), mem()]))) + elif k == 34: + emit("%s %s, %s" % (random.choice(["cvtsd2ss", "cvtss2sd"]), random.choice(XM), random.choice([random.choice(XM), mem()]))) + elif k == 35: + emit(random.choice("ret leave syscall cpuid rdtsc pause nop ud2 int3 hlt cqo cdq mfence lfence sfence".split())) + elif k == 36: + emit("db " + ", ".join(str(random.choice([0, 1, 255, 128, 77, -1, -128])) for _ in range(random.randrange(1, 6)))) + elif k == 37: + lines.append(" L%d:" % n) + lines.append(" add rax, 1;") + lines.append(" j%s L%d;" % (random.choice(CC), n)) + lines.append(" jmp L%d;" % n) + elif k == 38: + lines.append(" jmp F%d;" % n) + lines.append(" nop;") + lines.append(" j%s F%d;" % (random.choice(CC), n)) + lines.append(" F%d:" % n) + else: + emit("lock add %s, %s" % (mem(sz), reg(sz))) + +open(os.path.join(out, "valid.raz"), "w").write("\n".join(lines) + "\n end\n") + +errors = { + "empty": "", + "badop": "foo rax;", + "noinsn": "42;", + "nosemi": "nop", + "undefined": "jmp nowhere;", + "twice": "a: nop; a: nop;", + "toomany": "add rax, rbx, rcx, rdx;", + "movimm": "mov 1, 2;", + "movmm": "mov [rax], [rbx];", + "addimm": "add 1, rax;", + "pushmem": "push [rax];", + "pushsmall": "push eax;", + "badmem": "mov rax, [rsi * 4];", + "badscale": "mov rax, [rsi + rdi * 3];", + "nomem": "mov rax, [];", + "unclosed": "mov rax, [rbx;", + "shiftcl": "shl rax, dl;", + "shiftimm": "shl 3, 1;", + "lea": "lea rax, rbx;", + "movzx": "movzx rax, rbx;", + "movzx4": "movzx rax, dword [rbx];", + "setsize": "sete rax;", + "cmovimm": "cmove rax, 5;", + "sse": "addsd rax, xmm1;", + "sse1": "addsd xmm1;", + "pshufd": "pshufd xmm1, xmm2;", + "pand3": "pand xmm1, xmm2, 3;", + "movdq": "movdqu rax, xmm1;", + "pmov": "pmovmskb xmm1, rax;", + "bits": "popcnt ax, bx;", + "movsd": "movsd rax, xmm1;", + "movq": "movq rax, rbx;", + "ucomi": "ucomisd rax, xmm1;", + "cvtsi": "cvtsi2sd rax, xmm1;", + "cvtt": "cvttsd2si xmm1, xmm2;", + "cvtss": "cvtss2sd rax, xmm1;", + "plainops": "ret rax;", + "dbrange": "db 256;", + "dbneg": "db -129;", + "imul1": "imul rax, 5;", + "imulmem": "imul [rax], rbx;", + "unary2": "not rax, rbx;", + "unaryimm": "neg 5;", + "inc": "inc 5;", + "xchgimm": "xchg rax, 5;", + "cmpxchg": "cmpxchg rax, 5;", + "calli": "call 5;", + "jmpimm": "jmp 5;", + "labels65": "".join("l%d: nop; " % i for i in range(65)), + "xmm16": "addsd xmm16, xmm1;", + "noend": None, +} +for name, body in errors.items(): + if body is None: + text = " nop;\n" + else: + text = " " + body + "\n end\n" + open(os.path.join(out, "err_%s.raz" % name), "w").write(text)