Files
ww/cmd/6l/main.c
Hojun-Cho 1657bdeda3 ww: import toolchain — C bootstrap + ww-side self-host (phases 0-10)
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.
2026-05-11 02:17:47 +09:00

74 lines
1.9 KiB
C

/*
* 6l — amd64 static linker. Reads relocatable ELF .o files, resolves,
* relocates, writes a static ELF executable.
*
* 6l -o out file1.o file2.o ...
*
* The first symbol named "_start" defined among the inputs becomes
* the entry point. If none is found, fall back to "main".
*/
#include "l.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main(int argc, char **argv)
{
const char *out = NULL;
const char **inputs = calloc(argc, sizeof *inputs);
int ninputs = 0;
u64 base = 0x400000;
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "-o") == 0 && i + 1 < argc) {
out = argv[++i];
} else if (argv[i][0] == '-') {
fprintf(stderr, "6l: unknown flag %s\n", argv[i]);
return 2;
} else {
inputs[ninputs++] = argv[i];
}
}
if (out == NULL || ninputs == 0) {
fputs("usage: 6l -o exe file1.o [file2.o...]\n", stderr);
return 2;
}
Lnk l = {0};
/* Seed the symbol table with the entry point so archive pulls
* include the .o that defines it. Without this, a libwwrt.a
* containing start.o is silently skipped if no user .o
* references _start, and the entry falls back to main — which
* has no proper exit path. */
(void)l_intern(&l, "_start");
for (int i = 0; i < ninputs; i++) {
if (l_load(&l, inputs[i]) != 0) return 1;
}
if (l_resolve(&l) != 0) return 1;
if (l_relocate(&l, base + 0x1000) != 0) return 1;
Lsym *entry = l_lookup(&l, "_start");
if (entry == NULL || !entry->defined) entry = l_lookup(&l, "main");
if (entry == NULL || !entry->defined) {
fprintf(stderr, "6l: no _start or main symbol defined\n");
return 1;
}
FILE *f = fopen(out, "wb");
if (f == NULL) {
fprintf(stderr, "6l: cannot open %s\n", out);
return 1;
}
int rc = l_emit_elf(&l, f, base, base + 0x1000 + entry->val);
fclose(f);
if (rc == 0) {
/* chmod +x */
char cmd[1024];
snprintf(cmd, sizeof cmd, "chmod +x %s", out);
(void)system(cmd);
}
free(inputs);
return rc;
}