Spec M5 — #section, #opcode, emit(), reloc(), sys.mc via svc
Prerequisite: M4. This is the milestone that proves "emit object-file code and say where it goes".
Parser / directives #
#section SEG SECT FLAGS[ ALIGN]: creates (or selects) the section viasec_newand makes it the current section for functions and globals declared after it, until the next#section.#sectionwith no arguments reverts to the default. Flags is a folded constant (e.g.0x80000400).#opcode name(p1, p2, ...) EXPR: registers an encoder in a linear table{name, params, tmpl}. A callname(args)in a function body: each arg must fold to a constant (otherwise error "non-constant #opcode argument"); the template is folded with the parameters substituted and the resulting 32-bit word goes into the instruction buffer asI_RAW. Not a symbol.emit(CONST): same effect, a raw word.reloc(TYPE, "symbol"): registers a relocation for the next word emitted in the function;TYPE∈BRANCH26 PAGE21 PAGEOFF12 UNSIGNED(predefined constants, internal#defines). An unknown symbol becomes an undefined external (sym_ref).- The encoder table and the current section are flat data, in insertion order.
Codegen #
I_RAWin the buffer carries the word;--dump-asmprints.word 0x.........- The pending relocation from
reloc()is attached to the offset of the nextI_RAW/instruction. - Uphold the plan's promise: the prologue writes args to the frame without touching
x0..x7, and the return value of a function that ends withsvcis thex0left by the syscall (the epilogue does not touch x0 when there is noreturn).
Library #
lib/sys_svc.mc: the same interface aslib/sys.mc(open/read/write/close/exit) implemented with#opcode mov16(rd, imm) 0xD2800000 | (imm << 5) | rd,#opcode svc(imm) 0xD4000001 | (imm << 5)and BSD numbersexit=1 read=3 write=4 open=5 close=6.
Tests #
030-section.mc: a function in__TEXT,__hotand a global in__DATA,__tbl→otool -lshows the sections; the program runs → 42.031-opcode.mc:#opcodeformovzused in a function that returns 42 withoutreturn.032-svc.mc:#include "../lib/sys_svc.mc";write(1, "hi\n", 3)via svc → stdouthi\n.033-reloc.mc:reloc(BRANCH26, "_helper"); emit(0x94000000);calling a function from the same file → 42;otool -rshows the relocation.
Acceptance #
make test green; otool -r/otool -l of the 030 and 033 .o files attached to the report.