aruu

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

emit_macho.c (18659B)


      1 #include "../config.h"
      2 
      3 #if TC_TARGET_PLATFORM == TC_PLATFORM_APPLE
      4 #include <assert.h>
      5 #include <stdint.h> /* uint64_t */
      6 #include <stdio.h>
      7 #include <string.h>
      8 
      9 #include <mach-o/loader.h>
     10 #include <mach-o/nlist.h>
     11 #include <mach-o/reloc.h>
     12 #include <mach/machine.h>
     13 
     14 #if TC_TARGET_ARCH == TC_ARCH_AARCH64
     15 #include <mach-o/arm64/reloc.h>
     16 #elif TC_TARGET_ARCH == TC_ARCH_X64
     17 #include <mach-o/x86_64/reloc.h>
     18 #else
     19 #error "Unsupported architecture"
     20 #endif
     21 
     22 #include "arch.h"
     23 #include "as_util.h"
     24 #include "ir_asm.h"
     25 #include "parse_asm.h"
     26 #include "table.h"
     27 #include "tcutil.h"
     28 
     29 #if !defined(__NO_BITFIELD) || !defined(__TC)
     30 #define SET_RELOCATION_INFO(rela, adr, sym, pcr, len, ext, typ)                                    \
     31   do {                                                                                             \
     32     (rela)->r_address   = (adr);                                                                   \
     33     (rela)->r_symbolnum = (sym);                                                                   \
     34     (rela)->r_pcrel     = (pcr);                                                                   \
     35     (rela)->r_length    = (len);                                                                   \
     36     (rela)->r_extern    = (ext);                                                                   \
     37     (rela)->r_type      = (typ);                                                                   \
     38   } while (0)
     39 #else
     40 #define SET_RELOCATION_INFO(rela, adr, sym, pcr, len, ext, typ)                                    \
     41   do {                                                                                             \
     42     (rela)->r_address = (adr);                                                                     \
     43     (rela)->r_pack =                                                                               \
     44         (((sym) & ((1U << 24) - 1U)) | (((pcr) & 1U) << 24) | (((len) & 3U) << 25)                 \
     45          | (((ext) & 1U) << 27) | (((typ) & 0x0f) << 28));                                         \
     46   } while (0)
     47 #endif
     48 
     49 struct Symtab {
     50   struct Strtab    strtab;
     51   struct Table     indices;
     52   struct nlist_64 *buf;
     53   int              ilocalsym, iextdefsym, iundefsym; /* for dysymtab */
     54   int              count;
     55 };
     56 
     57 void
     58 symtab_init(struct Symtab *symtab)
     59 {
     60   strtab_init(&symtab->strtab);
     61   table_init(&symtab->indices);
     62   symtab->buf   = NULL;
     63   symtab->count = 0;
     64 }
     65 
     66 int
     67 symtab_find(struct Symtab *symtab, const struct Name *name)
     68 {
     69   intptr_t index;
     70   if (table_try_get(&symtab->indices, name, (void **)&index))
     71     return index;
     72   return -1;
     73 }
     74 
     75 struct nlist_64 *
     76 symtab_add(struct Symtab *symtab, const struct Name *name)
     77 {
     78   uint32_t offset = strtab_add(&symtab->strtab, name);
     79   if (name->bytes > 0) {
     80     int index = symtab_find(symtab, name);
     81     if (index >= 0)
     82       return &symtab->buf[index];
     83   }
     84 
     85   int old_count        = symtab->count;
     86   int new_count        = old_count + 1;
     87   symtab->buf          = realloc_or_die(symtab->buf, sizeof(*symtab->buf) * new_count);
     88   symtab->count        = new_count;
     89   struct nlist_64 *sym = &symtab->buf[old_count];
     90   memset(sym, 0x00, sizeof(*sym));
     91   sym->n_un.n_strx = offset;
     92   table_put(&symtab->indices, name, INT2VOIDP(old_count));
     93   return sym;
     94 }
     95 
     96 /* */
     97 
     98 static void
     99 construct_symtab(struct Symtab *symtab, struct Table *label_table, uint64_t start_address)
    100 {
    101   symtab_init(symtab);
    102 
    103   /* NUL */
    104   strtab_add(&symtab->strtab, alloc_cname(""));
    105 
    106   enum SymbolKind {
    107     LOCAL,    /* local */
    108     EXTERNAL, /* external defined */
    109     UNDEF,    /* undefined (including common) */
    110   };
    111   int *pcounts[3] = {
    112       &symtab->ilocalsym,
    113       &symtab->iextdefsym,
    114       &symtab->iundefsym,
    115   };
    116   for (enum SymbolKind sk = 0; sk < (int)ARRAY_SIZE(pcounts); ++sk) {
    117     const struct Name *name;
    118     struct LabelInfo  *info;
    119     *pcounts[sk] = symtab->count;
    120     for (int it = 0; (it = table_iterate(label_table, it, &name, (void **)&info)) != -1;) {
    121       switch (sk) {
    122         case LOCAL:
    123           if (!(!(info->flag & LF_GLOBAL) && (info->flag & LF_REFERRED)))
    124             continue;
    125           break;
    126         case EXTERNAL:
    127           if (!((info->flag & LF_GLOBAL) && (info->flag & LF_DEFINED) && !(info->flag & LF_COMM)))
    128             continue;
    129           break;
    130         case UNDEF:
    131           if (!((info->flag & LF_GLOBAL) && (!(info->flag & LF_DEFINED) || (info->flag & LF_COMM))))
    132             continue;
    133           break;
    134       }
    135 
    136       struct nlist_64 *sym  = symtab_add(symtab, name);
    137       uint8_t          type = 0;
    138       int              sect = 0;
    139       if (info->flag & LF_GLOBAL) {
    140         type = N_EXT;
    141         sect = (info->flag & LF_DEFINED) != 0;
    142       } else if (info->flag & LF_REFERRED || info->flag & LF_DEFINED) {
    143         sect = 1;
    144       } else {
    145         assert(0);
    146       }
    147 
    148       if (info->section != NULL && info->flag & LF_COMM) {
    149         /* .comm */
    150         assert(info->align > 0 && IS_POWER_OF_2(info->align));
    151         SET_COMM_ALIGN(sym->n_desc, most_significant_bit(info->align));
    152         sym->n_value = info->size;
    153       } else if (sect) {
    154         type |= N_SECT;
    155         sym->n_sect  = info->section->index;
    156         sym->n_desc  = info->flag & LF_WEAK ? N_WEAK_DEF : 0;
    157         sym->n_value = (info->flag & LF_DEFINED) ? info->address - start_address : 0;
    158       }
    159       sym->n_type = type;
    160     }
    161   }
    162 }
    163 
    164 static inline void
    165 construct_rela_element_abs64(
    166     struct Symtab               *symtab,
    167     const struct UnresolvedInfo *u,
    168     struct relocation_info      *rela,
    169     uint32_t                     type
    170 )
    171 {
    172   int symidx = symtab_find(symtab, u->label);
    173   assert(symidx >= 0);
    174   SET_RELOCATION_INFO(rela, u->offset, symidx, 0, 3, 1, type);
    175 }
    176 
    177 #if TC_TARGET_ARCH == TC_ARCH_X64
    178 static inline void
    179 construct_rela_element(
    180     struct Symtab               *symtab,
    181     struct Table                *label_table,
    182     struct SectionInfo          *section,
    183     const struct UnresolvedInfo *u,
    184     struct relocation_info      *rela
    185 )
    186 {
    187   UNUSED(label_table);
    188   UNUSED(section);
    189   switch (u->kind) {
    190     default:
    191       assert(0);
    192       break;
    193     case UNRES_ABS64:
    194       construct_rela_element_abs64(symtab, u, rela, X86_64_RELOC_UNSIGNED);
    195       break;
    196 
    197     case UNRES_EXTERN:
    198     case UNRES_EXTERN_PC32: {
    199       int symidx = symtab_find(symtab, u->label);
    200       assert(symidx >= 0);
    201       SET_RELOCATION_INFO(rela, u->offset, symidx, 1, 2, 1, X86_64_RELOC_SIGNED);
    202     } break;
    203     case UNRES_CALL: {
    204       int symidx = symtab_find(symtab, u->label);
    205       assert(symidx >= 0);
    206       SET_RELOCATION_INFO(rela, u->offset, symidx, 1, 2, 1, X86_64_RELOC_BRANCH);
    207     } break;
    208     case UNRES_X64_GOT_LOAD: {
    209       int symidx = symtab_find(symtab, u->label);
    210       assert(symidx >= 0);
    211 
    212       /* assert(u->add == 0); */
    213       SET_RELOCATION_INFO(rela, u->offset, symidx, 1, 2, 1, X86_64_RELOC_GOT_LOAD);
    214     } break;
    215   }
    216 }
    217 
    218 #elif TC_TARGET_ARCH == TC_ARCH_AARCH64
    219 static inline void
    220 construct_rela_element(
    221     struct Symtab               *symtab,
    222     struct Table                *label_table,
    223     struct SectionInfo          *section,
    224     const struct UnresolvedInfo *u,
    225     struct relocation_info      *rela
    226 )
    227 {
    228   UNUSED(label_table);
    229   switch (u->kind) {
    230     default:
    231       assert(0);
    232       break;
    233     case UNRES_ABS64:
    234       construct_rela_element_abs64(symtab, u, rela, ARM64_RELOC_UNSIGNED);
    235       break;
    236 
    237     case UNRES_EXTERN_PC32:
    238     case UNRES_CALL: {
    239       int symidx = symtab_find(symtab, u->label);
    240       assert(symidx >= 0);
    241 
    242       assert(u->add == 0);
    243       SET_RELOCATION_INFO(rela, u->offset, symidx, 1, 2, 1, ARM64_RELOC_BRANCH26);
    244     } break;
    245 
    246     case UNRES_GOT_HI:
    247     case UNRES_GOT_LO: {
    248       assert(table_get(label_table, u->label) != NULL);
    249       int symidx = symtab_find(symtab, u->label);
    250       assert(symidx >= 0);
    251 
    252       assert(u->add == 0);
    253       uint32_t type =
    254           u->kind == UNRES_GOT_HI ? ARM64_RELOC_GOT_LOAD_PAGE21 : ARM64_RELOC_GOT_LOAD_PAGEOFF12;
    255       SET_RELOCATION_INFO(rela, u->offset, symidx, u->kind == UNRES_GOT_HI ? 1 : 0, 2, 1, type);
    256     } break;
    257 
    258     case UNRES_PCREL_HI:
    259     case UNRES_PCREL_LO: {
    260       int symidx = symtab_find(symtab, u->label);
    261       assert(symidx >= 0);
    262 
    263       uint32_t type = u->kind == UNRES_PCREL_HI ? ARM64_RELOC_PAGE21 : ARM64_RELOC_PAGEOFF12;
    264       SET_RELOCATION_INFO(rela, u->offset, symidx, u->kind == UNRES_PCREL_HI ? 1 : 0, 2, 1, type);
    265 
    266       if (u->add != 0) {
    267         int                     count = ++section->rela_count;
    268         struct relocation_info *rela_buf;
    269         section->rela_buf = rela_buf = realloc_or_die(section->rela_buf, count * sizeof(*rela_buf));
    270 
    271         struct relocation_info *rela2 = &rela_buf[count - 1];
    272         SET_RELOCATION_INFO(rela2, u->offset, u->add, 0, 2, 0, ARM64_RELOC_ADDEND);
    273       }
    274     } break;
    275   }
    276 }
    277 #endif
    278 
    279 static void
    280 construct_relas(struct Vector *unresolved, struct Symtab *symtab, struct Table *label_table)
    281 {
    282   for (int i = 0; i < unresolved->len; ++i) {
    283     struct UnresolvedInfo  *u       = unresolved->data[i];
    284     struct SectionInfo     *section = u->src_section;
    285     int                     count   = ++section->rela_count;
    286     struct relocation_info *rela_buf;
    287     section->rela_buf = rela_buf = realloc_or_die(section->rela_buf, count * sizeof(*rela_buf));
    288     construct_rela_element(symtab, label_table, section, u, &rela_buf[count - 1]);
    289   }
    290 }
    291 
    292 /* */
    293 
    294 struct Work {
    295   struct Symtab                symtab;
    296   struct mach_header_64        header;
    297   struct segment_command_64    segmentcmd;
    298   struct build_version_command buildversioncmd;
    299   struct symtab_command        symtabcmd;
    300   struct dysymtab_command      dysymtabcmd;
    301 
    302   struct Vector *sections;
    303   uint64_t       start_address;
    304   uint64_t       reloc_start_off;
    305   uint64_t       section_start_off;
    306   uint32_t       size_of_cmds;
    307 };
    308 
    309 static inline int
    310 detect_output_sections(struct Vector *sections, struct Work *work)
    311 {
    312   int      count         = 0;
    313   uint64_t start_address = 0;
    314   for (int sec = 0; sec < sections->len; ++sec) {
    315     struct SectionInfo *section = sections->data[sec];
    316     if ((section->ds == NULL || section->ds->len <= 0) && section->bss_size <= 0)
    317       continue;
    318     section->index = ++count;
    319     if (start_address == 0)
    320       start_address = section->start_address;
    321   }
    322   work->start_address = start_address;
    323   return count;
    324 }
    325 
    326 static inline void
    327 reverse_relas(struct Vector *sections)
    328 {
    329   /* reverse the order of relas */
    330   for (int sec = 0; sec < sections->len; ++sec) {
    331     struct SectionInfo     *section = sections->data[sec];
    332     int                     n = section->rela_count, mid = n >> 1;
    333     struct relocation_info *buf = section->rela_buf;
    334     for (int j = 0; j < mid; ++j) {
    335       struct relocation_info *p   = &buf[j];
    336       struct relocation_info *q   = &buf[n - j - 1];
    337       struct relocation_info  tmp = *p;
    338       *p                          = *q;
    339       *q                          = tmp;
    340     }
    341   }
    342 }
    343 
    344 static inline uint64_t
    345 arrange_section_offsets(struct Work *work, int section_count)
    346 {
    347   const uint32_t size_of_cmds = sizeof(struct segment_command_64)
    348                                 + sizeof(struct section_64) * section_count
    349                                 + sizeof(struct build_version_command)
    350                                 + sizeof(struct symtab_command) + sizeof(struct dysymtab_command);
    351   work->size_of_cmds          = size_of_cmds;
    352   const uint64_t section_start_off = sizeof(struct mach_header_64) + size_of_cmds;
    353   work->section_start_off          = section_start_off;
    354   uint64_t       addr = 0, off_p = section_start_off;
    355   struct Vector *sections = work->sections;
    356   for (int sec = 0; sec < sections->len; ++sec) {
    357     struct SectionInfo *section = sections->data[sec];
    358     uint64_t            size    = section->ds != NULL ? section->ds->len : section->bss_size;
    359     if (size <= 0)
    360       continue;
    361     uint64_t align         = section->align;
    362     section->start_address = addr = ALIGN(addr, align);
    363     off_p                         = ALIGN(off_p, align);
    364     if (section->ds != NULL) {
    365       section->offset = off_p;
    366       off_p += size;
    367     } else {
    368       section->offset = 0;
    369     }
    370     addr += size;
    371   }
    372   work->reloc_start_off = off_p;
    373   for (int sec = 0; sec < sections->len; ++sec) {
    374     struct SectionInfo *section = sections->data[sec];
    375     if (section->ds == NULL)
    376       continue;
    377     section->rela_ofs = 0;
    378     int rela_count    = section->rela_count;
    379     if (rela_count > 0) {
    380       section->rela_ofs = off_p;
    381       off_p += sizeof(struct relocation_info) * rela_count;
    382     }
    383   }
    384 
    385   return off_p;
    386 }
    387 
    388 static inline void
    389 construct_load_commands(struct Work *work, uint64_t symbol_start_off, int section_count)
    390 {
    391   work->header = (struct mach_header_64){
    392       .magic = MH_MAGIC_64,
    393 #if TC_TARGET_ARCH == TC_ARCH_AARCH64
    394       .cputype    = CPU_TYPE_ARM64,
    395       .cpusubtype = CPU_SUBTYPE_ARM_ALL,
    396 #elif TC_TARGET_ARCH == TC_ARCH_X64
    397       .cputype    = CPU_TYPE_X86_64,
    398       .cpusubtype = CPU_SUBTYPE_X86_ALL,
    399 #else
    400 #error "Unsupported architecture"
    401 #endif
    402       .filetype   = MH_OBJECT,
    403       .ncmds      = 4,
    404       .sizeofcmds = work->size_of_cmds,
    405       .flags      = MH_SUBSECTIONS_VIA_SYMBOLS, /* TODO: handle this flag
    406                                                  */
    407   };
    408   uint64_t       vmsize = 0, filesize = 0;
    409   struct Vector *sections = work->sections;
    410   for (int sec = 0; sec < sections->len; ++sec) {
    411     struct SectionInfo *section = sections->data[sec];
    412     if (section->ds != NULL) {
    413       size_t size = section->ds->len;
    414       if (size <= 0)
    415         continue;
    416       vmsize   = ALIGN(vmsize, section->align) + size;
    417       filesize = ALIGN(filesize, section->align) + size;
    418     } else {
    419       size_t size = section->bss_size;
    420       assert(size > 0);
    421       vmsize = ALIGN(vmsize, section->align) + size;
    422     }
    423   }
    424   work->segmentcmd = (struct segment_command_64){
    425       .cmd      = LC_SEGMENT_64,
    426       .cmdsize  = sizeof(work->segmentcmd) + sizeof(struct section_64) * section_count,
    427       .segname  = "",
    428       .vmaddr   = 0,
    429       .vmsize   = vmsize,
    430       .fileoff  = work->section_start_off,
    431       .filesize = filesize,
    432       .maxprot  = 7, /* rwx */
    433       .initprot = 7, /* rwx */
    434       .nsects   = section_count,
    435       .flags    = 0,
    436   };
    437   work->buildversioncmd = (struct build_version_command){
    438       .cmd      = LC_BUILD_VERSION,
    439       .cmdsize  = sizeof(work->buildversioncmd),
    440       .platform = PLATFORM_MACOS,
    441       .minos    = 0x000e0000, /* 14.0.0 */
    442       .sdk      = 0x000e0500, /* 14.5.0 */
    443       .ntools   = 0,
    444   };
    445   const struct Symtab *symtab        = &work->symtab;
    446   const uint64_t       str_start_off = symbol_start_off + sizeof(*symtab->buf) * symtab->count;
    447   work->symtabcmd                    = (struct symtab_command){
    448       .cmd     = LC_SYMTAB,
    449       .cmdsize = sizeof(work->symtabcmd),
    450       .symoff  = symbol_start_off,
    451       .nsyms   = symtab->count,
    452       .stroff  = str_start_off,
    453       .strsize = symtab->strtab.size,
    454   };
    455   work->dysymtabcmd = (struct dysymtab_command){
    456       .cmd        = LC_DYSYMTAB,
    457       .cmdsize    = sizeof(work->dysymtabcmd),
    458       .ilocalsym  = symtab->ilocalsym,
    459       .nlocalsym  = symtab->iextdefsym - symtab->ilocalsym,
    460       .iextdefsym = symtab->iextdefsym,
    461       .nextdefsym = symtab->iundefsym - symtab->iextdefsym,
    462       .iundefsym  = symtab->iundefsym,
    463       .nundefsym  = symtab->count - symtab->iundefsym,
    464   };
    465 }
    466 
    467 static inline int
    468 output_to_file(const char *ofn, const struct Work *work)
    469 {
    470   FILE *ofp;
    471   if (ofn == NULL) {
    472     ofp = stdout;
    473   } else {
    474     ofp = fopen(ofn, "wb");
    475     if (ofp == NULL) {
    476       fprintf(stderr, "Failed to open output file: %s\n", ofn);
    477       return 1;
    478     }
    479   }
    480 
    481   fwrite(&work->header, sizeof(work->header), 1, ofp);
    482   fwrite(&work->segmentcmd, sizeof(work->segmentcmd), 1, ofp);
    483   struct Vector *sections = work->sections;
    484   for (int sec = 0; sec < sections->len; ++sec) {
    485     struct SectionInfo *section = sections->data[sec];
    486     size_t              size    = section->ds != NULL ? section->ds->len : section->bss_size;
    487     if (size <= 0)
    488       continue;
    489     uint32_t flags = 0;
    490     if (section->flag & SF_INIT_FUNCS)
    491       flags |= S_MOD_INIT_FUNC_POINTERS;
    492     else if (section->flag & SF_CSTRLITERALS)
    493       flags |= S_CSTRING_LITERALS;
    494     else if (section->flag & SF_BSS)
    495       flags |= S_ZEROFILL;
    496     else if (section->flag & SF_EXECUTABLE)
    497       flags |= S_ATTR_PURE_INSTRUCTIONS | S_ATTR_SOME_INSTRUCTIONS;
    498     struct section_64 sect = {
    499         .addr   = section->start_address,
    500         .size   = size,
    501         .offset = section->offset,
    502         .align  = most_significant_bit(section->align),
    503         .reloff = section->rela_ofs,
    504         .nreloc = section->rela_count,
    505         .flags  = flags,
    506     };
    507     strncpy(
    508         sect.sectname,
    509         section->name->chars,
    510         MIN(sizeof(sect.sectname), (size_t)section->name->bytes)
    511     );
    512     if (section->segname != NULL)
    513       strncpy(sect.segname, section->segname, sizeof(sect.segname));
    514     fwrite(&sect, sizeof(sect), 1, ofp);
    515   }
    516   fwrite(&work->buildversioncmd, sizeof(work->buildversioncmd), 1, ofp);
    517   fwrite(&work->symtabcmd, sizeof(work->symtabcmd), 1, ofp);
    518   fwrite(&work->dysymtabcmd, sizeof(work->dysymtabcmd), 1, ofp);
    519 
    520   for (int sec = 0; sec < sections->len; ++sec) {
    521     struct SectionInfo *section = sections->data[sec];
    522     struct DataStorage *ds      = section->ds;
    523     if (ds == NULL || ds->len <= 0)
    524       continue;
    525     put_padding(ofp, section->offset);
    526     fwrite(ds->buf, ds->len, 1, ofp);
    527   }
    528   put_padding(ofp, work->reloc_start_off);
    529   for (int i = 0; i < sections->len; ++i) {
    530     struct SectionInfo *section    = sections->data[i];
    531     int                 rela_count = section->rela_count;
    532     if (rela_count > 0) {
    533       put_padding(ofp, section->rela_ofs);
    534       fwrite(section->rela_buf, sizeof(struct relocation_info), rela_count, ofp);
    535     }
    536   }
    537   fwrite(work->symtab.buf, sizeof(*work->symtab.buf), work->symtab.count, ofp);
    538   fwrite(strtab_dump(&work->symtab.strtab), work->symtab.strtab.size, 1, ofp);
    539 
    540   return 0;
    541 }
    542 
    543 int
    544 emit_macho_obj(
    545     const char *ofn, struct Vector *sections, struct Table *label_table, struct Vector *unresolved
    546 )
    547 {
    548   struct Work work;
    549   memset(&work, 0x00, sizeof(work));
    550   work.sections = sections;
    551 
    552   const int section_count = detect_output_sections(sections, &work);
    553   construct_symtab(&work.symtab, label_table, work.start_address);
    554   construct_relas(unresolved, &work.symtab, label_table);
    555   reverse_relas(sections);
    556 
    557   uint64_t off_p = arrange_section_offsets(&work, section_count);
    558   construct_load_commands(&work, off_p, section_count);
    559   return output_to_file(ofn, &work);
    560 }
    561 #else
    562 /* ISO C wants a declaration in every file, and off Apple this has none */
    563 extern int emit_macho_none;
    564 #endif