/* * 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 #include #include 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; }