C bootstrap (phases 0-9):
cmd/wwc, cmd/6c, cmd/6a, cmd/6l, cmd/ww, rt, lib/*.
ww-side self-host (phase 10):
selfhost/cmd/wwc — ww-cgen frontend; bootstrap fixed point.
selfhost/cmd/6a — assembler; byte-identical to C 6a (test 991).
selfhost/cmd/6l — linker w/ archive (.a) support; byte-identical
to C 6l (test 992).
selfhost/cmd/ww — driver (build/run/version); byte-identical to
C ww (test 993).
make test: 15/15. make bootstrap: ww2.s == ww3.s, ww2.o == ww3.o,
ww2 == ww3 byte-identical, with the full ww-tooled chain.
90 lines
1.9 KiB
C
90 lines
1.9 KiB
C
/*
|
|
* out.c — emit a static ELF64 executable.
|
|
*
|
|
* Layout (file order):
|
|
* [0..64) ELF header
|
|
* [64..120) program header (one PT_LOAD)
|
|
* [120..0x1000) zero pad
|
|
* [0x1000..) .text bytes
|
|
*
|
|
* The single PT_LOAD covers the whole file, R+X. No interpreter,
|
|
* no dynamic, no .bss yet. Entry point is the address of the
|
|
* symbol named "_start" (or whatever main supplies via -e).
|
|
*/
|
|
#include "l.h"
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
#define ET_EXEC 2
|
|
#define EM_X86_64 62
|
|
#define EV_CURRENT 1
|
|
#define ELFCLASS64 2
|
|
#define ELFDATA2LSB 1
|
|
|
|
#define PT_LOAD 1
|
|
#define PF_X 1
|
|
#define PF_W 2
|
|
#define PF_R 4
|
|
|
|
#pragma pack(push, 1)
|
|
typedef struct {
|
|
u8 e_ident[16];
|
|
u16 e_type, e_machine;
|
|
u32 e_version;
|
|
u64 e_entry, e_phoff, e_shoff;
|
|
u32 e_flags;
|
|
u16 e_ehsize, e_phentsize, e_phnum, e_shentsize, e_shnum, e_shstrndx;
|
|
} Ehdr;
|
|
|
|
typedef struct {
|
|
u32 p_type, p_flags;
|
|
u64 p_offset, p_vaddr, p_paddr;
|
|
u64 p_filesz, p_memsz, p_align;
|
|
} Phdr;
|
|
#pragma pack(pop)
|
|
|
|
int
|
|
l_emit_elf(Lnk *l, FILE *f, u64 base, u64 entry)
|
|
{
|
|
const u64 text_off = 0x1000;
|
|
const u64 text_va = base + text_off;
|
|
const u64 filesz = text_off + l->textlen;
|
|
|
|
Ehdr eh = {0};
|
|
memcpy(eh.e_ident, "\x7f""ELF", 4);
|
|
eh.e_ident[4] = ELFCLASS64;
|
|
eh.e_ident[5] = ELFDATA2LSB;
|
|
eh.e_ident[6] = EV_CURRENT;
|
|
eh.e_type = ET_EXEC;
|
|
eh.e_machine = EM_X86_64;
|
|
eh.e_version = EV_CURRENT;
|
|
eh.e_entry = entry;
|
|
eh.e_phoff = sizeof(Ehdr);
|
|
eh.e_ehsize = sizeof(Ehdr);
|
|
eh.e_phentsize = sizeof(Phdr);
|
|
eh.e_phnum = 1;
|
|
(void)text_va;
|
|
|
|
Phdr ph = {0};
|
|
ph.p_type = PT_LOAD;
|
|
ph.p_flags = PF_R | PF_X;
|
|
ph.p_offset = 0;
|
|
ph.p_vaddr = base;
|
|
ph.p_paddr = base;
|
|
ph.p_filesz = filesz;
|
|
ph.p_memsz = filesz;
|
|
ph.p_align = 0x1000;
|
|
|
|
fwrite(&eh, 1, sizeof eh, f);
|
|
fwrite(&ph, 1, sizeof ph, f);
|
|
|
|
/* pad to text_off */
|
|
long here = ftell(f);
|
|
for (long i = here; i < (long)text_off; i++) fputc(0, f);
|
|
|
|
if (l->textlen) fwrite(l->text, 1, l->textlen, f);
|
|
|
|
return 0;
|
|
}
|