aruu

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

emit_elf.c (22430B)


      1 #include "../config.h"
      2 #include <alloca.h>
      3 
      4 #if TC_TARGET_PLATFORM != TC_PLATFORM_APPLE
      5 #include <assert.h>
      6 #include <stdint.h> /* uint64_t */
      7 #include <stdio.h>
      8 #include <string.h>
      9 
     10 #include "arch.h"
     11 #include "as_util.h"
     12 #include "elfutil.h"
     13 #include "ir_asm.h"
     14 #include "parse_asm.h"
     15 #include "table.h"
     16 #include "tcutil.h"
     17 
     18 #define ELF_MIN_ALIGN 0x08
     19 
     20 #if TC_TARGET_ARCH == TC_ARCH_RISCV64
     21 int isa_zbb = 0;
     22 #endif
     23 
     24 struct Symtab {
     25   struct Strtab strtab;
     26   struct Table  indices;
     27   Elf64_Sym    *buf;
     28   int           count;
     29 };
     30 
     31 void
     32 symtab_init(struct Symtab *symtab)
     33 {
     34   strtab_init(&symtab->strtab);
     35   table_init(&symtab->indices);
     36   symtab->buf   = NULL;
     37   symtab->count = 0;
     38 }
     39 
     40 int
     41 symtab_find(struct Symtab *symtab, const struct Name *name)
     42 {
     43   intptr_t index;
     44   if (table_try_get(&symtab->indices, name, (void **)&index))
     45     return index;
     46   return -1;
     47 }
     48 
     49 Elf64_Sym *
     50 symtab_add(struct Symtab *symtab, const struct Name *name)
     51 {
     52   uint32_t offset = strtab_add(&symtab->strtab, name);
     53   if (name->bytes > 0) {
     54     int index = symtab_find(symtab, name);
     55     if (index >= 0)
     56       return &symtab->buf[index];
     57   }
     58 
     59   int old_count  = symtab->count;
     60   int new_count  = old_count + 1;
     61   symtab->buf    = realloc_or_die(symtab->buf, sizeof(*symtab->buf) * new_count);
     62   symtab->count  = new_count;
     63   Elf64_Sym *sym = &symtab->buf[old_count];
     64   memset(sym, 0x00, sizeof(*sym));
     65   sym->st_name = offset;
     66   table_put(&symtab->indices, name, INT2VOIDP(old_count));
     67   return sym;
     68 }
     69 
     70 void
     71 symtab_concat(struct Symtab *dest, struct Symtab *src)
     72 {
     73   int                 n     = src->count;
     74   const struct Name **names = alloca(sizeof(*names) * n);
     75   const struct Name  *name;
     76   intptr_t            index;
     77   for (int it = 0; (it = table_iterate(&src->indices, it, &name, (void **)&index)) != -1;) {
     78     assert(index < n);
     79     names[index] = name;
     80   }
     81   for (int i = 0; i < n; ++i) {
     82     const struct Name *name        = names[i];
     83     Elf64_Sym         *p           = symtab_add(dest, name);
     84     Elf64_Word         st_name_bak = p->st_name;
     85     memcpy(p, &src->buf[i], sizeof(*p));
     86     p->st_name = st_name_bak;
     87   }
     88 }
     89 
     90 /* */
     91 
     92 static int
     93 construct_symtab(struct Symtab *symtab, struct Vector *sections, struct Table *label_table)
     94 {
     95   symtab_init(symtab);
     96 
     97   struct Symtab symtab_global;
     98   symtab_init(&symtab_global);
     99 
    100   struct Symtab symtab_weak;
    101   symtab_init(&symtab_weak);
    102 
    103   struct Symtab *symtabs[] = {
    104       [STB_LOCAL]  = symtab,
    105       [STB_GLOBAL] = &symtab_global,
    106       [STB_WEAK]   = &symtab_weak,
    107   };
    108 
    109   const struct Name *nulname = alloc_cname("");
    110   /* UND */
    111   Elf64_Sym *sym;
    112   sym          = symtab_add(symtab, nulname);
    113   sym->st_info = ELF64_ST_INFO(STB_LOCAL, STT_NOTYPE);
    114   /* SECTION */
    115   for (int i = 0; i < sections->len; ++i) {
    116     struct SectionInfo *section = sections->data[i];
    117     if ((section->flag & SF_BSS ? section->bss_size : section->ds->len) <= 0)
    118       continue;
    119     sym           = symtab_add(symtab, nulname);
    120     sym->st_info  = ELF64_ST_INFO(STB_LOCAL, STT_SECTION);
    121     sym->st_shndx = section->index; /* section index */
    122   }
    123 
    124   const struct Name *name;
    125   struct LabelInfo  *info;
    126   for (int it = 0; (it = table_iterate(label_table, it, &name, (void **)&info)) != -1;) {
    127     int bind;
    128     if (info->flag & LF_WEAK) {
    129       bind = STB_WEAK;
    130     } else if (info->flag & LF_GLOBAL) {
    131       bind = STB_GLOBAL;
    132     } else if (info->flag & LF_REFERRED || info->kind == LK_FUNC) {
    133       bind = STB_LOCAL;
    134     } else {
    135       continue;
    136     }
    137     sym = symtab_add(symtabs[bind], name);
    138     int type;
    139     switch (info->kind) {
    140       default:
    141         assert(0); /* fallthrough to suppress warning */
    142       case LK_NONE:
    143         type = STT_NOTYPE;
    144         break;
    145       case LK_FUNC:
    146         type = STT_FUNC;
    147         break;
    148       case LK_OBJECT:
    149         type = STT_OBJECT;
    150         break;
    151     }
    152     sym->st_info  = ELF64_ST_INFO(bind, type);
    153     sym->st_value = (info->flag & LF_DEFINED) ? info->address - info->section->start_address : 0;
    154     sym->st_size  = info->size;
    155     assert(info->section == NULL || info->section->index > 0);
    156     Elf64_Section shndx = SHN_UNDEF;
    157     if (info->section != NULL) {
    158       if ((info->flag & (LF_COMM | LF_GLOBAL)) == (LF_COMM | LF_GLOBAL))
    159         shndx = SHN_COMMON;
    160       else
    161         shndx = info->section->index; /* symbol index for
    162                                        * local section */
    163     }
    164     sym->st_shndx = shndx;
    165   }
    166 
    167   int local_symbol_count = symtab->count;
    168   /* append global symbols after locals; */
    169   symtab_concat(symtab, &symtab_weak);
    170   symtab_concat(symtab, &symtab_global);
    171 
    172   return local_symbol_count;
    173 }
    174 
    175 static inline void
    176 construct_rela_element_abs64(
    177     struct Symtab               *symtab,
    178     struct Table                *label_table,
    179     const struct UnresolvedInfo *u,
    180     Elf64_Rela                  *rela,
    181     int                          type
    182 )
    183 {
    184   struct LabelInfo *label = table_get(label_table, u->label);
    185   if (label == NULL || label->flag & (LF_GLOBAL | LF_REFERRED)) {
    186     int symidx = symtab_find(symtab, u->label);
    187     assert(symidx >= 0);
    188 
    189     rela->r_offset = u->offset;
    190     rela->r_info   = ELF64_R_INFO(symidx, type);
    191     rela->r_addend = u->add;
    192   } else {
    193     int secidx     = label->section->index;
    194     rela->r_offset = u->offset;
    195     rela->r_info   = ELF64_R_INFO(secidx, type);
    196     rela->r_addend = u->add + (label->address - label->section->start_address);
    197   }
    198 }
    199 
    200 #if TC_TARGET_ARCH == TC_ARCH_X64
    201 static inline void
    202 construct_rela_element(
    203     struct Symtab               *symtab,
    204     struct Table                *label_table,
    205     const struct UnresolvedInfo *u,
    206     Elf64_Rela                  *rela
    207 )
    208 {
    209   switch (u->kind) {
    210     default:
    211       assert(0);
    212       break;
    213     case UNRES_ABS64:
    214       construct_rela_element_abs64(symtab, label_table, u, rela, R_X86_64_64);
    215       break;
    216     case UNRES_X64_ABS32S:
    217       construct_rela_element_abs64(symtab, label_table, u, rela, R_X86_64_32S);
    218       break;
    219     case UNRES_X64_ABS32:
    220       construct_rela_element_abs64(symtab, label_table, u, rela, R_X86_64_32);
    221       break;
    222     case UNRES_EXTERN:
    223     case UNRES_EXTERN_PC32: {
    224       int symidx = symtab_find(symtab, u->label);
    225       assert(symidx >= 0);
    226 
    227       rela->r_offset = u->offset;
    228       rela->r_info   = ELF64_R_INFO(symidx, R_X86_64_PC32);
    229       rela->r_addend = u->add;
    230     } break;
    231     case UNRES_CALL: {
    232       int symidx = symtab_find(symtab, u->label);
    233       assert(symidx >= 0);
    234 
    235       rela->r_offset = u->offset;
    236       rela->r_info   = ELF64_R_INFO(symidx, R_X86_64_PLT32);
    237       rela->r_addend = u->add;
    238     } break;
    239     case UNRES_X64_GOT_LOAD: {
    240       int symidx = symtab_find(symtab, u->label);
    241       assert(symidx >= 0);
    242 
    243       rela->r_offset = u->offset;
    244       rela->r_info   = ELF64_R_INFO(symidx, R_X86_64_GOTPCREL);
    245       rela->r_addend = u->add;
    246     } break;
    247     case UNRES_X64_TPOFF32:
    248       construct_rela_element_abs64(symtab, label_table, u, rela, R_X86_64_TPOFF32);
    249       break;
    250     case UNRES_X64_GOTTPOFF: {
    251       int symidx = symtab_find(symtab, u->label);
    252       assert(symidx >= 0);
    253 
    254       rela->r_offset = u->offset;
    255       rela->r_info   = ELF64_R_INFO(symidx, R_X86_64_GOTTPOFF);
    256       rela->r_addend = u->add;
    257     } break;
    258   }
    259 }
    260 
    261 #elif TC_TARGET_ARCH == TC_ARCH_AARCH64
    262 static inline void
    263 construct_rela_element(
    264     struct Symtab               *symtab,
    265     struct Table                *label_table,
    266     const struct UnresolvedInfo *u,
    267     Elf64_Rela                  *rela
    268 )
    269 {
    270   switch (u->kind) {
    271     default:
    272       assert(0);
    273       break;
    274     case UNRES_ABS64:
    275       construct_rela_element_abs64(symtab, label_table, u, rela, R_AARCH64_ABS64);
    276       break;
    277     case UNRES_CALL: {
    278       int symidx = symtab_find(symtab, u->label);
    279       assert(symidx >= 0);
    280 
    281       rela->r_offset = u->offset;
    282       rela->r_info   = ELF64_R_INFO(symidx, R_AARCH64_CALL26);
    283       rela->r_addend = u->add;
    284     } break;
    285 
    286     case UNRES_PCREL_HI:
    287     case UNRES_PCREL_LO: {
    288       int symidx = symtab_find(symtab, u->label);
    289       assert(symidx >= 0);
    290 
    291       rela->r_offset = u->offset;
    292       rela->r_info   = ELF64_R_INFO(
    293           symidx, u->kind == UNRES_PCREL_HI ? R_AARCH64_ADR_PREL_PG_HI21 : R_AARCH64_ADD_ABS_LO12_NC
    294       );
    295       rela->r_addend = u->add;
    296     } break;
    297 
    298     case UNRES_GOT_HI:
    299     case UNRES_GOT_LO: {
    300       struct LabelInfo *label = table_get(label_table, u->label);
    301       int type = u->kind == UNRES_GOT_HI ? R_AARCH64_ADR_GOT_PAGE : R_AARCH64_LD64_GOT_LO12_NC;
    302       if (label == NULL || label->flag & (LF_GLOBAL | LF_REFERRED)) {
    303         int symidx = symtab_find(symtab, u->label);
    304         assert(symidx >= 0);
    305 
    306         rela->r_offset = u->offset;
    307         rela->r_info   = ELF64_R_INFO(symidx, type);
    308         rela->r_addend = u->add;
    309       } else {
    310         int secidx     = label->section->index;
    311         rela->r_offset = u->offset;
    312         rela->r_info   = ELF64_R_INFO(secidx, type);
    313         rela->r_addend = u->add + (label->address - label->section->start_address);
    314       }
    315     } break;
    316   }
    317 }
    318 
    319 #elif TC_TARGET_ARCH == TC_ARCH_RISCV64
    320 static inline void
    321 construct_rela_element(
    322     struct Symtab               *symtab,
    323     struct Table                *label_table,
    324     const struct UnresolvedInfo *u,
    325     Elf64_Rela                  *rela
    326 )
    327 {
    328   switch (u->kind) {
    329     default:
    330       assert(0);
    331       break;
    332     case UNRES_ABS64:
    333       construct_rela_element_abs64(symtab, label_table, u, rela, R_RISCV_64);
    334       break;
    335     case UNRES_PCREL_HI:
    336     case UNRES_PCREL_LO:
    337     case UNRES_RISCV_HI20:
    338     case UNRES_RISCV_LO12_I: {
    339       int symidx = symtab_find(symtab, u->label);
    340       assert(symidx >= 0);
    341 
    342       Elf64_Xword type;
    343       switch (u->kind) {
    344         default: /* fallthrough to suppress warning */
    345         case UNRES_PCREL_HI:
    346           type = R_RISCV_PCREL_HI20;
    347           break;
    348         case UNRES_PCREL_LO:
    349           type = R_RISCV_PCREL_LO12_I;
    350           break;
    351         case UNRES_RISCV_HI20:
    352           type = R_RISCV_HI20;
    353           break;
    354         case UNRES_RISCV_LO12_I:
    355           type = R_RISCV_LO12_I;
    356           break;
    357       }
    358 
    359       rela->r_offset = u->offset;
    360       rela->r_info   = ELF64_R_INFO(symidx, type);
    361       rela->r_addend = u->add;
    362     } break;
    363 
    364     case UNRES_CALL: {
    365       int symidx = symtab_find(symtab, u->label);
    366       assert(symidx >= 0);
    367 
    368       rela->r_offset = u->offset;
    369       rela->r_info   = ELF64_R_INFO(symidx, R_RISCV_CALL);
    370       rela->r_addend = u->add;
    371     } break;
    372 
    373     case UNRES_RISCV_BRANCH:
    374     case UNRES_RISCV_RVC_BRANCH: {
    375       Elf64_Sym *sym   = symtab_add(symtab, u->label);
    376       size_t     index = sym - symtab->buf;
    377 
    378       rela->r_offset = u->offset;
    379       rela->r_info   = ELF64_R_INFO(
    380           index, u->kind == UNRES_RISCV_RVC_BRANCH ? R_RISCV_RVC_BRANCH : R_RISCV_BRANCH
    381       );
    382       rela->r_addend = u->add;
    383     } break;
    384     case UNRES_RISCV_JAL:
    385     case UNRES_RISCV_RVC_JUMP: {
    386       int symidx = symtab_find(symtab, u->label);
    387       assert(symidx >= 0);
    388 
    389       rela->r_offset = u->offset;
    390       rela->r_info =
    391           ELF64_R_INFO(symidx, u->kind == UNRES_RISCV_JAL ? R_RISCV_JAL : R_RISCV_RVC_JUMP);
    392       rela->r_addend = u->add;
    393     } break;
    394     case UNRES_RISCV_RELAX: {
    395       rela->r_offset = u->offset;
    396       rela->r_info   = ELF64_R_INFO(0, R_RISCV_RELAX);
    397       rela->r_addend = u->add;
    398     } break;
    399   }
    400 }
    401 #endif
    402 
    403 static void
    404 construct_relas(struct Vector *unresolved, struct Symtab *symtab, struct Table *label_table)
    405 {
    406   for (int i = 0; i < unresolved->len; ++i) {
    407     struct UnresolvedInfo *u       = unresolved->data[i];
    408     struct SectionInfo    *section = u->src_section;
    409     int                    count   = ++section->rela_count;
    410     Elf64_Rela            *rela_buf;
    411     section->rela_buf = rela_buf = realloc_or_die(section->rela_buf, count * sizeof(*rela_buf));
    412     construct_rela_element(symtab, label_table, u, &rela_buf[count - 1]);
    413   }
    414 }
    415 
    416 /* */
    417 
    418 #if TC_TARGET_ARCH == TC_ARCH_RISCV64
    419 static const char  kRiscvAttributesArch[] = "riscv";
    420 static const char *kRiscvAttributes[]     = {
    421     "rv64i2p1_m2p0_a2p1_f2p2_d2p2_c2p0_zicsr2p0_zmmul1p0_zaamo1p0_"
    422     "zalrsc1p0",
    423     "rv64i2p1_m2p0_a2p1_f2p2_d2p2_c2p0_zicsr2p0_zifencei2p0_zmmul1p0_"
    424     "zaamo1p0_zalrsc1p0_zbb1p0",
    425 };
    426 #endif
    427 
    428 struct Work {
    429   struct DataStorage section_headers;
    430   struct Symtab      symtab;
    431   struct Strtab      shstrtab;
    432   struct Vector     *sections;
    433   uint64_t           sh_ofs;
    434   uint64_t           symtab_ofs;
    435   uint64_t           strtab_ofs;
    436   uint64_t           shstrtab_ofs;
    437   int                out_section_count;
    438   int                shnum;
    439   int                local_symbol_count;
    440 #if TC_TARGET_ARCH == TC_ARCH_RISCV64
    441   const char *riscv_attributes;
    442   size_t      riscv_attributes_str_size;
    443   size_t      riscv_attributes_total_size;
    444   uint64_t    riscv_attributes_ofs;
    445 #endif
    446 };
    447 
    448 static inline int
    449 detect_output_sections(struct Vector *sections)
    450 {
    451   int count = 0;
    452   for (int sec = 0; sec < sections->len; ++sec) {
    453     struct SectionInfo *section = sections->data[sec];
    454     if ((section->flag & SF_BSS ? section->bss_size : section->ds->len) <= 0)
    455       continue;
    456     section->index = ++count;
    457   }
    458   return count;
    459 }
    460 
    461 static inline uint64_t
    462 arrange_section_offsets(struct Work *work)
    463 {
    464   struct Vector *sections = work->sections;
    465 
    466   uint64_t offset = sizeof(Elf64_Ehdr);
    467   for (int sec = 0; sec < sections->len; ++sec) {
    468     struct SectionInfo *section = sections->data[sec];
    469     size_t              size;
    470     if (section->ds == NULL || (size = section->ds->len) <= 0)
    471       continue;
    472     section->offset = offset = ALIGN(offset, ELF_MIN_ALIGN);
    473     offset += size;
    474   }
    475 
    476   for (int sec = 0; sec < sections->len; ++sec) {
    477     struct SectionInfo *section = sections->data[sec];
    478     if (section->rela_count <= 0)
    479       continue;
    480     section->rela_ofs = offset = ALIGN(offset, ELF_MIN_ALIGN);
    481     offset += sizeof(Elf64_Rela) * section->rela_count;
    482   }
    483 
    484   work->symtab_ofs = offset = ALIGN(offset, ELF_MIN_ALIGN);
    485   offset += sizeof(*work->symtab.buf) * work->symtab.count;
    486   work->strtab_ofs = offset;
    487   offset += work->symtab.strtab.size;
    488 
    489 #if TC_TARGET_ARCH == TC_ARCH_RISCV64
    490   work->riscv_attributes          = kRiscvAttributes[isa_zbb];
    491   work->riscv_attributes_str_size = strlen(work->riscv_attributes) + 1; /* include '\0' */
    492   work->riscv_attributes_total_size =
    493       1 + 4 + sizeof(kRiscvAttributesArch) + 1 + 4 + 1 + work->riscv_attributes_str_size;
    494   work->riscv_attributes_ofs = offset;
    495   offset += work->riscv_attributes_total_size;
    496 #endif
    497 
    498   return offset;
    499 }
    500 
    501 static inline void
    502 construct_section_headers(struct Work *work, uint64_t offset)
    503 {
    504   struct Vector *sections = work->sections;
    505 
    506   /* section headers */
    507   strtab_init(&work->shstrtab);
    508   struct DataStorage *section_headers = &work->section_headers;
    509   data_init(section_headers);
    510 
    511   Elf64_Word index = 1 + work->out_section_count;
    512   for (int sec = 0; sec < sections->len; ++sec) {
    513     struct SectionInfo *section = sections->data[sec];
    514     index += section->rela_count > 0;
    515   }
    516 #if TC_TARGET_ARCH == TC_ARCH_RISCV64
    517   ++index; /* for .riscv.attributes section */
    518 #endif
    519   const Elf64_Word strtab_index = index++;
    520   const Elf64_Word symtab_index = index;
    521   const int        shnum        = index + 2; /* symtab, shstrtab */
    522 
    523   const Elf64_Shdr nulsec = {
    524       .sh_name      = strtab_add(&work->shstrtab, alloc_cname("")),
    525       .sh_type      = SHT_NULL,
    526       .sh_addralign = 1,
    527   };
    528   data_append(section_headers, &nulsec, sizeof(nulsec));
    529 
    530   const struct Name *init_array_name = alloc_cname(".init_array");
    531   const struct Name *fini_array_name = alloc_cname(".fini_array");
    532   for (int sec = 0; sec < sections->len; ++sec) {
    533     struct SectionInfo *section = sections->data[sec];
    534     size_t              size    = section->ds != NULL ? section->ds->len : section->bss_size;
    535     if (size <= 0)
    536       continue;
    537     Elf64_Xword flags = SHF_ALLOC;
    538     if (section->flag & SF_EXECUTABLE)
    539       flags |= SHF_EXECINSTR;
    540     if (section->flag & SF_WRITABLE)
    541       flags |= SHF_WRITE;
    542     if (section->flag & SF_TLS)
    543       flags |= SHF_TLS;
    544 
    545     Elf64_Word type;
    546     if (section->flag & SF_BSS)
    547       type = SHT_NOBITS;
    548     else if (section->flag & SF_NOTE)
    549       type = SHT_NOTE;
    550     else if (equal_name(section->name, init_array_name))
    551       type = SHT_INIT_ARRAY;
    552     else if (equal_name(section->name, fini_array_name))
    553       type = SHT_FINI_ARRAY;
    554     else
    555       type = SHT_PROGBITS;
    556 
    557     const Elf64_Shdr shdr = {
    558         .sh_name      = strtab_add(&work->shstrtab, section->name),
    559         .sh_type      = type,
    560         .sh_flags     = flags,
    561         .sh_offset    = section->offset,
    562         .sh_size      = size,
    563         .sh_addralign = section->align,
    564     };
    565     data_append(section_headers, &shdr, sizeof(shdr));
    566   }
    567 
    568   for (int sec = 0; sec < sections->len; ++sec) {
    569     struct SectionInfo *section = sections->data[sec];
    570     if (section->rela_count <= 0)
    571       continue;
    572     const struct Name *name = section->name;
    573     char              *buf  = malloc_or_die(name->bytes + 6); /* sizeof(".rela\0") */
    574     snprintf(buf, name->bytes + 6, ".rela%.*s", name->bytes, name->chars);
    575 
    576     assert(section->index > 0);
    577     const Elf64_Shdr shdr = {
    578         .sh_name      = strtab_add(&work->shstrtab, alloc_name(buf, NULL, 0)),
    579         .sh_type      = SHT_RELA,
    580         .sh_flags     = SHF_INFO_LINK,
    581         .sh_offset    = section->rela_ofs,
    582         .sh_size      = sizeof(Elf64_Rela) * section->rela_count,
    583         .sh_link      = symtab_index,
    584         .sh_info      = section->index,
    585         .sh_addralign = 8,
    586         .sh_entsize   = sizeof(Elf64_Rela),
    587     };
    588     data_append(section_headers, &shdr, sizeof(shdr));
    589   }
    590 
    591 #if TC_TARGET_ARCH == TC_ARCH_RISCV64
    592   const Elf64_Shdr riscv_attributes_sec = {
    593       .sh_name      = strtab_add(&work->shstrtab, alloc_cname(".riscv.attributes")),
    594       .sh_type      = SHT_RISCV_ATTRIBUTES,
    595       .sh_offset    = work->riscv_attributes_ofs,
    596       .sh_size      = work->riscv_attributes_total_size,
    597       .sh_addralign = 1,
    598   };
    599   data_append(section_headers, &riscv_attributes_sec, sizeof(riscv_attributes_sec));
    600 #endif
    601 
    602   const Elf64_Shdr strtabsec = {
    603       .sh_name      = strtab_add(&work->shstrtab, alloc_cname(".strtab")),
    604       .sh_type      = SHT_STRTAB,
    605       .sh_offset    = work->strtab_ofs,
    606       .sh_size      = work->symtab.strtab.size,
    607       .sh_addralign = 1,
    608   };
    609   data_append(section_headers, &strtabsec, sizeof(strtabsec));
    610 
    611   const Elf64_Shdr symtabsec = {
    612       .sh_name      = strtab_add(&work->shstrtab, alloc_cname(".symtab")),
    613       .sh_type      = SHT_SYMTAB,
    614       .sh_offset    = work->symtab_ofs,
    615       .sh_size      = sizeof(*work->symtab.buf) * work->symtab.count,
    616       .sh_link      = strtab_index,
    617       .sh_info      = work->local_symbol_count, /* number of local symbols */
    618       .sh_addralign = 8,
    619       .sh_entsize   = sizeof(Elf64_Sym),
    620   };
    621   data_append(section_headers, &symtabsec, sizeof(symtabsec));
    622 
    623   const uint64_t   shstrtab_ofs  = offset; /* align(offset, 0x10); */
    624   const size_t     shstrtab_name = strtab_add(&work->shstrtab, alloc_cname(".shstrtab"));
    625   const Elf64_Shdr shstrtabsec   = {
    626       .sh_name      = shstrtab_name,
    627       .sh_type      = SHT_STRTAB,
    628       .sh_offset    = shstrtab_ofs,
    629       .sh_size      = work->shstrtab.size,
    630       .sh_addralign = 1,
    631   };
    632   data_append(section_headers, &shstrtabsec, sizeof(shstrtabsec));
    633   offset += work->shstrtab.size;
    634 
    635   const uint64_t sh_ofs = offset = ALIGN(offset, 0x10);
    636   /* offset += section_headers.len; */
    637 
    638   work->sh_ofs       = sh_ofs;
    639   work->shstrtab_ofs = shstrtab_ofs;
    640   work->shnum        = shnum;
    641 }
    642 
    643 static inline int
    644 output_to_file(const char *ofn, const struct Work *work)
    645 {
    646   FILE *ofp;
    647   if (ofn == NULL) {
    648     ofp = stdout;
    649   } else {
    650     ofp = fopen(ofn, "wb");
    651     if (ofp == NULL) {
    652       fprintf(stderr, "Failed to open output file: %s\n", ofn);
    653       return 1;
    654     }
    655   }
    656 
    657   const uint64_t entry = 0;
    658   const int      phnum = 0;
    659 #if TC_TARGET_ARCH == TC_ARCH_RISCV64
    660   const int flags = EF_RISCV_RVC | EF_RISCV_FLOAT_ABI_DOUBLE;
    661 #else
    662   const int flags = 0;
    663 #endif
    664   out_elf_header(ofp, entry, phnum, work->shnum, flags, work->sh_ofs);
    665 
    666   struct Vector *sections = work->sections;
    667   for (int sec = 0; sec < sections->len; ++sec) {
    668     struct SectionInfo *section = sections->data[sec];
    669     struct DataStorage *ds      = section->ds;
    670     if (ds == NULL || ds->len <= 0)
    671       continue;
    672     put_padding(ofp, section->offset);
    673     fwrite(ds->buf, ds->len, 1, ofp);
    674   }
    675 
    676   for (int sec = 0; sec < sections->len; ++sec) {
    677     struct SectionInfo *section    = sections->data[sec];
    678     int                 rela_count = section->rela_count;
    679     if (rela_count > 0) {
    680       put_padding(ofp, section->rela_ofs);
    681       fwrite(section->rela_buf, sizeof(Elf64_Rela), rela_count, ofp);
    682     }
    683   }
    684 
    685   put_padding(ofp, work->symtab_ofs);
    686   const struct Symtab *symtab = &work->symtab;
    687   fwrite(symtab->buf, sizeof(*symtab->buf), symtab->count, ofp);
    688   fwrite(strtab_dump(&symtab->strtab), symtab->strtab.size, 1, ofp);
    689 
    690 #if TC_TARGET_ARCH == TC_ARCH_RISCV64
    691   const unsigned char RISCV_ATTRIBUTES_MAGIC = 0x41;
    692   fputc(RISCV_ATTRIBUTES_MAGIC, ofp);
    693   {
    694     uint32_t total_size = work->riscv_attributes_total_size - 1;
    695     fwrite(&total_size, sizeof(total_size), 1, ofp); /* TODO: ensure little endian */
    696   }
    697   fwrite(kRiscvAttributesArch, sizeof(kRiscvAttributesArch), 1, ofp);
    698   fputc(0x01, ofp); /* ? */
    699   {
    700     uint32_t size = 1 + 4 + 1 + work->riscv_attributes_str_size;
    701     fwrite(&size, sizeof(size), 1, ofp); /* TODO: ensure little endian */
    702   }
    703   fputc(0x05, ofp);                                                        /* ? */
    704   fwrite(work->riscv_attributes, work->riscv_attributes_str_size, 1, ofp); /* output last '\0' */
    705 #endif
    706 
    707   assert(ofp == stdout || ftell(ofp) == (long)work->shstrtab_ofs);
    708   fwrite(strtab_dump(&work->shstrtab), work->shstrtab.size, 1, ofp);
    709 
    710   put_padding(ofp, work->sh_ofs);
    711   fwrite(work->section_headers.buf, work->section_headers.len, 1, ofp);
    712 
    713   return 0;
    714 }
    715 
    716 int
    717 emit_elf_obj(
    718     const char *ofn, struct Vector *sections, struct Table *label_table, struct Vector *unresolved
    719 )
    720 {
    721   struct Work work;
    722   memset(&work, 0x00, sizeof(work));
    723   work.sections           = sections;
    724   work.out_section_count  = detect_output_sections(sections);
    725   work.local_symbol_count = construct_symtab(&work.symtab, sections, label_table);
    726   construct_relas(unresolved, &work.symtab, label_table);
    727   uint64_t offset = arrange_section_offsets(&work);
    728   construct_section_headers(&work, offset);
    729   return output_to_file(ofn, &work);
    730 }
    731 #endif