aruu

[MIRROR] Actual replacement for Busybox | suckless
git clone https://git.daat.foo/aruu.git
Log | Files | Refs | README | LICENSE

ld.c (36676B)


      1 /*
      2  * ld - static ELF linker
      3  * based on neatld by ali gholami rudi (ISC license)
      4  *
      5  * permission to use, copy, modify, and/or distribute this software for any
      6  * purpose with or without fee is hereby granted, provided that the above
      7  * copyright notice and this permission notice appear in all copies
      8  */
      9 
     10 #include "ld.h"
     11 #include "ld_arch.h"
     12 
     13 #include <ctype.h>
     14 #include <fcntl.h>
     15 #include <sys/stat.h>
     16 #include <unistd.h>
     17 
     18 /* config */
     19 static unsigned long sec_vaddr[3] = {0x400000};
     20 static unsigned long sec_laddr[3] = {0x400000};
     21 static int           sec_set[3]   = {1};
     22 static int           secalign     = 16;
     23 static char         *entry        = "_start";
     24 static int           e_machine;
     25 static int           e_flags;
     26 static int           nosyms;
     27 static char         *libdirs[MAXLIBDIRS];
     28 static int           nlibdirs;
     29 static char         *mapfile;
     30 
     31 /* runtime-selected arch backend, set when first object is loaded */
     32 static const struct ld_arch_backend *ld_arch;
     33 
     34 void
     35 die(char *msg)
     36 {
     37   fprintf(stderr, "ld: %s\n", msg);
     38   exit(1);
     39 }
     40 
     41 void
     42 die_undef(char *name)
     43 {
     44   fprintf(stderr, "ld: %s undefined\n", name);
     45   exit(1);
     46 }
     47 
     48 void
     49 die_reloc(char *name, unsigned long value)
     50 {
     51   fprintf(stderr, "ld: %s value 0x%lx out of range\n", name, value);
     52   exit(1);
     53 }
     54 
     55 void
     56 die_dup(char *name)
     57 {
     58   fprintf(stderr, "ld: duplicate symbol %s\n", name);
     59   exit(1);
     60 }
     61 
     62 static Elf_Sym *
     63 obj_find(struct obj *obj, char *name)
     64 {
     65   int i;
     66   for (i = 0; i < obj->nsyms; i++) {
     67     Elf_Sym *sym = &obj->syms[i];
     68     if (ELF_ST_BIND(sym->st_info) == STB_LOCAL || sym->st_shndx == SHN_UNDEF)
     69       continue;
     70     if (!strcmp(name, obj->symstr + sym->st_name))
     71       return sym;
     72   }
     73   return NULL;
     74 }
     75 
     76 static void
     77 obj_init(struct obj *obj, char *mem)
     78 {
     79   int i;
     80   obj->mem   = mem;
     81   obj->ehdr  = (void *)mem;
     82   obj->shdr  = (void *)(mem + obj->ehdr->e_shoff);
     83   obj->shstr = mem + obj->shdr[obj->ehdr->e_shstrndx].sh_offset;
     84   for (i = 0; i < obj->ehdr->e_shnum; i++) {
     85     if (obj->shdr[i].sh_type != SHT_SYMTAB)
     86       continue;
     87     obj->symstr = mem + obj->shdr[obj->shdr[i].sh_link].sh_offset;
     88     obj->syms   = (void *)(mem + obj->shdr[i].sh_offset);
     89     obj->nsyms  = obj->shdr[i].sh_size / sizeof(*obj->syms);
     90   }
     91 }
     92 
     93 static void
     94 outelf_init(struct outelf *oe)
     95 {
     96   memset(oe, 0, sizeof(*oe));
     97   oe->ehdr.e_ident[0]  = 0x7f;
     98   oe->ehdr.e_ident[1]  = 'E';
     99   oe->ehdr.e_ident[2]  = 'L';
    100   oe->ehdr.e_ident[3]  = 'F';
    101   oe->ehdr.e_ident[4]  = ELFCLASS;
    102   oe->ehdr.e_ident[5]  = ELFDATA2LSB;
    103   oe->ehdr.e_ident[6]  = EV_CURRENT;
    104   oe->ehdr.e_type      = ET_EXEC;
    105   oe->ehdr.e_version   = EV_CURRENT;
    106   oe->ehdr.e_shstrndx  = SHN_UNDEF;
    107   oe->ehdr.e_ehsize    = sizeof(oe->ehdr);
    108   oe->ehdr.e_phentsize = sizeof(oe->phdr[0]);
    109   oe->ehdr.e_shentsize = sizeof(Elf_Shdr);
    110 }
    111 
    112 struct secmap *
    113 outelf_mapping(struct outelf *oe, Elf_Shdr *shdr)
    114 {
    115   int i;
    116   for (i = 0; i < oe->nsecs; i++)
    117     if (oe->secs[i].o_shdr == shdr)
    118       return &oe->secs[i];
    119   return NULL;
    120 }
    121 
    122 static int
    123 outelf_find(struct outelf *oe, char *name, struct obj **sym_obj, Elf_Sym **sym_sym)
    124 {
    125   int         i;
    126   struct obj *strong_obj = NULL;
    127   struct obj *weak_obj   = NULL;
    128   Elf_Sym    *strong_sym = NULL;
    129   Elf_Sym    *weak_sym   = NULL;
    130 
    131   /* a strong definition overrides a weak one whatever the link order.
    132    * musl libc.a depends on it (weak default in one member, strong
    133    * implementation in another), so the first match is not enough */
    134   for (i = 0; i < oe->nobjs; i++) {
    135     struct obj *obj = &oe->objs[i];
    136     Elf_Sym    *sym;
    137     if (!(sym = obj_find(obj, name)))
    138       continue;
    139     if (ELF_ST_BIND(sym->st_info) != STB_WEAK) {
    140       if (strong_obj)
    141         die_dup(name);
    142       strong_obj = obj;
    143       strong_sym = sym;
    144     } else if (!weak_obj) {
    145       weak_obj = obj;
    146       weak_sym = sym;
    147     }
    148   }
    149   if (strong_obj) {
    150     *sym_obj = strong_obj;
    151     *sym_sym = strong_sym;
    152     return 0;
    153   }
    154   if (weak_obj) {
    155     *sym_obj = weak_obj;
    156     *sym_sym = weak_sym;
    157     return 0;
    158   }
    159   return 1;
    160 }
    161 
    162 static unsigned long
    163 bss_addr(struct outelf *oe, Elf_Sym *sym)
    164 {
    165   int i;
    166   for (i = 0; i < oe->nbss_syms; i++)
    167     if (oe->bss_syms[i].sym == sym)
    168       return oe->bss_vaddr + oe->bss_syms[i].off;
    169   return 0;
    170 }
    171 
    172 /* linker-defined symbols for section boundaries, empty for static
    173  * binaries without constructors */
    174 static int
    175 is_ldsym(char *name)
    176 {
    177   return !strcmp(name, "__init_array_start") || !strcmp(name, "__init_array_end")
    178          || !strcmp(name, "__fini_array_start") || !strcmp(name, "__fini_array_end")
    179          || !strcmp(name, "__preinit_array_start") || !strcmp(name, "__preinit_array_end")
    180          || !strcmp(name, "__ehdr_start") || !strcmp(name, "__executable_start");
    181 }
    182 
    183 static unsigned long
    184 ldsym_val(struct outelf *oe, char *name)
    185 {
    186   if (!strcmp(name, "__ehdr_start") || !strcmp(name, "__executable_start"))
    187     return sec_vaddr[I_CS];
    188   return oe->bss_vaddr + oe->bss_len;
    189 }
    190 
    191 static unsigned long
    192 symval(struct outelf *oe, struct obj *obj, Elf_Sym *sym)
    193 {
    194   struct secmap *sec;
    195   char          *name = obj ? obj->symstr + sym->st_name : NULL;
    196   int            s_idx, s_off;
    197 
    198   switch (ELF_ST_TYPE(sym->st_info)) {
    199     case STT_SECTION:
    200       if ((sec = outelf_mapping(oe, &obj->shdr[sym->st_shndx]))) {
    201         if (obj->shdr[sym->st_shndx].sh_flags & SHF_TLS)
    202           return sec->vaddr - oe->tls_size;
    203         return sec->vaddr;
    204       }
    205       break;
    206     case STT_NOTYPE:
    207     case STT_OBJECT:
    208     case STT_FUNC:
    209     case STT_TLS:
    210       /* a weak global stays overridable when the sym entry of this relocation
    211        * defines it locally (st_shndx != SHN_UNDEF). musl libc.a has the weak
    212        * default and the strong definition in different members, and every
    213        * reference must bind to the strong one */
    214       if (name && *name && (sym->st_shndx == SHN_UNDEF || ELF_ST_BIND(sym->st_info) == STB_WEAK)) {
    215         if (outelf_find(oe, name, &obj, &sym)) {
    216           if (is_ldsym(name))
    217             return ldsym_val(oe, name);
    218           /* weak undefined symbols resolve to 0 */
    219           if (ELF_ST_BIND(sym->st_info) == STB_WEAK)
    220             return 0;
    221           else
    222             die_undef(name);
    223         }
    224       }
    225       if (sym->st_shndx == SHN_COMMON)
    226         return bss_addr(oe, sym);
    227       s_idx = sym->st_shndx;
    228       s_off = sym->st_value;
    229       if ((sec = outelf_mapping(oe, &obj->shdr[s_idx]))) {
    230         /* variant ii: a tls symbol address is tp-relative, so return its offset
    231          * from the thread pointer instead of a runtime address */
    232         if (obj->shdr[s_idx].sh_flags & SHF_TLS)
    233           return sec->vaddr + s_off - oe->tls_size;
    234         return sec->vaddr + s_off;
    235       }
    236   }
    237   return 0;
    238 }
    239 
    240 static unsigned long
    241 outelf_addr(struct outelf *oe, char *name)
    242 {
    243   struct obj *obj;
    244   Elf_Sym    *sym;
    245 
    246   if (is_ldsym(name))
    247     return ldsym_val(oe, name);
    248 
    249   if (outelf_find(oe, name, &obj, &sym))
    250     die_undef(name);
    251   return symval(oe, obj, sym);
    252 }
    253 
    254 static void
    255 outelf_got_prescan(struct outelf *oe)
    256 {
    257   int i, j, k, g;
    258   for (i = 0; i < oe->nobjs; i++) {
    259     struct obj *obj = &oe->objs[i];
    260     for (j = 0; j < obj->ehdr->e_shnum; j++) {
    261       Elf_Shdr *rs = &obj->shdr[j];
    262       Elf_Rela *rels;
    263       int       nrels;
    264       if (rs->sh_type != SHT_REL_)
    265         continue;
    266       rels  = (Elf_Rela *)(obj->mem + rs->sh_offset);
    267       nrels = rs->sh_size / sizeof(*rels);
    268       for (k = 0; k < nrels; k++) {
    269         Elf_Rela *rel     = (void *)&rels[k];
    270         int       type    = ELF_R_TYPE(rel->r_info);
    271         int       sym_idx = ELF_R_SYM(rel->r_info);
    272         if (!ld_arch || !ld_arch->is_got_rel(type))
    273           continue;
    274         /* sym_idx is unique only within its own object, so obj_idx must match
    275          * too */
    276         for (g = 0; g < oe->ngot; g++)
    277           if (oe->got[g].sym_idx == sym_idx && oe->got[g].obj_idx == i)
    278             break;
    279         if (g == oe->ngot) {
    280           if (oe->ngot >= MAXGOT)
    281             die("ld: too many got entries");
    282           oe->got[oe->ngot].sym_idx = sym_idx;
    283           oe->got[oe->ngot].obj_idx = i;
    284           oe->ngot++;
    285         }
    286       }
    287     }
    288   }
    289 }
    290 
    291 static void
    292 outelf_reloc_sec(struct outelf *oe, int o_idx, int s_idx)
    293 {
    294   struct obj    *obj        = &oe->objs[o_idx];
    295   Elf_Shdr      *rel_shdr   = &obj->shdr[s_idx];
    296   Elf_Rela      *rels       = (Elf_Rela *)(obj->mem + obj->shdr[s_idx].sh_offset);
    297   Elf_Shdr      *other_shdr = &obj->shdr[rel_shdr->sh_info];
    298   char          *other      = obj->mem + other_shdr->sh_offset;
    299   int            nrels      = rel_shdr->sh_size / sizeof(*rels);
    300   struct secmap *other_sec  = outelf_mapping(oe, other_shdr);
    301   int            i;
    302 
    303   /* relocations against a section dropped from the output (eh_frame,
    304    * notes, debug info) have nothing to apply to */
    305   if (!other_sec)
    306     return;
    307 
    308   for (i = 0; i < nrels; i++) {
    309     Elf_Rela       *rel     = (void *)&rels[i];
    310     int             sym_idx = ELF_R_SYM(rel->r_info);
    311     Elf_Sym        *sym     = &obj->syms[sym_idx];
    312     struct ld_reloc r;
    313     r.type        = ELF_R_TYPE(rel->r_info);
    314     r.val         = symval(oe, obj, sym) + REL_ADDEND(rel);
    315     r.dst         = (unsigned long *)(other + rel->r_offset);
    316     r.addr        = other_sec->vaddr + rel->r_offset;
    317     r.oe          = oe;
    318     r.target_shdr = other_shdr;
    319     r.sym_idx     = sym_idx;
    320     r.obj_idx     = o_idx;
    321     r.addend      = REL_ADDEND(rel);
    322     ld_arch->reloc_apply(&r);
    323   }
    324 }
    325 
    326 static void
    327 outelf_reloc(struct outelf *oe)
    328 {
    329   int i, j;
    330   for (i = 0; i < oe->nobjs; i++) {
    331     struct obj *obj = &oe->objs[i];
    332     for (j = 0; j < obj->ehdr->e_shnum; j++)
    333       if (obj->shdr[j].sh_type == SHT_REL_)
    334         outelf_reloc_sec(oe, i, j);
    335   }
    336 }
    337 
    338 static void
    339 alloc_bss(struct outelf *oe, Elf_Sym *sym)
    340 {
    341   int n               = oe->nbss_syms++;
    342   int off             = ALIGN(oe->bss_len, MAX(sym->st_value, 4));
    343   oe->bss_syms[n].sym = sym;
    344   oe->bss_syms[n].off = off;
    345   oe->bss_len         = off + sym->st_size;
    346 }
    347 
    348 static void
    349 outelf_bss(struct outelf *oe)
    350 {
    351   int i, j;
    352   for (i = 0; i < oe->nobjs; i++) {
    353     struct obj *obj = &oe->objs[i];
    354     for (j = 0; j < obj->nsyms; j++)
    355       if (obj->syms[j].st_shndx == SHN_COMMON)
    356         alloc_bss(oe, &obj->syms[j]);
    357   }
    358 }
    359 
    360 #define SEC_TLS(s)   ((s)->sh_flags & SHF_TLS)
    361 #define SEC_CODE(s)  (!SEC_TLS(s) && ((s)->sh_flags & SHF_EXECINSTR))
    362 #define SEC_BSS(s)   (!SEC_TLS(s) && (s)->sh_type == SHT_NOBITS)
    363 #define SEC_NOTE(s)  (!SEC_TLS(s) && !SEC_CODE(s) && (s)->sh_type == SHT_NOTE)
    364 #define SEC_DATA(s)  (!SEC_TLS(s) && !SEC_CODE(s) && !SEC_BSS(s) && !SEC_NOTE(s))
    365 #define SEC_TDATA(s) (SEC_TLS(s) && (s)->sh_type != SHT_NOBITS)
    366 #define SEC_TBSS(s)  (SEC_TLS(s) && (s)->sh_type == SHT_NOBITS)
    367 
    368 static int
    369 outelf_str(struct outelf *oe, char *s)
    370 {
    371   int   n = oe->nsymstr;
    372   char *d = oe->symstr + oe->nsymstr;
    373   while (*s)
    374     *d++ = *s++;
    375   *d++        = '\0';
    376   oe->nsymstr = d - oe->symstr;
    377   return n;
    378 }
    379 
    380 static void
    381 build_symtab(struct outelf *oe)
    382 {
    383   int       i, j;
    384   Elf_Sym  *syms     = oe->syms;
    385   Elf_Shdr *cs_shdr  = &oe->shdr[++oe->nsh];
    386   Elf_Shdr *ds_shdr  = &oe->shdr[++oe->nsh];
    387   Elf_Shdr *bss_shdr = &oe->shdr[++oe->nsh];
    388   Elf_Shdr *sym_shdr = &oe->shdr[++oe->nsh];
    389   Elf_Shdr *str_shdr = &oe->shdr[++oe->nsh];
    390   int       n        = 1;
    391   int       faddr    = oe->shdr_faddr;
    392 
    393   oe->nsh++;
    394   outelf_str(oe, "");
    395   sym_shdr->sh_name = outelf_str(oe, ".symtab");
    396   str_shdr->sh_name = outelf_str(oe, ".strtab");
    397   cs_shdr->sh_name  = outelf_str(oe, ".text");
    398   ds_shdr->sh_name  = outelf_str(oe, ".data");
    399   bss_shdr->sh_name = outelf_str(oe, ".bss");
    400 
    401   for (i = 0; i < oe->nobjs; i++) {
    402     struct obj *obj = &oe->objs[i];
    403     for (j = 0; j < obj->nsyms; j++) {
    404       Elf_Sym *sym  = &obj->syms[j];
    405       int      type = ELF_ST_TYPE(sym->st_info);
    406       int      bind = ELF_ST_BIND(sym->st_info);
    407       char    *name = obj->symstr + sym->st_name;
    408       if (!*name || bind == STB_LOCAL || sym->st_shndx == SHN_UNDEF)
    409         continue;
    410       syms[n].st_name  = outelf_str(oe, name);
    411       syms[n].st_info  = ELF64_ST_INFO(bind, type);
    412       syms[n].st_value = symval(oe, obj, sym);
    413       syms[n].st_size  = sym->st_size;
    414       syms[n].st_shndx = SHN_ABS;
    415       n++;
    416     }
    417   }
    418   oe->nsyms = n;
    419 
    420   oe->shdr_faddr = faddr;
    421   faddr += oe->nsh * sizeof(oe->shdr[0]);
    422   oe->syms_faddr = faddr;
    423   faddr += oe->nsyms * sizeof(oe->syms[0]);
    424   oe->symstr_faddr = faddr;
    425 
    426   oe->ehdr.e_shstrndx = str_shdr - oe->shdr;
    427   oe->ehdr.e_shoff    = oe->shdr_faddr;
    428   oe->ehdr.e_shnum    = oe->nsh;
    429 
    430   str_shdr->sh_type   = SHT_STRTAB;
    431   str_shdr->sh_offset = oe->symstr_faddr;
    432   str_shdr->sh_size   = oe->nsymstr;
    433 
    434   sym_shdr->sh_type    = SHT_SYMTAB;
    435   sym_shdr->sh_entsize = sizeof(oe->syms[0]);
    436   sym_shdr->sh_offset  = oe->syms_faddr;
    437   sym_shdr->sh_size    = oe->nsyms * sizeof(oe->syms[0]);
    438   sym_shdr->sh_link    = str_shdr - oe->shdr;
    439   sym_shdr->sh_info    = 0;
    440 
    441   cs_shdr->sh_type      = SHT_PROGBITS;
    442   cs_shdr->sh_flags     = SHF_ALLOC | SHF_EXECINSTR;
    443   cs_shdr->sh_offset    = oe->phdr[I_CS].p_offset;
    444   cs_shdr->sh_addr      = oe->phdr[I_CS].p_vaddr;
    445   cs_shdr->sh_addralign = oe->phdr[I_CS].p_align;
    446   cs_shdr->sh_size      = oe->phdr[I_CS].p_filesz;
    447 
    448   ds_shdr->sh_type      = SHT_PROGBITS;
    449   ds_shdr->sh_flags     = SHF_ALLOC | SHF_WRITE;
    450   ds_shdr->sh_offset    = oe->phdr[I_DS].p_offset;
    451   ds_shdr->sh_addr      = oe->phdr[I_DS].p_vaddr;
    452   ds_shdr->sh_addralign = oe->phdr[I_DS].p_align;
    453   ds_shdr->sh_size      = oe->phdr[I_DS].p_filesz;
    454 
    455   bss_shdr->sh_type      = SHT_NOBITS;
    456   bss_shdr->sh_flags     = SHF_ALLOC | SHF_WRITE;
    457   bss_shdr->sh_offset    = oe->phdr[I_BSS].p_offset;
    458   bss_shdr->sh_addr      = oe->phdr[I_BSS].p_vaddr;
    459   bss_shdr->sh_addralign = oe->phdr[I_BSS].p_align;
    460   bss_shdr->sh_size      = oe->phdr[I_BSS].p_filesz;
    461 }
    462 
    463 static int
    464 secmap_cmp_faddr(const void *a, const void *b)
    465 {
    466   const struct secmap *const *pa = a, *const *pb = b;
    467   if ((*pa)->faddr < (*pb)->faddr)
    468     return -1;
    469   if ((*pa)->faddr > (*pb)->faddr)
    470     return 1;
    471   return 0;
    472 }
    473 
    474 static void
    475 outelf_write(struct outelf *oe, int fd)
    476 {
    477   int             i, ncode;
    478   long            code_end = -1;
    479   struct secmap **code_secs;
    480 
    481   oe->ehdr.e_entry = outelf_addr(oe, entry) - sec_vaddr[I_CS] + sec_laddr[I_CS];
    482   if (!nosyms)
    483     build_symtab(oe);
    484   oe->ehdr.e_phnum   = oe->nph;
    485   oe->ehdr.e_phoff   = sizeof(oe->ehdr);
    486   oe->ehdr.e_machine = e_machine;
    487   oe->ehdr.e_flags   = e_flags;
    488 
    489   lseek(fd, 0, SEEK_SET);
    490   write(fd, &oe->ehdr, sizeof(oe->ehdr));
    491   write(fd, &oe->phdr, oe->nph * sizeof(oe->phdr[0]));
    492 
    493   /* link_cs groups sections by name (.init, .fini, the rest), not by
    494    * oe->secs[] order, so the index no longer implies faddr. the gap fill
    495    * below needs true faddr order */
    496   code_secs = malloc(oe->nsecs * sizeof(*code_secs));
    497   ncode     = 0;
    498   for (i = 0; i < oe->nsecs; i++)
    499     if (SEC_CODE(oe->secs[i].o_shdr))
    500       code_secs[ncode++] = &oe->secs[i];
    501   qsort(code_secs, ncode, sizeof(*code_secs), secmap_cmp_faddr);
    502 
    503   for (i = 0; i < ncode; i++) {
    504     struct secmap *sec = code_secs[i];
    505     char          *buf = sec->obj->mem + sec->o_shdr->sh_offset;
    506     int            len = sec->o_shdr->sh_size;
    507     /* link_cs aligns code sections but leaves the gap, which reads back as
    508      * zero and decodes as a valid instruction. fill with int3 so a stray
    509      * fall-through traps */
    510     if (code_end >= 0 && (long)sec->faddr > code_end) {
    511       long           gap = sec->faddr - code_end;
    512       unsigned char *pad = malloc(gap);
    513       memset(pad, 0xcc, gap);
    514       lseek(fd, code_end, SEEK_SET);
    515       write(fd, pad, gap);
    516       free(pad);
    517     }
    518     /* an empty section can share its address with one that has code (musl's
    519      * empty .text beside .text.strlen), and the order of equal addresses is
    520      * qsort's: the end only moves forward, or the next gap fill writes over
    521      * the code */
    522     if ((long)(sec->faddr + len) > code_end)
    523       code_end = sec->faddr + len;
    524     lseek(fd, sec->faddr, SEEK_SET);
    525     write(fd, buf, len);
    526   }
    527   free(code_secs);
    528 
    529   for (i = 0; i < oe->nsecs; i++) {
    530     struct secmap *sec = &oe->secs[i];
    531     char          *buf = sec->obj->mem + sec->o_shdr->sh_offset;
    532     int            len = sec->o_shdr->sh_size;
    533     if (SEC_BSS(sec->o_shdr) || SEC_TBSS(sec->o_shdr) || SEC_CODE(sec->o_shdr))
    534       continue;
    535     lseek(fd, sec->faddr, SEEK_SET);
    536     write(fd, buf, len);
    537   }
    538   if (oe->ngot > 0) {
    539     unsigned long *gotbuf = malloc(oe->ngot * sizeof(unsigned long));
    540     int            g;
    541     for (g = 0; g < oe->ngot; g++) {
    542       struct obj *go = &oe->objs[oe->got[g].obj_idx];
    543       Elf_Sym    *gs = &go->syms[oe->got[g].sym_idx];
    544       gotbuf[g]      = symval(oe, go, gs);
    545     }
    546     lseek(fd, oe->got_faddr, SEEK_SET);
    547     write(fd, gotbuf, oe->ngot * sizeof(unsigned long));
    548     free(gotbuf);
    549   }
    550   if (!nosyms) {
    551     lseek(fd, oe->shdr_faddr, SEEK_SET);
    552     write(fd, &oe->shdr, oe->nsh * sizeof(oe->shdr[0]));
    553     lseek(fd, oe->syms_faddr, SEEK_SET);
    554     write(fd, &oe->syms, oe->nsyms * sizeof(oe->syms[0]));
    555     lseek(fd, oe->symstr_faddr, SEEK_SET);
    556     write(fd, &oe->symstr, oe->nsymstr);
    557   }
    558 }
    559 
    560 static void
    561 outelf_add(struct outelf *oe, char *mem)
    562 {
    563   Elf_Ehdr   *ehdr = (void *)mem;
    564   Elf_Shdr   *shdr = (void *)(mem + ehdr->e_shoff);
    565   struct obj *obj;
    566   int         i;
    567 
    568   if (ehdr->e_type != ET_REL)
    569     return;
    570   e_machine = ehdr->e_machine;
    571   e_flags   = ehdr->e_flags;
    572   if (ld_arch == NULL) {
    573     ld_arch = ld_arch_select(e_machine);
    574     if (ld_arch == NULL)
    575       die("ld: unsupported architecture");
    576   } else if (e_machine != ld_arch->em_machine) {
    577     die("ld: mixed input architectures");
    578   }
    579   if (oe->nobjs >= MAXOBJS)
    580     die("ld: too many objects");
    581   obj = &oe->objs[oe->nobjs++];
    582   obj_init(obj, mem);
    583   for (i = 0; i < obj->nsyms; i++) {
    584     Elf_Sym    *sym = &obj->syms[i];
    585     struct obj *sym_obj;
    586     Elf_Sym    *sym_sym;
    587     if (ELF_ST_BIND(sym->st_info) == STB_LOCAL || sym->st_shndx == SHN_UNDEF
    588         || ELF_ST_BIND(sym->st_info) == STB_WEAK)
    589       continue;
    590     outelf_find(oe, obj->symstr + sym->st_name, &sym_obj, &sym_sym);
    591   }
    592   for (i = 0; i < ehdr->e_shnum; i++) {
    593     struct secmap *sec;
    594     if (!(shdr[i].sh_flags & 0x7))
    595       continue;
    596     if (oe->nsecs >= MAXSECS)
    597       die("ld: too many sections");
    598     sec         = &oe->secs[oe->nsecs++];
    599     sec->o_shdr = &shdr[i];
    600     sec->obj    = obj;
    601   }
    602 }
    603 
    604 static int
    605 link_cs(
    606     struct outelf *oe,
    607     Elf_Phdr      *phdr,
    608     unsigned long  faddr,
    609     unsigned long  vaddr,
    610     unsigned long  laddr,
    611     int            len
    612 )
    613 {
    614   int i, pass;
    615   /* .init/.fini of all objects are fragments of one function (crti.o
    616    * prologue, object parts, crtn.o epilogue) and must be byte-adjacent
    617    * wherever the objects sit in link order. pass 0 lays out every .init,
    618    * pass 1 every .fini, pass 2 the rest, pass 3 the notes: read only like
    619    * the code, and one run of them for the PT_NOTE segment to cover */
    620   oe->note_len = 0;
    621   for (pass = 0; pass < 4; pass++) {
    622     for (i = 0; i < oe->nsecs; i++) {
    623       struct secmap *sec = &oe->secs[i];
    624       const char    *name;
    625       int            alignment, is_init, is_fini;
    626       if (pass == 3 ? !SEC_NOTE(sec->o_shdr) : !SEC_CODE(sec->o_shdr))
    627         continue;
    628       name    = sec->obj->shstr + sec->o_shdr->sh_name;
    629       is_init = !strcmp(name, ".init");
    630       is_fini = !strcmp(name, ".fini");
    631       if ((pass == 0 && !is_init) || (pass == 1 && !is_fini) || (pass == 2 && (is_init || is_fini)))
    632         continue;
    633       alignment  = pass < 2 ? 1 : MAX(sec->o_shdr->sh_addralign, 4);
    634       len        = ALIGN(vaddr + len, alignment) - vaddr;
    635       sec->vaddr = vaddr + len;
    636       sec->faddr = faddr + len;
    637       if (pass == 3 && !oe->note_len) {
    638         oe->note_vaddr = sec->vaddr;
    639         oe->note_faddr = sec->faddr;
    640       }
    641       len += sec->o_shdr->sh_size;
    642       if (pass == 3)
    643         oe->note_len = sec->vaddr + sec->o_shdr->sh_size - oe->note_vaddr;
    644     }
    645   }
    646   phdr->p_type   = PT_LOAD;
    647   phdr->p_flags  = PF_R | PF_X;
    648   phdr->p_vaddr  = vaddr;
    649   phdr->p_paddr  = laddr;
    650   phdr->p_offset = faddr;
    651   phdr->p_filesz = len;
    652   phdr->p_memsz  = len;
    653   phdr->p_align  = PAGE_SIZE;
    654   return len;
    655 }
    656 
    657 static int
    658 link_ds(
    659     struct outelf *oe, Elf_Phdr *phdr, unsigned long faddr, unsigned long vaddr, unsigned long laddr
    660 )
    661 {
    662   int len = 0;
    663   int i;
    664   for (i = 0; i < oe->nsecs; i++) {
    665     struct secmap *sec       = &oe->secs[i];
    666     int            alignment = MAX(sec->o_shdr->sh_addralign, 4);
    667     if (!SEC_DATA(sec->o_shdr))
    668       continue;
    669     len        = ALIGN(vaddr + len, alignment) - vaddr;
    670     sec->vaddr = vaddr + len;
    671     sec->faddr = faddr + len;
    672     len += sec->o_shdr->sh_size;
    673   }
    674   len            = ALIGN(len, 4);
    675   phdr->p_type   = PT_LOAD;
    676   phdr->p_flags  = PF_R | PF_W;
    677   phdr->p_align  = PAGE_SIZE;
    678   phdr->p_vaddr  = vaddr;
    679   phdr->p_paddr  = laddr;
    680   phdr->p_filesz = len;
    681   phdr->p_memsz  = len;
    682   phdr->p_offset = faddr;
    683   return len;
    684 }
    685 
    686 static int
    687 link_bss(struct outelf *oe, Elf_Phdr *phdr, unsigned long faddr, unsigned long vaddr, int len)
    688 {
    689   int i;
    690   for (i = 0; i < oe->nsecs; i++) {
    691     struct secmap *sec       = &oe->secs[i];
    692     int            alignment = MAX(sec->o_shdr->sh_addralign, 4);
    693     if (!SEC_BSS(sec->o_shdr))
    694       continue;
    695     len        = ALIGN(vaddr + len, alignment) - vaddr;
    696     sec->vaddr = vaddr + len;
    697     sec->faddr = faddr;
    698     len += sec->o_shdr->sh_size;
    699   }
    700   phdr->p_type   = PT_LOAD;
    701   phdr->p_flags  = PF_R | PF_W;
    702   phdr->p_vaddr  = vaddr;
    703   phdr->p_paddr  = vaddr;
    704   phdr->p_offset = faddr;
    705   phdr->p_filesz = 0;
    706   phdr->p_memsz  = len;
    707   phdr->p_align  = PAGE_SIZE;
    708   return len;
    709 }
    710 
    711 /* merge every .tdata/.tbss into one tls template. variant ii (x86,
    712  * x86-64) puts tls variables below the thread pointer, so a symbol at
    713  * offset off sits at tp - (tls_size - off). tdata comes first (it has
    714  * file bytes), tbss continues the same offset so the template is
    715  * contiguous. returns 0 and adds no phdr when there is no tls section */
    716 static int
    717 link_tls(struct outelf *oe, Elf_Phdr *phdr, unsigned long faddr, unsigned long vaddr)
    718 {
    719   int i, len = 0, filesz, align = 1;
    720 
    721   for (i = 0; i < oe->nsecs; i++) {
    722     struct secmap *sec = &oe->secs[i];
    723     int            alignment;
    724     if (!SEC_TDATA(sec->o_shdr))
    725       continue;
    726     alignment  = MAX(sec->o_shdr->sh_addralign, 1);
    727     align      = MAX(align, alignment);
    728     len        = ALIGN(len, alignment);
    729     sec->vaddr = len;
    730     sec->faddr = faddr + len;
    731     len += sec->o_shdr->sh_size;
    732   }
    733   filesz = ALIGN(len, 4);
    734   len    = filesz;
    735 
    736   for (i = 0; i < oe->nsecs; i++) {
    737     struct secmap *sec = &oe->secs[i];
    738     int            alignment;
    739     if (!SEC_TBSS(sec->o_shdr))
    740       continue;
    741     alignment  = MAX(sec->o_shdr->sh_addralign, 1);
    742     align      = MAX(align, alignment);
    743     len        = ALIGN(len, alignment);
    744     sec->vaddr = len;
    745     len += sec->o_shdr->sh_size;
    746   }
    747   if (len == 0)
    748     return 0;
    749 
    750   len = ALIGN(len, align);
    751 
    752   phdr->p_type   = PT_TLS;
    753   phdr->p_flags  = PF_R;
    754   phdr->p_vaddr  = vaddr;
    755   phdr->p_paddr  = vaddr;
    756   phdr->p_offset = faddr;
    757   phdr->p_filesz = filesz;
    758   phdr->p_memsz  = len;
    759   phdr->p_align  = align;
    760 
    761   oe->tls_size   = len;
    762   oe->tls_filesz = filesz;
    763   return len;
    764 }
    765 
    766 static void
    767 outelf_link(struct outelf *oe)
    768 {
    769   unsigned long faddr, vaddr, laddr;
    770   int           len, has_tls;
    771 
    772   len   = ALIGN(sizeof(oe->ehdr) + MAXPHDRS * sizeof(oe->phdr[0]), secalign);
    773   faddr = len & ~PAGE_MASK;
    774   vaddr = sec_vaddr[I_CS];
    775   laddr = sec_laddr[I_CS];
    776   len   = link_cs(oe, &oe->phdr[0], faddr, vaddr, laddr, len & PAGE_MASK);
    777 
    778   len = ALIGN(faddr + len, secalign) - faddr;
    779   faddr += len;
    780   vaddr = sec_set[I_DS] ? sec_vaddr[I_DS] | (faddr & PAGE_MASK) : vaddr + PAGE_SIZE + len;
    781   laddr = sec_set[I_DS] ? sec_laddr[I_DS] | (faddr & PAGE_MASK) : laddr + PAGE_SIZE + len;
    782   len   = link_ds(oe, &oe->phdr[1], faddr, vaddr, laddr);
    783 
    784   outelf_got_prescan(oe);
    785 
    786   oe->got_vaddr = vaddr + len;
    787   oe->got_faddr = faddr + len;
    788   len += oe->ngot * sizeof(unsigned long);
    789   len = ALIGN(len, 4);
    790 
    791   /* tls template follows the got inside the data segment. its tbss tail
    792    * has no file bytes, like bss, so it grows p_memsz but not p_filesz */
    793   has_tls              = link_tls(oe, &oe->phdr[3], faddr + len, vaddr + len) != 0;
    794   oe->phdr[1].p_filesz = ALIGN(len + oe->tls_filesz, 4);
    795   len                  = ALIGN(len + oe->tls_size, 4);
    796   oe->phdr[1].p_memsz  = len;
    797 
    798   len = ALIGN(faddr + len, secalign) - faddr;
    799   faddr += len;
    800   vaddr = sec_set[I_BSS] ? sec_vaddr[I_BSS] | (faddr & PAGE_MASK) : vaddr + PAGE_SIZE + len;
    801   outelf_bss(oe);
    802   oe->bss_vaddr = vaddr;
    803   len           = link_bss(oe, &oe->phdr[2], faddr, vaddr, oe->bss_len);
    804 
    805   oe->nph = has_tls ? 4 : 3;
    806   if (oe->note_len) {
    807     Elf_Phdr *note = &oe->phdr[oe->nph++];
    808 
    809     note->p_type   = PT_NOTE;
    810     note->p_flags  = PF_R;
    811     note->p_vaddr  = oe->note_vaddr;
    812     note->p_paddr  = oe->note_vaddr;
    813     note->p_offset = oe->note_faddr;
    814     note->p_filesz = oe->note_len;
    815     note->p_memsz  = oe->note_len;
    816     note->p_align  = 4;
    817   }
    818   oe->shdr_faddr = faddr;
    819   outelf_reloc(oe);
    820 }
    821 
    822 /* archive (.a) handling */
    823 struct arhdr {
    824   char ar_name[16];
    825   char ar_date[12];
    826   char ar_uid[6];
    827   char ar_gid[6];
    828   char ar_mode[8];
    829   char ar_size[10];
    830   char ar_fmag[2];
    831 };
    832 
    833 static int
    834 get_be32(unsigned char *s)
    835 {
    836   return s[3] | (s[2] << 8) | (s[1] << 16) | (s[0] << 24);
    837 }
    838 
    839 static int
    840 sym_undef(struct outelf *oe, char *name)
    841 {
    842   int i, j;
    843   int undef = 0;
    844   for (i = 0; i < oe->nobjs; i++) {
    845     struct obj *obj = &oe->objs[i];
    846     for (j = 0; j < obj->nsyms; j++) {
    847       Elf_Sym *sym = &obj->syms[j];
    848       if (ELF_ST_BIND(sym->st_info) == STB_LOCAL)
    849         continue;
    850       if (strcmp(name, obj->symstr + sym->st_name))
    851         continue;
    852       if (sym->st_shndx != SHN_UNDEF)
    853         return 0;
    854       undef = 1;
    855     }
    856   }
    857   return undef;
    858 }
    859 
    860 static int
    861 outelf_ar_link(struct outelf *oe, char *ar, int base)
    862 {
    863   char *ar_index;
    864   char *ar_name;
    865   int   nsyms = get_be32((void *)ar);
    866   int   added = 0;
    867   int   i;
    868 
    869   ar_index = ar + 4;
    870   ar_name  = ar_index + nsyms * 4;
    871   for (i = 0; i < nsyms; i++) {
    872     int   off    = get_be32((void *)(ar_index + i * 4)) + sizeof(struct arhdr);
    873     char *member = ar - base + off;
    874     int   j;
    875 
    876     if (!sym_undef(oe, ar_name))
    877       goto next;
    878 
    879     for (j = 0; j < oe->nobjs; j++)
    880       if (oe->objs[j].mem == member)
    881         goto next;
    882 
    883     outelf_add(oe, member);
    884     added++;
    885   next:
    886     ar_name = strchr(ar_name, '\0') + 1;
    887   }
    888   return added;
    889 }
    890 
    891 static void
    892 outelf_archive(struct outelf *oe, char *ar)
    893 {
    894   char *beg = ar;
    895 
    896   ar += 8;
    897   for (;;) {
    898     struct arhdr *hdr  = (void *)ar;
    899     char         *name = hdr->ar_name;
    900     int           size;
    901 
    902     ar += sizeof(*hdr);
    903     hdr->ar_size[sizeof(hdr->ar_size) - 1] = '\0';
    904     size                                   = atoi(hdr->ar_size);
    905     size                                   = (size + 1) & ~1;
    906 
    907     if (name[0] == '/' && name[1] == ' ') {
    908       while (outelf_ar_link(oe, ar, ar - beg))
    909         ;
    910       return;
    911     }
    912     if (name[0] == '/' && name[1] == '/' && name[2] == ' ')
    913       outelf_add(oe, ar);
    914     ar += size;
    915   }
    916 }
    917 
    918 /* find the archive symbol index for multi-pass linking */
    919 static char *
    920 ar_symtab(char *ar)
    921 {
    922   ar += 8;
    923   for (;;) {
    924     struct arhdr *hdr  = (void *)ar;
    925     char         *name = hdr->ar_name;
    926     int           size;
    927 
    928     ar += sizeof(*hdr);
    929     hdr->ar_size[sizeof(hdr->ar_size) - 1] = '\0';
    930     size                                   = atoi(hdr->ar_size);
    931     size                                   = (size + 1) & ~1;
    932 
    933     if (name[0] == '/' && name[1] == ' ')
    934       return ar;
    935     ar += size;
    936   }
    937 }
    938 
    939 /* multi-pass archive resolution: iterate over all archives until no
    940  * new objects are pulled in. handles circular deps between libc and
    941  * libgcc */
    942 static char *ar_mems[MAXFILES];
    943 static int   nar_mems;
    944 
    945 static void
    946 resolve_archives(struct outelf *oe)
    947 {
    948   int i, changed;
    949 
    950   do {
    951     changed = 0;
    952     for (i = 0; i < nar_mems; i++) {
    953       char *symtab = ar_symtab(ar_mems[i]);
    954       while (outelf_ar_link(oe, symtab, symtab - ar_mems[i]))
    955         changed = 1;
    956     }
    957   } while (changed);
    958 }
    959 
    960 /* file I/O */
    961 static long
    962 filesize(int fd)
    963 {
    964   struct stat st;
    965   if (fstat(fd, &st) < 0)
    966     return -1;
    967   return st.st_size;
    968 }
    969 
    970 static char *
    971 fileread(char *path)
    972 {
    973   int     fd = open(path, O_RDONLY);
    974   long    size;
    975   char   *buf;
    976   ssize_t nread;
    977 
    978   if (fd < 0)
    979     return NULL;
    980   size = filesize(fd);
    981   if (size <= 0) {
    982     close(fd);
    983     return NULL;
    984   }
    985   buf = malloc((size_t)size);
    986   if (!buf) {
    987     close(fd);
    988     return NULL;
    989   }
    990   nread = read(fd, buf, (size_t)size);
    991   close(fd);
    992   if (nread != (ssize_t)size) {
    993     free(buf);
    994     return NULL;
    995   }
    996   return buf;
    997 }
    998 
    999 static int
   1000 is_ar(char *path)
   1001 {
   1002   int len = strlen(path);
   1003   return len > 2 && path[len - 2] == '.' && path[len - 1] == 'a';
   1004 }
   1005 
   1006 static int
   1007 lib_find(char *path, char *lib)
   1008 {
   1009   struct stat st;
   1010   int         i;
   1011 
   1012   if (lib[0] == ':') {
   1013     lib++;
   1014     for (i = 0; i < nlibdirs; i++) {
   1015       sprintf(path, "%s/%s", libdirs[i], lib);
   1016       if (!stat(path, &st))
   1017         return 0;
   1018     }
   1019     return 1;
   1020   }
   1021 
   1022   for (i = 0; i < nlibdirs; i++) {
   1023     sprintf(path, "%s/lib%s.a", libdirs[i], lib);
   1024     if (!stat(path, &st))
   1025       return 0;
   1026   }
   1027   return 1;
   1028 }
   1029 
   1030 static unsigned long
   1031 hexnum(char *s)
   1032 {
   1033   unsigned long n = 0;
   1034   if (s[0] == '0' && s[1] == 'x')
   1035     s += 2;
   1036   for (; isdigit(*s) || isalpha(*s); s++) {
   1037     n <<= 4;
   1038     n |= isdigit(*s) ? *s - '0' : tolower(*s) - 'a' + 10;
   1039   }
   1040   return n;
   1041 }
   1042 
   1043 static void
   1044 set_addr(int sec, char *arg)
   1045 {
   1046   int   idx = I_CS;
   1047   char *sep = strchr(arg, ':');
   1048 
   1049   if (sec == 'd')
   1050     idx = I_DS;
   1051   if (sec == 'b')
   1052     idx = I_BSS;
   1053   sec_vaddr[idx] = hexnum(arg);
   1054   sec_laddr[idx] = sep ? hexnum(sep + 1) : sec_vaddr[idx];
   1055   sec_set[idx]   = 1;
   1056 }
   1057 
   1058 static void
   1059 usage(void)
   1060 {
   1061   fprintf(
   1062       stderr,
   1063       "usage: ld [-static] [-o outfile] [-e entry] [-L dir] [-l lib]\n"
   1064       "          [-Ttext addr] [-Tdata addr] [-Tbss addr] [-Map file]\n"
   1065       "          [-s] [-p] [-h name] objfile ...\n"
   1066   );
   1067   exit(1);
   1068 }
   1069 
   1070 int
   1071 main(int argc, char *argv[])
   1072 {
   1073   char                 out[PATHLEN] = "a.out";
   1074   static struct outelf oe;
   1075   char                *mem[MAXFILES];
   1076   int                  nmem = 0;
   1077   int                  fd;
   1078   int                  i = 0;
   1079 
   1080   if (argc < 2)
   1081     usage();
   1082   outelf_init(&oe);
   1083 
   1084   while (++i < argc) {
   1085     if (argv[i][0] != '-') {
   1086       mem[nmem++] = fileread(argv[i]);
   1087       if (!mem[nmem - 1])
   1088         die("ld: cannot open object");
   1089       if (is_ar(argv[i])) {
   1090         ar_mems[nar_mems++] = mem[nmem - 1];
   1091         outelf_archive(&oe, mem[nmem - 1]);
   1092       } else
   1093         outelf_add(&oe, mem[nmem - 1]);
   1094       continue;
   1095     }
   1096 
   1097     if (argv[i][1] == 'l' && argv[i][2] == '\0') {
   1098       char path[PATHLEN];
   1099       if (i + 1 >= argc)
   1100         die("ld: -l missing argument");
   1101       if (lib_find(path, argv[++i]))
   1102         die("ld: cannot find library");
   1103       mem[nmem] = fileread(path);
   1104       if (!mem[nmem])
   1105         die("ld: cannot read library");
   1106       nmem++;
   1107       if (is_ar(path)) {
   1108         ar_mems[nar_mems++] = mem[nmem - 1];
   1109         outelf_archive(&oe, mem[nmem - 1]);
   1110       } else
   1111         outelf_add(&oe, mem[nmem - 1]);
   1112       continue;
   1113     }
   1114 
   1115     if (argv[i][1] == 'l' && argv[i][2] != '\0') {
   1116       char path[PATHLEN];
   1117       if (lib_find(path, argv[i] + 2))
   1118         die("ld: cannot find library");
   1119       mem[nmem] = fileread(path);
   1120       if (!mem[nmem])
   1121         die("ld: cannot read library");
   1122       nmem++;
   1123       if (is_ar(path)) {
   1124         ar_mems[nar_mems++] = mem[nmem - 1];
   1125         outelf_archive(&oe, mem[nmem - 1]);
   1126       } else
   1127         outelf_add(&oe, mem[nmem - 1]);
   1128       continue;
   1129     }
   1130 
   1131     if (argv[i][1] == 'L' && argv[i][2] == '\0') {
   1132       if (i + 1 >= argc)
   1133         die("ld: -L missing argument");
   1134       if (nlibdirs >= MAXLIBDIRS)
   1135         die("ld: too many library dirs");
   1136       libdirs[nlibdirs++] = argv[++i];
   1137       continue;
   1138     }
   1139 
   1140     if (argv[i][1] == 'L' && argv[i][2] != '\0') {
   1141       if (nlibdirs >= MAXLIBDIRS)
   1142         die("ld: too many library dirs");
   1143       libdirs[nlibdirs++] = argv[i] + 2;
   1144       continue;
   1145     }
   1146 
   1147     if (argv[i][1] == 'o' && argv[i][2] == '\0') {
   1148       if (i + 1 >= argc)
   1149         die("ld: -o missing argument");
   1150       strcpy(out, argv[++i]);
   1151       continue;
   1152     }
   1153     if (argv[i][1] == 'o') {
   1154       strcpy(out, argv[i] + 2);
   1155       continue;
   1156     }
   1157 
   1158     if ((argv[i][1] == 's' || argv[i][1] == 'S') && argv[i][2] == '\0') {
   1159       nosyms = 1;
   1160       continue;
   1161     }
   1162 
   1163     if (argv[i][1] == 'g' && argv[i][2] == '\0')
   1164       continue;
   1165 
   1166     if (argv[i][1] == 'e' && argv[i][2] == '\0') {
   1167       if (i + 1 >= argc)
   1168         die("ld: -e missing argument");
   1169       entry = argv[++i];
   1170       continue;
   1171     }
   1172     if (argv[i][1] == 'e') {
   1173       entry = argv[i] + 2;
   1174       continue;
   1175     }
   1176 
   1177     if (argv[i][1] == 'p' && argv[i][2] == '\0') {
   1178       secalign = PAGE_SIZE;
   1179       continue;
   1180     }
   1181 
   1182     /* -ttext/-tdata/-tbss: set segment base addresses */
   1183     if (!strncmp(argv[i], "-Ttext", 6)) {
   1184       char *arg = argv[i][6] ? (argv[i][6] == '=' ? argv[i] + 7 : argv[i] + 6) : argv[++i];
   1185       set_addr('c', arg);
   1186       continue;
   1187     }
   1188     if (!strncmp(argv[i], "-Tdata", 6)) {
   1189       char *arg = argv[i][6] ? (argv[i][6] == '=' ? argv[i] + 7 : argv[i] + 6) : argv[++i];
   1190       set_addr('d', arg);
   1191       continue;
   1192     }
   1193     if (!strncmp(argv[i], "-Tbss", 5)) {
   1194       char *arg = argv[i][5] ? (argv[i][5] == '=' ? argv[i] + 6 : argv[i] + 5) : argv[++i];
   1195       set_addr('b', arg);
   1196       continue;
   1197     }
   1198 
   1199     /* -T linker script: tolerate (not yet supported) */
   1200     if (argv[i][1] == 'T' && argv[i][2] == '\0') {
   1201       if (i + 1 < argc)
   1202         ++i;
   1203       continue;
   1204     }
   1205 
   1206     /* -map file: write link map */
   1207     if (!strncmp(argv[i], "-Map", 4)) {
   1208       mapfile = argv[i][4] ? (argv[i][4] == '=' ? argv[i] + 5 : argv[i] + 4) : argv[++i];
   1209       continue;
   1210     }
   1211 
   1212     /* -m: neatld section address or GNU emulation mode */
   1213     if (argv[i][1] == 'm') {
   1214       /* -melf_x86_64: emulation, tolerate */
   1215       if (argv[i][2] == 'e')
   1216         continue;
   1217       /* -m c=addr or -mc=addr: section address */
   1218       if (argv[i][2] == '\0') {
   1219         if (i + 1 < argc) {
   1220           char *a = argv[i + 1];
   1221           /* elf_* is emulation not section */
   1222           if (a[0] == 'e') {
   1223             ++i;
   1224             continue;
   1225           }
   1226           set_addr(a[0], a[2] == '=' ? a + 3 : a + 1);
   1227           ++i;
   1228         }
   1229         continue;
   1230       }
   1231       {
   1232         char  sec = argv[i][2];
   1233         char *arg = argv[i][3] == '=' ? argv[i] + 4 : (argv[i][3] ? argv[i] + 3 : argv[++i]);
   1234         set_addr(sec, arg);
   1235       }
   1236       continue;
   1237     }
   1238 
   1239     /* -z takes one argument: -z now, -z relro, etc */
   1240     if (argv[i][1] == 'z') {
   1241       if (argv[i][2] == '\0' && i + 1 < argc)
   1242         ++i;
   1243       continue;
   1244     }
   1245 
   1246     /* -h name / -soname name: shared lib internal name, tolerate */
   1247     if (argv[i][1] == 'h' && argv[i][2] == '\0') {
   1248       if (i + 1 < argc)
   1249         ++i;
   1250       continue;
   1251     }
   1252     if (!strncmp(argv[i] + 1, "soname", 6)) {
   1253       if (argv[i][7] == '\0' && i + 1 < argc)
   1254         ++i;
   1255       continue;
   1256     }
   1257 
   1258     /* -u sym: force undefined symbol, tolerate */
   1259     if (argv[i][1] == 'u' && argv[i][2] == '\0') {
   1260       if (i + 1 < argc)
   1261         ++i;
   1262       continue;
   1263     }
   1264 
   1265     /* -defsym sym=val: tolerate */
   1266     if (!strncmp(argv[i] + 1, "defsym", 6)) {
   1267       if (argv[i][7] == '\0' && i + 1 < argc)
   1268         ++i;
   1269       continue;
   1270     }
   1271 
   1272     /* -r / --relocatable: partial linking, tolerate for now */
   1273     if (argv[i][1] == 'r' && argv[i][2] == '\0')
   1274       continue;
   1275 
   1276     /* -n / -N: nmagic, tolerate */
   1277     if ((argv[i][1] == 'n' || argv[i][1] == 'N') && argv[i][2] == '\0')
   1278       continue;
   1279 
   1280     /* -static / -bstatic: already static, no-op */
   1281     if (!strcmp(argv[i] + 1, "static") || !strcmp(argv[i] + 1, "Bstatic"))
   1282       continue;
   1283 
   1284     /* -shared / -bdynamic: static only, tolerate */
   1285     if (!strcmp(argv[i] + 1, "shared") || !strcmp(argv[i] + 1, "Bdynamic"))
   1286       continue;
   1287 
   1288     /* -pie / -no-pie / -fno-pie: tolerate */
   1289     if (!strcmp(argv[i] + 1, "pie") || !strcmp(argv[i] + 1, "no-pie")
   1290         || !strcmp(argv[i] + 1, "fno-pie") || !strcmp(argv[i] + 1, "fpie"))
   1291       continue;
   1292 
   1293     if (argv[i][1] == 'v' && argv[i][2] == '\0') {
   1294       printf("ld (aruu-dev)\n");
   1295       return 0;
   1296     }
   1297 
   1298     if (!strcmp(argv[i], "--version")) {
   1299       printf("ld (aruu-dev)\n");
   1300       return 0;
   1301     }
   1302 
   1303     if (!strcmp(argv[i], "--help"))
   1304       usage();
   1305 
   1306     /* long options: tolerate (--build-id, --hash-style, etc) */
   1307     if (argv[i][1] == '-')
   1308       continue;
   1309 
   1310     /* unknown single-char option: warn but continue */
   1311     fprintf(stderr, "ld: unknown option: %s\n", argv[i]);
   1312   }
   1313 
   1314   resolve_archives(&oe);
   1315   outelf_link(&oe);
   1316   fd = open(out, O_WRONLY | O_TRUNC | O_CREAT, 0755);
   1317   if (fd < 0)
   1318     die("ld: failed to create output");
   1319   outelf_write(&oe, fd);
   1320   close(fd);
   1321 
   1322   for (i = 0; i < nmem; i++)
   1323     free(mem[i]);
   1324   return 0;
   1325 }