fixup! riscv: Implement large addend for global address
[tinycc.git] / tccmacho.c
blob0b70457cb38386ecd02cd640124dad3d7c29af0c
1 /*
2 * Mach-O file handling for TCC
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 #include "tcc.h"
20 /* In order to make life easy for us we are generating Mach-O files which
21 don't make use of some modern features, but which aren't entirely classic
22 either in that they do use some modern features. We're also only
23 generating 64bit Mach-O files, and only native endian at that.
25 In particular we're generating executables that don't make use of
26 DYLD_INFO for dynamic linking info, as that requires us building a
27 trie of exported names. We're simply using classic symbol tables which
28 are still supported by modern dyld.
30 But we do use LC_MAIN, which is a "modern" feature in order to not have
31 to setup our own crt code. We're not using lazy linking, so even function
32 calls are resolved at startup. */
34 #if !defined TCC_TARGET_X86_64 && !defined TCC_TARGET_ARM64
35 #error Platform not supported
36 #endif
38 /* XXX: this file uses tcc_error() to the effect of exit(1) */
39 #undef _tcc_error
41 #define DEBUG_MACHO 0
42 #define dprintf if (DEBUG_MACHO) printf
44 #define MH_EXECUTE (0x2)
45 #define MH_DYLDLINK (0x4)
46 #define MH_DYLIB (0x6)
47 #define MH_PIE (0x200000)
49 #define CPU_SUBTYPE_LIB64 (0x80000000)
50 #define CPU_SUBTYPE_X86_ALL (3)
51 #define CPU_SUBTYPE_ARM64_ALL (0)
53 #define CPU_ARCH_ABI64 (0x01000000)
55 #define CPU_TYPE_X86 (7)
56 #define CPU_TYPE_X86_64 (CPU_TYPE_X86 | CPU_ARCH_ABI64)
57 #define CPU_TYPE_ARM (12)
58 #define CPU_TYPE_ARM64 (CPU_TYPE_ARM | CPU_ARCH_ABI64)
60 struct fat_header {
61 uint32_t magic; /* FAT_MAGIC or FAT_MAGIC_64 */
62 uint32_t nfat_arch; /* number of structs that follow */
65 struct fat_arch {
66 int cputype; /* cpu specifier (int) */
67 int cpusubtype; /* machine specifier (int) */
68 uint32_t offset; /* file offset to this object file */
69 uint32_t size; /* size of this object file */
70 uint32_t align; /* alignment as a power of 2 */
73 #define FAT_MAGIC 0xcafebabe
74 #define FAT_CIGAM 0xbebafeca
75 #define FAT_MAGIC_64 0xcafebabf
76 #define FAT_CIGAM_64 0xbfbafeca
78 struct mach_header {
79 uint32_t magic; /* mach magic number identifier */
80 int cputype; /* cpu specifier */
81 int cpusubtype; /* machine specifier */
82 uint32_t filetype; /* type of file */
83 uint32_t ncmds; /* number of load commands */
84 uint32_t sizeofcmds; /* the size of all the load commands */
85 uint32_t flags; /* flags */
88 struct mach_header_64 {
89 struct mach_header mh;
90 uint32_t reserved; /* reserved, pad to 64bit */
93 /* Constant for the magic field of the mach_header (32-bit architectures) */
94 #define MH_MAGIC 0xfeedface /* the mach magic number */
95 #define MH_CIGAM 0xcefaedfe /* NXSwapInt(MH_MAGIC) */
96 #define MH_MAGIC_64 0xfeedfacf /* the 64-bit mach magic number */
97 #define MH_CIGAM_64 0xcffaedfe /* NXSwapInt(MH_MAGIC_64) */
99 struct load_command {
100 uint32_t cmd; /* type of load command */
101 uint32_t cmdsize; /* total size of command in bytes */
104 #define LC_REQ_DYLD 0x80000000
105 #define LC_SYMTAB 0x2
106 #define LC_DYSYMTAB 0xb
107 #define LC_LOAD_DYLIB 0xc
108 #define LC_ID_DYLIB 0xd
109 #define LC_LOAD_DYLINKER 0xe
110 #define LC_SEGMENT_64 0x19
111 #define LC_RPATH (0x1c | LC_REQ_DYLD)
112 #define LC_REEXPORT_DYLIB (0x1f | LC_REQ_DYLD)
113 #define LC_DYLD_INFO_ONLY (0x22|LC_REQ_DYLD)
114 #define LC_MAIN (0x28|LC_REQ_DYLD)
115 #define LC_SOURCE_VERSION 0x2A
116 #define LC_BUILD_VERSION 0x32
117 #define LC_DYLD_EXPORTS_TRIE (0x33 | LC_REQ_DYLD)
118 #define LC_DYLD_CHAINED_FIXUPS (0x34 | LC_REQ_DYLD)
120 #define SG_READ_ONLY 0x10 /* This segment is made read-only after fixups */
122 typedef int vm_prot_t;
124 struct segment_command_64 { /* for 64-bit architectures */
125 uint32_t cmd; /* LC_SEGMENT_64 */
126 uint32_t cmdsize; /* includes sizeof section_64 structs */
127 char segname[16]; /* segment name */
128 uint64_t vmaddr; /* memory address of this segment */
129 uint64_t vmsize; /* memory size of this segment */
130 uint64_t fileoff; /* file offset of this segment */
131 uint64_t filesize; /* amount to map from the file */
132 vm_prot_t maxprot; /* maximum VM protection */
133 vm_prot_t initprot; /* initial VM protection */
134 uint32_t nsects; /* number of sections in segment */
135 uint32_t flags; /* flags */
138 struct section_64 { /* for 64-bit architectures */
139 char sectname[16]; /* name of this section */
140 char segname[16]; /* segment this section goes in */
141 uint64_t addr; /* memory address of this section */
142 uint64_t size; /* size in bytes of this section */
143 uint32_t offset; /* file offset of this section */
144 uint32_t align; /* section alignment (power of 2) */
145 uint32_t reloff; /* file offset of relocation entries */
146 uint32_t nreloc; /* number of relocation entries */
147 uint32_t flags; /* flags (section type and attributes)*/
148 uint32_t reserved1; /* reserved (for offset or index) */
149 uint32_t reserved2; /* reserved (for count or sizeof) */
150 uint32_t reserved3; /* reserved */
153 enum {
154 DYLD_CHAINED_IMPORT = 1,
157 struct dyld_chained_fixups_header {
158 uint32_t fixups_version; ///< 0
159 uint32_t starts_offset; ///< Offset of dyld_chained_starts_in_image.
160 uint32_t imports_offset; ///< Offset of imports table in chain_data.
161 uint32_t symbols_offset; ///< Offset of symbol strings in chain_data.
162 uint32_t imports_count; ///< Number of imported symbol names.
163 uint32_t imports_format; ///< DYLD_CHAINED_IMPORT*
164 uint32_t symbols_format; ///< 0 => uncompressed, 1 => zlib compressed
167 struct dyld_chained_starts_in_image
169 uint32_t seg_count;
170 uint32_t seg_info_offset[1]; // each entry is offset into this struct for that segment
171 // followed by pool of dyld_chain_starts_in_segment data
174 enum {
175 DYLD_CHAINED_PTR_64 = 2, // target is vmaddr
176 DYLD_CHAINED_PTR_64_OFFSET = 6, // target is vm offset
179 enum {
180 DYLD_CHAINED_PTR_START_NONE = 0xFFFF, // used in page_start[] to denote a page with no fixups
183 #define SEG_PAGE_SIZE 16384
185 struct dyld_chained_starts_in_segment
187 uint32_t size; // size of this (amount kernel needs to copy)
188 uint16_t page_size; // 0x1000 or 0x4000
189 uint16_t pointer_format; // DYLD_CHAINED_PTR_*
190 uint64_t segment_offset; // offset in memory to start of segment
191 uint32_t max_valid_pointer; // for 32-bit OS, any value beyond this is not a pointer
192 uint16_t page_count; // how many pages are in array
193 uint16_t page_start[1]; // each entry is offset in each page of first element in chain
194 // or DYLD_CHAINED_PTR_START_NONE if no fixups on page
197 enum BindSpecialDylib {
198 BIND_SPECIAL_DYLIB_FLAT_LOOKUP = -2,
201 struct dyld_chained_import
203 uint32_t lib_ordinal : 8,
204 weak_import : 1,
205 name_offset : 23;
208 struct dyld_chained_ptr_64_rebase
210 uint64_t target : 36, // vmaddr, 64GB max image size
211 high8 : 8, // top 8 bits set to this after slide added
212 reserved : 7, // all zeros
213 next : 12, // 4-byte stride
214 bind : 1; // == 0
217 struct dyld_chained_ptr_64_bind
219 uint64_t ordinal : 24,
220 addend : 8, // 0 thru 255
221 reserved : 19, // all zeros
222 next : 12, // 4-byte stride
223 bind : 1; // == 1
226 #define S_REGULAR 0x0
227 #define S_ZEROFILL 0x1
228 #define S_NON_LAZY_SYMBOL_POINTERS 0x6
229 #define S_LAZY_SYMBOL_POINTERS 0x7
230 #define S_SYMBOL_STUBS 0x8
231 #define S_MOD_INIT_FUNC_POINTERS 0x9
232 #define S_MOD_TERM_FUNC_POINTERS 0xa
234 #define S_ATTR_PURE_INSTRUCTIONS 0x80000000
235 #define S_ATTR_SOME_INSTRUCTIONS 0x00000400
236 #define S_ATTR_DEBUG 0x02000000
239 typedef uint32_t lc_str;
241 struct dylib_command {
242 uint32_t cmd; /* LC_ID_DYLIB, LC_LOAD_{,WEAK_}DYLIB,
243 LC_REEXPORT_DYLIB */
244 uint32_t cmdsize; /* includes pathname string */
245 lc_str name; /* library's path name */
246 uint32_t timestamp; /* library's build time stamp */
247 uint32_t current_version; /* library's current version number */
248 uint32_t compatibility_version; /* library's compatibility vers number*/
251 struct rpath_command {
252 uint32_t cmd; /* LC_RPATH */
253 uint32_t cmdsize; /* includes string */
254 lc_str path; /* path to add to run path */
257 struct dylinker_command {
258 uint32_t cmd; /* LC_ID_DYLINKER, LC_LOAD_DYLINKER or
259 LC_DYLD_ENVIRONMENT */
260 uint32_t cmdsize; /* includes pathname string */
261 lc_str name; /* dynamic linker's path name */
264 struct linkedit_data_command {
265 uint32_t cmd; /* LC_CODE_SIGNATURE, LC_SEGMENT_SPLIT_INFO,
266 LC_FUNCTION_STARTS, LC_DATA_IN_CODE,
267 LC_DYLIB_CODE_SIGN_DRS,
268 LC_LINKER_OPTIMIZATION_HINT,
269 LC_DYLD_EXPORTS_TRIE, or
270 LC_DYLD_CHAINED_FIXUPS. */
271 uint32_t cmdsize; /* sizeof(struct linkedit_data_command) */
272 uint32_t dataoff; /* file offset of data in __LINKEDIT segment */
273 uint32_t datasize; /* file size of data in __LINKEDIT segment */
276 #define PLATFORM_MACOS 1
278 struct build_version_command {
279 uint32_t cmd; /* LC_BUILD_VERSION */
280 uint32_t cmdsize; /* sizeof(struct build_version_command) plus */
281 /* ntools * sizeof(struct build_tool_version) */
282 uint32_t platform; /* platform */
283 uint32_t minos; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */
284 uint32_t sdk; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */
285 uint32_t ntools; /* number of tool entries following this */
288 struct source_version_command {
289 uint32_t cmd; /* LC_SOURCE_VERSION */
290 uint32_t cmdsize; /* 16 */
291 uint64_t version; /* A.B.C.D.E packed as a24.b10.c10.d10.e10 */
294 struct symtab_command {
295 uint32_t cmd; /* LC_SYMTAB */
296 uint32_t cmdsize; /* sizeof(struct symtab_command) */
297 uint32_t symoff; /* symbol table offset */
298 uint32_t nsyms; /* number of symbol table entries */
299 uint32_t stroff; /* string table offset */
300 uint32_t strsize; /* string table size in bytes */
303 struct dysymtab_command {
304 uint32_t cmd; /* LC_DYSYMTAB */
305 uint32_t cmdsize; /* sizeof(struct dysymtab_command) */
307 uint32_t ilocalsym; /* index to local symbols */
308 uint32_t nlocalsym; /* number of local symbols */
310 uint32_t iextdefsym;/* index to externally defined symbols */
311 uint32_t nextdefsym;/* number of externally defined symbols */
313 uint32_t iundefsym; /* index to undefined symbols */
314 uint32_t nundefsym; /* number of undefined symbols */
316 uint32_t tocoff; /* file offset to table of contents */
317 uint32_t ntoc; /* number of entries in table of contents */
319 uint32_t modtaboff; /* file offset to module table */
320 uint32_t nmodtab; /* number of module table entries */
322 uint32_t extrefsymoff; /* offset to referenced symbol table */
323 uint32_t nextrefsyms; /* number of referenced symbol table entries */
325 uint32_t indirectsymoff;/* file offset to the indirect symbol table */
326 uint32_t nindirectsyms; /* number of indirect symbol table entries */
328 uint32_t extreloff; /* offset to external relocation entries */
329 uint32_t nextrel; /* number of external relocation entries */
330 uint32_t locreloff; /* offset to local relocation entries */
331 uint32_t nlocrel; /* number of local relocation entries */
334 #define BIND_OPCODE_DONE 0x00
335 #define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30
336 #define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40
337 #define BIND_OPCODE_SET_TYPE_IMM 0x50
338 #define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70
339 #define BIND_OPCODE_DO_BIND 0x90
341 #define BIND_SYMBOL_FLAGS_WEAK_IMPORT 0x1
343 #define BIND_TYPE_POINTER 1
344 #define BIND_SPECIAL_DYLIB_FLAT_LOOKUP -2
346 #define REBASE_OPCODE_DONE 0x00
347 #define REBASE_OPCODE_SET_TYPE_IMM 0x10
348 #define REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x20
349 #define REBASE_OPCODE_DO_REBASE_IMM_TIMES 0x50
351 #define REBASE_TYPE_POINTER 1
353 #define EXPORT_SYMBOL_FLAGS_KIND_REGULAR 0x00
354 #define EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE 0x02
355 #define EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION 0x04
357 struct dyld_info_command {
358 uint32_t cmd; /* LC_DYLD_INFO or LC_DYLD_INFO_ONLY */
359 uint32_t cmdsize; /* sizeof(struct dyld_info_command) */
360 uint32_t rebase_off; /* file offset to rebase info */
361 uint32_t rebase_size; /* size of rebase info */
362 uint32_t bind_off; /* file offset to binding info */
363 uint32_t bind_size; /* size of binding info */
364 uint32_t weak_bind_off; /* file offset to weak binding info */
365 uint32_t weak_bind_size; /* size of weak binding info */
366 uint32_t lazy_bind_off; /* file offset to lazy binding info */
367 uint32_t lazy_bind_size; /* size of lazy binding infs */
368 uint32_t export_off; /* file offset to lazy binding info */
369 uint32_t export_size; /* size of lazy binding infs */
372 #define INDIRECT_SYMBOL_LOCAL 0x80000000
374 struct entry_point_command {
375 uint32_t cmd; /* LC_MAIN only used in MH_EXECUTE filetypes */
376 uint32_t cmdsize; /* 24 */
377 uint64_t entryoff; /* file (__TEXT) offset of main() */
378 uint64_t stacksize;/* if not zero, initial stack size */
381 enum skind {
382 sk_unknown = 0,
383 sk_discard,
384 sk_text,
385 sk_stubs,
386 sk_stub_helper,
387 sk_ro_data,
388 sk_uw_info,
389 sk_nl_ptr, // non-lazy pointers, aka GOT
390 sk_debug_info,
391 sk_debug_abbrev,
392 sk_debug_line,
393 sk_debug_aranges,
394 sk_debug_str,
395 sk_debug_line_str,
396 sk_stab,
397 sk_stab_str,
398 sk_la_ptr, // lazy pointers
399 sk_init,
400 sk_fini,
401 sk_rw_data,
402 sk_bss,
403 sk_linkedit,
404 sk_last
407 struct nlist_64 {
408 uint32_t n_strx; /* index into the string table */
409 uint8_t n_type; /* type flag, see below */
410 uint8_t n_sect; /* section number or NO_SECT */
411 uint16_t n_desc; /* see <mach-o/stab.h> */
412 uint64_t n_value; /* value of this symbol (or stab offset) */
415 #define N_UNDF 0x0
416 #define N_ABS 0x2
417 #define N_EXT 0x1
418 #define N_SECT 0xe
420 #define N_WEAK_REF 0x0040
421 #define N_WEAK_DEF 0x0080
423 struct macho {
424 struct mach_header_64 mh;
425 int *seg2lc, nseg;
426 struct load_command **lc;
427 struct entry_point_command *ep;
428 int nlc;
429 struct {
430 Section *s;
431 int machosect;
432 } sk_to_sect[sk_last];
433 int *elfsectomacho;
434 int *e2msym;
435 Section *symtab, *strtab, *indirsyms, *stubs, *exports;
436 uint32_t ilocal, iextdef, iundef;
437 int stubsym, n_got, nr_plt;
438 int segment[sk_last];
439 #ifdef CONFIG_NEW_MACHO
440 Section *chained_fixups;
441 int n_bind;
442 int n_bind_rebase;
443 struct bind_rebase {
444 int section;
445 int bind;
446 ElfW_Rel rel;
447 } *bind_rebase;
448 #else
449 Section *rebase, *binding, *weak_binding, *lazy_binding;
450 Section *stub_helper, *la_symbol_ptr;
451 struct dyld_info_command *dyldinfo;
452 int helpsym, lasym, dyld_private, dyld_stub_binder;
453 int n_lazy_bind;
454 struct s_lazy_bind {
455 int section;
456 int bind_offset;
457 int la_symbol_offset;
458 ElfW_Rel rel;
459 } *s_lazy_bind;
460 int n_rebase;
461 struct s_rebase {
462 int section;
463 ElfW_Rel rel;
464 } *s_rebase;
465 int n_bind;
466 struct bind {
467 int section;
468 ElfW_Rel rel;
469 } *bind;
470 #endif
473 #define SHT_LINKEDIT (SHT_LOOS + 42)
474 #define SHN_FROMDLL (SHN_LOOS + 2) /* Symbol is undefined, comes from a DLL */
476 static void * add_lc(struct macho *mo, uint32_t cmd, uint32_t cmdsize)
478 struct load_command *lc = tcc_mallocz(cmdsize);
479 lc->cmd = cmd;
480 lc->cmdsize = cmdsize;
481 mo->lc = tcc_realloc(mo->lc, sizeof(mo->lc[0]) * (mo->nlc + 1));
482 mo->lc[mo->nlc++] = lc;
483 return lc;
486 static struct segment_command_64 * add_segment(struct macho *mo, const char *name)
488 struct segment_command_64 *sc = add_lc(mo, LC_SEGMENT_64, sizeof(*sc));
489 strncpy(sc->segname, name, 16);
490 mo->seg2lc = tcc_realloc(mo->seg2lc, sizeof(*mo->seg2lc) * (mo->nseg + 1));
491 mo->seg2lc[mo->nseg++] = mo->nlc - 1;
492 return sc;
495 static struct segment_command_64 * get_segment(struct macho *mo, int i)
497 return (struct segment_command_64 *) (mo->lc[mo->seg2lc[i]]);
500 static int add_section(struct macho *mo, struct segment_command_64 **_seg, const char *name)
502 struct segment_command_64 *seg = *_seg;
503 int ret = seg->nsects;
504 struct section_64 *sec;
505 seg->nsects++;
506 seg->cmdsize += sizeof(*sec);
507 seg = tcc_realloc(seg, sizeof(*seg) + seg->nsects * sizeof(*sec));
508 sec = (struct section_64*)((char*)seg + sizeof(*seg)) + ret;
509 memset(sec, 0, sizeof(*sec));
510 strncpy(sec->sectname, name, 16);
511 strncpy(sec->segname, seg->segname, 16);
512 *_seg = seg;
513 return ret;
516 static struct section_64 *get_section(struct segment_command_64 *seg, int i)
518 return (struct section_64*)((char*)seg + sizeof(*seg)) + i;
521 static void * add_dylib(struct macho *mo, char *name)
523 struct dylib_command *lc;
524 int sz = (sizeof(*lc) + strlen(name) + 1 + 7) & -8;
525 lc = add_lc(mo, LC_LOAD_DYLIB, sz);
526 lc->name = sizeof(*lc);
527 strcpy((char*)lc + lc->name, name);
528 lc->timestamp = 2;
529 lc->current_version = 1 << 16;
530 lc->compatibility_version = 1 << 16;
531 return lc;
534 static int uleb128_size (unsigned long long value)
536 int size = 0;
538 do {
539 value >>= 7;
540 size++;
541 } while (value != 0);
542 return size;
545 static void write_uleb128(Section *section, uint64_t value)
547 do {
548 unsigned char byte = value & 0x7f;
549 uint8_t *ptr = section_ptr_add(section, 1);
551 value >>= 7;
552 *ptr = byte | (value ? 0x80 : 0);
553 } while (value != 0);
556 static void tcc_macho_add_destructor(TCCState *s1)
558 int init_sym, mh_execute_header, at_exit_sym;
559 Section *s;
560 ElfW_Rel *rel;
561 uint8_t *ptr;
563 mh_execute_header = put_elf_sym(s1->symtab, -4096, 0,
564 ELFW(ST_INFO)(STB_GLOBAL, STT_OBJECT), 0,
565 text_section->sh_num, "__mh_execute_header");
566 s = find_section(s1, ".fini_array");
567 if (s->data_offset == 0)
568 return;
569 init_sym = put_elf_sym(s1->symtab, text_section->data_offset, 0,
570 ELFW(ST_INFO)(STB_LOCAL, STT_FUNC), 0,
571 text_section->sh_num, "___GLOBAL_init_65535");
572 at_exit_sym = put_elf_sym(s1->symtab, 0, 0,
573 ELFW(ST_INFO)(STB_GLOBAL, STT_FUNC), 0,
574 SHN_UNDEF, "___cxa_atexit");
575 #ifdef TCC_TARGET_X86_64
576 ptr = section_ptr_add(text_section, 4);
577 ptr[0] = 0x55; // pushq %rbp
578 ptr[1] = 0x48; // movq %rsp, %rbp
579 ptr[2] = 0x89;
580 ptr[3] = 0xe5;
581 for_each_elem(s->reloc, 0, rel, ElfW_Rel) {
582 int sym_index = ELFW(R_SYM)(rel->r_info);
584 ptr = section_ptr_add(text_section, 26);
585 ptr[0] = 0x48; // lea destructor(%rip),%rax
586 ptr[1] = 0x8d;
587 ptr[2] = 0x05;
588 put_elf_reloca(s1->symtab, text_section,
589 text_section->data_offset - 23,
590 R_X86_64_PC32, sym_index, -4);
591 ptr[7] = 0x48; // mov %rax,%rdi
592 ptr[8] = 0x89;
593 ptr[9] = 0xc7;
594 ptr[10] = 0x31; // xorl %ecx, %ecx
595 ptr[11] = 0xc9;
596 ptr[12] = 0x89; // movl %ecx, %esi
597 ptr[13] = 0xce;
598 ptr[14] = 0x48; // lea mh_execute_header(%rip),%rdx
599 ptr[15] = 0x8d;
600 ptr[16] = 0x15;
601 put_elf_reloca(s1->symtab, text_section,
602 text_section->data_offset - 9,
603 R_X86_64_PC32, mh_execute_header, -4);
604 ptr[21] = 0xe8; // call __cxa_atexit
605 put_elf_reloca(s1->symtab, text_section,
606 text_section->data_offset - 4,
607 R_X86_64_PLT32, at_exit_sym, -4);
609 ptr = section_ptr_add(text_section, 2);
610 ptr[0] = 0x5d; // pop %rbp
611 ptr[1] = 0xc3; // ret
612 #elif defined TCC_TARGET_ARM64
613 ptr = section_ptr_add(text_section, 8);
614 write32le(ptr, 0xa9bf7bfd); // stp x29, x30, [sp, #-16]!
615 write32le(ptr + 4, 0x910003fd); // mov x29, sp
616 for_each_elem(s->reloc, 0, rel, ElfW_Rel) {
617 int sym_index = ELFW(R_SYM)(rel->r_info);
619 ptr = section_ptr_add(text_section, 24);
620 put_elf_reloc(s1->symtab, text_section,
621 text_section->data_offset - 24,
622 R_AARCH64_ADR_PREL_PG_HI21, sym_index);
623 write32le(ptr, 0x90000000); // adrp x0, destructor@page
624 put_elf_reloc(s1->symtab, text_section,
625 text_section->data_offset - 20,
626 R_AARCH64_LDST8_ABS_LO12_NC, sym_index);
627 write32le(ptr + 4, 0x91000000); // add x0,x0,destructor@pageoff
628 write32le(ptr + 8, 0xd2800001); // mov x1, #0
629 put_elf_reloc(s1->symtab, text_section,
630 text_section->data_offset - 12,
631 R_AARCH64_ADR_PREL_PG_HI21, mh_execute_header);
632 write32le(ptr + 12, 0x90000002); // adrp x2, mh_execute_header@page
633 put_elf_reloc(s1->symtab, text_section,
634 text_section->data_offset - 8,
635 R_AARCH64_LDST8_ABS_LO12_NC, mh_execute_header);
636 write32le(ptr + 16, 0x91000042); // add x2,x2,mh_execute_header@pageoff
637 put_elf_reloc(s1->symtab, text_section,
638 text_section->data_offset - 4,
639 R_AARCH64_CALL26, at_exit_sym);
640 write32le(ptr + 20, 0x94000000); // bl __cxa_atexit
642 ptr = section_ptr_add(text_section, 8);
643 write32le(ptr, 0xa8c17bfd); // ldp x29, x30, [sp], #16
644 write32le(ptr + 4, 0xd65f03c0); // ret
645 #endif
646 s->reloc->data_offset = s->data_offset = 0;
647 s->sh_flags &= ~SHF_ALLOC;
648 add_array (s1, ".init_array", init_sym);
651 #ifdef CONFIG_NEW_MACHO
652 static void bind_rebase_add(struct macho *mo, int bind, int sh_info,
653 ElfW_Rel *rel, struct sym_attr *attr)
655 mo->bind_rebase = tcc_realloc(mo->bind_rebase, (mo->n_bind_rebase + 1) *
656 sizeof(struct bind_rebase));
657 mo->bind_rebase[mo->n_bind_rebase].section = sh_info;
658 mo->bind_rebase[mo->n_bind_rebase].bind = bind;
659 mo->bind_rebase[mo->n_bind_rebase].rel = *rel;
660 if (attr)
661 mo->bind_rebase[mo->n_bind_rebase].rel.r_offset = attr->got_offset;
662 mo->n_bind_rebase++;
663 mo->n_bind += bind;
666 static void check_relocs(TCCState *s1, struct macho *mo)
668 Section *s;
669 ElfW_Rel *rel, save_rel;
670 ElfW(Sym) *sym;
671 int i, j, type, gotplt_entry, sym_index, for_code;
672 uint32_t *pi, *goti;
673 struct sym_attr *attr;
675 goti = NULL;
676 mo->nr_plt = mo->n_got = 0;
677 for (i = 1; i < s1->nb_sections; i++) {
678 s = s1->sections[i];
679 if (s->sh_type != SHT_RELX ||
680 !strncmp(s1->sections[s->sh_info]->name, ".debug_", 7))
681 continue;
682 for_each_elem(s, 0, rel, ElfW_Rel) {
683 save_rel = *rel;
684 type = ELFW(R_TYPE)(rel->r_info);
685 gotplt_entry = gotplt_entry_type(type);
686 for_code = code_reloc(type);
687 /* We generate a non-lazy pointer for used undefined symbols
688 and for defined symbols that must have a place for their
689 address due to codegen (i.e. a reloc requiring a got slot). */
690 sym_index = ELFW(R_SYM)(rel->r_info);
691 sym = &((ElfW(Sym) *)symtab_section->data)[sym_index];
692 if (sym->st_shndx == SHN_UNDEF
693 || gotplt_entry == ALWAYS_GOTPLT_ENTRY) {
694 attr = get_sym_attr(s1, sym_index, 1);
695 if (!attr->dyn_index) {
696 attr->got_offset = s1->got->data_offset;
697 attr->plt_offset = -1;
698 attr->dyn_index = 1; /* used as flag */
699 section_ptr_add(s1->got, PTR_SIZE);
700 put_elf_reloc(s1->symtab, s1->got, attr->got_offset,
701 R_JMP_SLOT, sym_index);
702 goti = tcc_realloc(goti, (mo->n_got + 1) * sizeof(*goti));
703 if (ELFW(ST_BIND)(sym->st_info) == STB_LOCAL) {
704 if (sym->st_shndx == SHN_UNDEF)
705 tcc_error("undefined local symbo: '%s'",
706 (char *) symtab_section->link->data + sym->st_name);
707 goti[mo->n_got++] = INDIRECT_SYMBOL_LOCAL;
708 } else {
709 goti[mo->n_got++] = mo->e2msym[sym_index];
710 if (sym->st_shndx == SHN_UNDEF
711 #ifdef TCC_TARGET_X86_64
712 && type == R_X86_64_GOTPCREL
713 #elif defined TCC_TARGET_ARM64
714 && type == R_AARCH64_ADR_GOT_PAGE
715 #endif
717 attr->plt_offset = -mo->n_bind_rebase - 2;
718 bind_rebase_add(mo, 1, s1->got->reloc->sh_info, &save_rel, attr);
719 s1->got->reloc->data_offset -= sizeof (ElfW_Rel);
721 if (for_code && sym->st_shndx == SHN_UNDEF)
722 s1->got->reloc->data_offset -= sizeof (ElfW_Rel);
725 if (for_code && sym->st_shndx == SHN_UNDEF) {
726 if ((int)attr->plt_offset < -1) {
727 /* remove above bind and replace with plt */
728 mo->bind_rebase[-attr->plt_offset - 2].bind = 2;
729 attr->plt_offset = -1;
731 if (attr->plt_offset == -1) {
732 uint8_t *jmp;
734 attr->plt_offset = mo->stubs->data_offset;
735 #ifdef TCC_TARGET_X86_64
736 if (type != R_X86_64_PLT32)
737 continue;
738 jmp = section_ptr_add(mo->stubs, 6);
739 jmp[0] = 0xff; /* jmpq *ofs(%rip) */
740 jmp[1] = 0x25;
741 put_elf_reloc(s1->symtab, mo->stubs,
742 attr->plt_offset + 2,
743 R_X86_64_GOTPCREL, sym_index);
744 #elif defined TCC_TARGET_ARM64
745 if (type != R_AARCH64_CALL26)
746 continue;
747 jmp = section_ptr_add(mo->stubs, 12);
748 put_elf_reloc(s1->symtab, mo->stubs,
749 attr->plt_offset,
750 R_AARCH64_ADR_GOT_PAGE, sym_index);
751 write32le(jmp, // adrp x16, #sym
752 0x90000010);
753 put_elf_reloc(s1->symtab, mo->stubs,
754 attr->plt_offset + 4,
755 R_AARCH64_LD64_GOT_LO12_NC, sym_index);
756 write32le(jmp + 4, // ld x16,[x16, #sym]
757 0xf9400210);
758 write32le(jmp + 8, // br x16
759 0xd61f0200);
760 #endif
761 bind_rebase_add(mo, 1, s1->got->reloc->sh_info, &save_rel, attr);
762 pi = section_ptr_add(mo->indirsyms, sizeof(*pi));
763 *pi = mo->e2msym[sym_index];
764 mo->nr_plt++;
766 rel->r_info = ELFW(R_INFO)(mo->stubsym, type);
767 rel->r_addend += attr->plt_offset;
770 if (type == R_DATA_PTR || type == R_JMP_SLOT)
771 bind_rebase_add(mo, sym->st_shndx == SHN_UNDEF ? 1 : 0,
772 s->sh_info, &save_rel, NULL);
775 /* remove deleted binds */
776 for (i = 0, j = 0; i < mo->n_bind_rebase; i++)
777 if (mo->bind_rebase[i].bind == 2)
778 mo->n_bind--;
779 else
780 mo->bind_rebase[j++] = mo->bind_rebase[i];
781 mo->n_bind_rebase = j;
782 pi = section_ptr_add(mo->indirsyms, mo->n_got * sizeof(*pi));
783 memcpy(pi, goti, mo->n_got * sizeof(*pi));
784 tcc_free(goti);
787 #else
789 static void check_relocs(TCCState *s1, struct macho *mo)
791 uint8_t *jmp;
792 Section *s;
793 ElfW_Rel *rel, save_rel;
794 ElfW(Sym) *sym;
795 int i, type, gotplt_entry, sym_index, for_code;
796 int bind_offset, la_symbol_offset;
797 uint32_t *pi, *goti;
798 struct sym_attr *attr;
800 #ifdef TCC_TARGET_X86_64
801 jmp = section_ptr_add(mo->stub_helper, 16);
802 jmp[0] = 0x4c; /* leaq _dyld_private(%rip), %r11 */
803 jmp[1] = 0x8d;
804 jmp[2] = 0x1d;
805 put_elf_reloca(s1->symtab, mo->stub_helper, 3,
806 R_X86_64_PC32, mo->dyld_private, -4);
807 jmp[7] = 0x41; /* pushq %r11 */
808 jmp[8] = 0x53;
809 jmp[9] = 0xff; /* jmpq *dyld_stub_binder@GOT(%rip) */
810 jmp[10] = 0x25;
811 put_elf_reloca(s1->symtab, mo->stub_helper, 11,
812 R_X86_64_GOTPCREL, mo->dyld_stub_binder, -4);
813 jmp[15] = 0x90; /* nop */
814 #elif defined TCC_TARGET_ARM64
815 jmp = section_ptr_add(mo->stub_helper, 24);
816 put_elf_reloc(s1->symtab, mo->stub_helper, 0,
817 R_AARCH64_ADR_PREL_PG_HI21, mo->dyld_private);
818 write32le(jmp, 0x90000011); // adrp x17, _dyld_private@page
819 put_elf_reloc(s1->symtab, mo->stub_helper, 4,
820 R_AARCH64_LDST64_ABS_LO12_NC, mo->dyld_private);
821 write32le(jmp + 4, 0x91000231); // add x17,x17,_dyld_private@pageoff
822 write32le(jmp + 8, 0xa9bf47f0); // stp x16/x17, [sp, #-16]!
823 put_elf_reloc(s1->symtab, mo->stub_helper, 12,
824 R_AARCH64_ADR_GOT_PAGE, mo->dyld_stub_binder);
825 write32le(jmp + 12, 0x90000010); // adrp x16, dyld_stub_binder@page
826 put_elf_reloc(s1->symtab, mo->stub_helper, 16,
827 R_AARCH64_LD64_GOT_LO12_NC, mo->dyld_stub_binder);
828 write32le(jmp + 16, 0xf9400210); // ldr x16,[x16,dyld_stub_binder@pageoff]
829 write32le(jmp + 20, 0xd61f0200); // br x16
830 #endif
832 goti = NULL;
833 mo->nr_plt = mo->n_got = 0;
834 for (i = 1; i < s1->nb_sections; i++) {
835 s = s1->sections[i];
836 if (s->sh_type != SHT_RELX ||
837 !strncmp(s1->sections[s->sh_info]->name, ".debug_", 7))
838 continue;
839 for_each_elem(s, 0, rel, ElfW_Rel) {
840 save_rel = *rel;
841 type = ELFW(R_TYPE)(rel->r_info);
842 gotplt_entry = gotplt_entry_type(type);
843 for_code = code_reloc(type);
844 /* We generate a non-lazy pointer for used undefined symbols
845 and for defined symbols that must have a place for their
846 address due to codegen (i.e. a reloc requiring a got slot). */
847 sym_index = ELFW(R_SYM)(rel->r_info);
848 sym = &((ElfW(Sym) *)symtab_section->data)[sym_index];
849 if (sym->st_shndx == SHN_UNDEF
850 || gotplt_entry == ALWAYS_GOTPLT_ENTRY) {
851 attr = get_sym_attr(s1, sym_index, 1);
852 if (!attr->dyn_index) {
853 attr->got_offset = s1->got->data_offset;
854 attr->plt_offset = -1;
855 attr->dyn_index = 1; /* used as flag */
856 section_ptr_add(s1->got, PTR_SIZE);
857 put_elf_reloc(s1->symtab, s1->got, attr->got_offset,
858 R_JMP_SLOT, sym_index);
859 goti = tcc_realloc(goti, (mo->n_got + 1) * sizeof(*goti));
860 if (ELFW(ST_BIND)(sym->st_info) == STB_LOCAL) {
861 if (sym->st_shndx == SHN_UNDEF)
862 tcc_error("undefined local symbo: '%s'",
863 (char *) symtab_section->link->data + sym->st_name);
864 goti[mo->n_got++] = INDIRECT_SYMBOL_LOCAL;
865 } else {
866 goti[mo->n_got++] = mo->e2msym[sym_index];
867 if (sym->st_shndx == SHN_UNDEF
868 #ifdef TCC_TARGET_X86_64
869 && type == R_X86_64_GOTPCREL
870 #elif defined TCC_TARGET_ARM64
871 && type == R_AARCH64_ADR_GOT_PAGE
872 #endif
874 mo->bind =
875 tcc_realloc(mo->bind,
876 (mo->n_bind + 1) *
877 sizeof(struct bind));
878 mo->bind[mo->n_bind].section = s1->got->reloc->sh_info;
879 mo->bind[mo->n_bind].rel = save_rel;
880 mo->bind[mo->n_bind].rel.r_offset = attr->got_offset;
881 mo->n_bind++;
882 s1->got->reloc->data_offset -= sizeof (ElfW_Rel);
886 if (for_code && sym->st_shndx == SHN_UNDEF) {
887 if (attr->plt_offset == -1) {
888 attr->plt_offset = mo->stubs->data_offset;
889 #ifdef TCC_TARGET_X86_64
890 if (type != R_X86_64_PLT32)
891 continue;
892 /* __stubs */
893 jmp = section_ptr_add(mo->stubs, 6);
894 jmp[0] = 0xff; /* jmpq *__la_symbol_ptr(%rip) */
895 jmp[1] = 0x25;
896 put_elf_reloca(s1->symtab, mo->stubs,
897 mo->stubs->data_offset - 4,
898 R_X86_64_PC32, mo->lasym,
899 mo->la_symbol_ptr->data_offset - 4);
901 /* __stub_helper */
902 bind_offset = mo->stub_helper->data_offset + 1;
903 jmp = section_ptr_add(mo->stub_helper, 10);
904 jmp[0] = 0x68; /* pushq $bind_offset */
905 jmp[5] = 0xe9; /* jmpq __stub_helper */
906 write32le(jmp + 6, -mo->stub_helper->data_offset);
908 /* __la_symbol_ptr */
909 la_symbol_offset = mo->la_symbol_ptr->data_offset;
910 put_elf_reloca(s1->symtab, mo->la_symbol_ptr,
911 mo->la_symbol_ptr->data_offset,
912 R_DATA_PTR, mo->helpsym,
913 mo->stub_helper->data_offset - 10);
914 section_ptr_add(mo->la_symbol_ptr, PTR_SIZE);
915 #elif defined TCC_TARGET_ARM64
916 if (type != R_AARCH64_CALL26)
917 continue;
918 /* __stubs */
919 jmp = section_ptr_add(mo->stubs, 12);
920 put_elf_reloca(s1->symtab, mo->stubs,
921 mo->stubs->data_offset - 12,
922 R_AARCH64_ADR_PREL_PG_HI21, mo->lasym,
923 mo->la_symbol_ptr->data_offset);
924 write32le(jmp, // adrp x16, __la_symbol_ptr@page
925 0x90000010);
926 put_elf_reloca(s1->symtab, mo->stubs,
927 mo->stubs->data_offset - 8,
928 R_AARCH64_LDST64_ABS_LO12_NC, mo->lasym,
929 mo->la_symbol_ptr->data_offset);
930 write32le(jmp + 4, // ldr x16,[x16, __la_symbol_ptr@pageoff]
931 0xf9400210);
932 write32le(jmp + 8, // br x16
933 0xd61f0200);
935 /* __stub_helper */
936 bind_offset = mo->stub_helper->data_offset + 8;
937 jmp = section_ptr_add(mo->stub_helper, 12);
938 write32le(jmp + 0, // ldr w16, l0
939 0x18000050);
940 write32le(jmp + 4, // b stubHelperHeader
941 0x14000000 +
942 ((-(mo->stub_helper->data_offset - 8) / 4) &
943 0x3ffffff));
944 write32le(jmp + 8, 0); // l0: .long bind_offset
946 /* __la_symbol_ptr */
947 la_symbol_offset = mo->la_symbol_ptr->data_offset;
948 put_elf_reloca(s1->symtab, mo->la_symbol_ptr,
949 mo->la_symbol_ptr->data_offset,
950 R_DATA_PTR, mo->helpsym,
951 mo->stub_helper->data_offset - 12);
952 section_ptr_add(mo->la_symbol_ptr, PTR_SIZE);
953 #endif
954 mo->s_lazy_bind =
955 tcc_realloc(mo->s_lazy_bind, (mo->n_lazy_bind + 1) *
956 sizeof(struct s_lazy_bind));
957 mo->s_lazy_bind[mo->n_lazy_bind].section =
958 mo->stub_helper->reloc->sh_info;
959 mo->s_lazy_bind[mo->n_lazy_bind].bind_offset =
960 bind_offset;
961 mo->s_lazy_bind[mo->n_lazy_bind].la_symbol_offset =
962 la_symbol_offset;
963 mo->s_lazy_bind[mo->n_lazy_bind].rel = save_rel;
964 mo->s_lazy_bind[mo->n_lazy_bind].rel.r_offset =
965 attr->plt_offset;
966 mo->n_lazy_bind++;
967 pi = section_ptr_add(mo->indirsyms, sizeof(*pi));
968 *pi = mo->e2msym[sym_index];
969 mo->nr_plt++;
971 rel->r_info = ELFW(R_INFO)(mo->stubsym, type);
972 rel->r_addend += attr->plt_offset;
975 if (type == R_DATA_PTR || type == R_JMP_SLOT) {
976 if (sym->st_shndx == SHN_UNDEF) {
977 mo->bind = tcc_realloc(mo->bind,
978 (mo->n_bind + 1) *
979 sizeof(struct bind));
980 mo->bind[mo->n_bind].section = s->sh_info;
981 mo->bind[mo->n_bind].rel = save_rel;
982 mo->n_bind++;
984 else {
985 mo->s_rebase =
986 tcc_realloc(mo->s_rebase, (mo->n_rebase + 1) *
987 sizeof(struct s_rebase));
988 mo->s_rebase[mo->n_rebase].section = s->sh_info;
989 mo->s_rebase[mo->n_rebase].rel = save_rel;
990 mo->n_rebase++;
995 pi = section_ptr_add(mo->indirsyms, mo->n_got * sizeof(*pi));
996 memcpy(pi, goti, mo->n_got * sizeof(*pi));
997 pi = section_ptr_add(mo->indirsyms, mo->nr_plt * sizeof(*pi));
998 memcpy(pi, mo->indirsyms->data, mo->nr_plt * sizeof(*pi));
999 tcc_free(goti);
1001 #endif
1003 static int check_symbols(TCCState *s1, struct macho *mo)
1005 int sym_index, sym_end;
1006 int ret = 0;
1008 mo->ilocal = mo->iextdef = mo->iundef = -1;
1009 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
1010 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
1011 int elf_index = ((struct nlist_64 *)mo->symtab->data + sym_index - 1)->n_value;
1012 ElfW(Sym) *sym = (ElfW(Sym) *)symtab_section->data + elf_index;
1013 const char *name = (char*)symtab_section->link->data + sym->st_name;
1014 unsigned type = ELFW(ST_TYPE)(sym->st_info);
1015 unsigned bind = ELFW(ST_BIND)(sym->st_info);
1016 unsigned vis = ELFW(ST_VISIBILITY)(sym->st_other);
1018 dprintf("%4d (%4d): %09lx %4d %4d %4d %3d %s\n",
1019 sym_index, elf_index, (long)sym->st_value,
1020 type, bind, vis, sym->st_shndx, name);
1021 if (bind == STB_LOCAL) {
1022 if (mo->ilocal == -1)
1023 mo->ilocal = sym_index - 1;
1024 if (mo->iextdef != -1 || mo->iundef != -1)
1025 tcc_error("local syms after global ones");
1026 } else if (sym->st_shndx != SHN_UNDEF) {
1027 if (mo->iextdef == -1)
1028 mo->iextdef = sym_index - 1;
1029 if (mo->iundef != -1)
1030 tcc_error("external defined symbol after undefined");
1031 } else if (sym->st_shndx == SHN_UNDEF) {
1032 if (mo->iundef == -1)
1033 mo->iundef = sym_index - 1;
1034 if (ELFW(ST_BIND)(sym->st_info) == STB_WEAK
1035 || s1->output_type != TCC_OUTPUT_EXE
1036 || find_elf_sym(s1->dynsymtab_section, name)) {
1037 /* Mark the symbol as coming from a dylib so that
1038 relocate_syms doesn't complain. Normally bind_exe_dynsyms
1039 would do this check, and place the symbol into dynsym
1040 which is checked by relocate_syms. But Mach-O doesn't use
1041 bind_exe_dynsyms. */
1042 sym->st_shndx = SHN_FROMDLL;
1043 continue;
1045 tcc_error_noabort("undefined symbol '%s'", name);
1046 ret = -1;
1049 return ret;
1052 static void convert_symbol(TCCState *s1, struct macho *mo, struct nlist_64 *pn)
1054 struct nlist_64 n = *pn;
1055 ElfSym *sym = (ElfW(Sym) *)symtab_section->data + pn->n_value;
1056 const char *name = (char*)symtab_section->link->data + sym->st_name;
1057 switch(ELFW(ST_TYPE)(sym->st_info)) {
1058 case STT_NOTYPE:
1059 case STT_OBJECT:
1060 case STT_FUNC:
1061 case STT_SECTION:
1062 n.n_type = N_SECT;
1063 break;
1064 case STT_FILE:
1065 n.n_type = N_ABS;
1066 break;
1067 default:
1068 tcc_error("unhandled ELF symbol type %d %s",
1069 ELFW(ST_TYPE)(sym->st_info), name);
1071 if (sym->st_shndx == SHN_UNDEF)
1072 tcc_error("should have been rewritten to SHN_FROMDLL: %s", name);
1073 else if (sym->st_shndx == SHN_FROMDLL)
1074 n.n_type = N_UNDF, n.n_sect = 0;
1075 else if (sym->st_shndx == SHN_ABS)
1076 n.n_type = N_ABS, n.n_sect = 0;
1077 else if (sym->st_shndx >= SHN_LORESERVE)
1078 tcc_error("unhandled ELF symbol section %d %s", sym->st_shndx, name);
1079 else if (!mo->elfsectomacho[sym->st_shndx]) {
1080 if (strncmp(s1->sections[sym->st_shndx]->name, ".debug_", 7))
1081 tcc_error("ELF section %d(%s) not mapped into Mach-O for symbol %s",
1082 sym->st_shndx, s1->sections[sym->st_shndx]->name, name);
1084 else
1085 n.n_sect = mo->elfsectomacho[sym->st_shndx];
1086 if (ELFW(ST_BIND)(sym->st_info) == STB_GLOBAL)
1087 n.n_type |= N_EXT;
1088 else if (ELFW(ST_BIND)(sym->st_info) == STB_WEAK)
1089 n.n_desc |= N_WEAK_REF | (n.n_type != N_UNDF ? N_WEAK_DEF : 0);
1090 n.n_strx = pn->n_strx;
1091 n.n_value = sym->st_value;
1092 *pn = n;
1095 static void convert_symbols(TCCState *s1, struct macho *mo)
1097 struct nlist_64 *pn;
1098 for_each_elem(mo->symtab, 0, pn, struct nlist_64)
1099 convert_symbol(s1, mo, pn);
1102 static int machosymcmp(const void *_a, const void *_b, void *arg)
1104 TCCState *s1 = arg;
1105 int ea = ((struct nlist_64 *)_a)->n_value;
1106 int eb = ((struct nlist_64 *)_b)->n_value;
1107 ElfSym *sa = (ElfSym *)symtab_section->data + ea;
1108 ElfSym *sb = (ElfSym *)symtab_section->data + eb;
1109 int r;
1110 /* locals, then defined externals, then undefined externals, the
1111 last two sections also by name, otherwise stable sort */
1112 r = (ELFW(ST_BIND)(sb->st_info) == STB_LOCAL)
1113 - (ELFW(ST_BIND)(sa->st_info) == STB_LOCAL);
1114 if (r)
1115 return r;
1116 r = (sa->st_shndx == SHN_UNDEF) - (sb->st_shndx == SHN_UNDEF);
1117 if (r)
1118 return r;
1119 if (ELFW(ST_BIND)(sa->st_info) != STB_LOCAL) {
1120 const char * na = (char*)symtab_section->link->data + sa->st_name;
1121 const char * nb = (char*)symtab_section->link->data + sb->st_name;
1122 r = strcmp(na, nb);
1123 if (r)
1124 return r;
1126 return ea - eb;
1129 /* cannot use qsort because code has to be reentrant */
1130 static void tcc_qsort (void *base, size_t nel, size_t width,
1131 int (*comp)(const void *, const void *, void *), void *arg)
1133 size_t wnel, gap, wgap, i, j, k;
1134 char *a, *b, tmp;
1136 wnel = width * nel;
1137 for (gap = 0; ++gap < nel;)
1138 gap *= 3;
1139 while ( gap /= 3 ) {
1140 wgap = width * gap;
1141 for (i = wgap; i < wnel; i += width) {
1142 for (j = i - wgap; ;j -= wgap) {
1143 a = j + (char *)base;
1144 b = a + wgap;
1145 if ( (*comp)(a, b, arg) <= 0 )
1146 break;
1147 k = width;
1148 do {
1149 tmp = *a;
1150 *a++ = *b;
1151 *b++ = tmp;
1152 } while ( --k );
1153 if (j < wgap)
1154 break;
1160 static void create_symtab(TCCState *s1, struct macho *mo)
1162 int sym_index, sym_end;
1163 struct nlist_64 *pn;
1165 /* Stub creation belongs to check_relocs, but we need to create
1166 the symbol now, so its included in the sorting. */
1167 mo->stubs = new_section(s1, "__stubs", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
1168 s1->got = new_section(s1, ".got", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
1169 mo->stubsym = put_elf_sym(s1->symtab, 0, 0,
1170 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
1171 mo->stubs->sh_num, ".__stubs");
1172 #ifdef CONFIG_NEW_MACHO
1173 mo->chained_fixups = new_section(s1, "CHAINED_FIXUPS",
1174 SHT_LINKEDIT, SHF_ALLOC | SHF_WRITE);
1175 #else
1176 mo->stub_helper = new_section(s1, "__stub_helper", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
1177 mo->la_symbol_ptr = new_section(s1, "__la_symbol_ptr", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
1178 mo->helpsym = put_elf_sym(s1->symtab, 0, 0,
1179 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
1180 mo->stub_helper->sh_num, ".__stub_helper");
1181 mo->lasym = put_elf_sym(s1->symtab, 0, 0,
1182 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
1183 mo->la_symbol_ptr->sh_num, ".__la_symbol_ptr");
1184 section_ptr_add(data_section, -data_section->data_offset & (PTR_SIZE - 1));
1185 mo->dyld_private = put_elf_sym(s1->symtab, data_section->data_offset, PTR_SIZE,
1186 ELFW(ST_INFO)(STB_LOCAL, STT_OBJECT), 0,
1187 data_section->sh_num, ".__dyld_private");
1188 section_ptr_add(data_section, PTR_SIZE);
1189 mo->dyld_stub_binder = put_elf_sym(s1->symtab, 0, 0,
1190 ELFW(ST_INFO)(STB_GLOBAL, STT_OBJECT), 0,
1191 SHN_UNDEF, "dyld_stub_binder");
1192 mo->rebase = new_section(s1, "REBASE", SHT_LINKEDIT, SHF_ALLOC | SHF_WRITE);
1193 mo->binding = new_section(s1, "BINDING", SHT_LINKEDIT, SHF_ALLOC | SHF_WRITE);
1194 mo->weak_binding = new_section(s1, "WEAK_BINDING", SHT_LINKEDIT, SHF_ALLOC | SHF_WRITE);
1195 mo->lazy_binding = new_section(s1, "LAZY_BINDING", SHT_LINKEDIT, SHF_ALLOC | SHF_WRITE);
1196 #endif
1197 mo->exports = new_section(s1, "EXPORT", SHT_LINKEDIT, SHF_ALLOC | SHF_WRITE);
1198 mo->indirsyms = new_section(s1, "LEINDIR", SHT_LINKEDIT, SHF_ALLOC | SHF_WRITE);
1200 mo->symtab = new_section(s1, "LESYMTAB", SHT_LINKEDIT, SHF_ALLOC | SHF_WRITE);
1201 mo->strtab = new_section(s1, "LESTRTAB", SHT_LINKEDIT, SHF_ALLOC | SHF_WRITE);
1202 put_elf_str(mo->strtab, " "); /* Mach-O starts strtab with a space */
1203 sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
1204 pn = section_ptr_add(mo->symtab, sizeof(*pn) * (sym_end - 1));
1205 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
1206 ElfW(Sym) *sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1207 const char *name = (char*)symtab_section->link->data + sym->st_name;
1208 pn[sym_index - 1].n_strx = put_elf_str(mo->strtab, name);
1209 pn[sym_index - 1].n_value = sym_index;
1211 section_ptr_add(mo->strtab, -mo->strtab->data_offset & (PTR_SIZE - 1));
1212 tcc_qsort(pn, sym_end - 1, sizeof(*pn), machosymcmp, s1);
1213 mo->e2msym = tcc_malloc(sym_end * sizeof(*mo->e2msym));
1214 mo->e2msym[0] = -1;
1215 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
1216 mo->e2msym[pn[sym_index - 1].n_value] = sym_index - 1;
1220 const struct {
1221 int seg_initial;
1222 uint32_t flags;
1223 const char *name;
1224 } skinfo[sk_last] = {
1225 /*[sk_unknown] =*/ { 0 },
1226 /*[sk_discard] =*/ { 0 },
1227 /*[sk_text] =*/ { 1, S_REGULAR | S_ATTR_PURE_INSTRUCTIONS
1228 | S_ATTR_SOME_INSTRUCTIONS, "__text" },
1229 /*[sk_stubs] =*/ { 1, S_REGULAR | S_ATTR_PURE_INSTRUCTIONS | S_SYMBOL_STUBS
1230 | S_ATTR_SOME_INSTRUCTIONS , "__stubs" },
1231 /*[sk_stub_helper] =*/ { 1, S_REGULAR | S_ATTR_PURE_INSTRUCTIONS
1232 | S_ATTR_SOME_INSTRUCTIONS , "__stub_helper" },
1233 /*[sk_ro_data] =*/ { 2, S_REGULAR, "__rodata" },
1234 /*[sk_uw_info] =*/ { 0 },
1235 /*[sk_nl_ptr] =*/ { 2, S_NON_LAZY_SYMBOL_POINTERS, "__got" },
1236 /*[sk_debug_info] =*/ { 3, S_REGULAR | S_ATTR_DEBUG, "__debug_info" },
1237 /*[sk_debug_abbrev] =*/ { 3, S_REGULAR | S_ATTR_DEBUG, "__debug_abbrev" },
1238 /*[sk_debug_line] =*/ { 3, S_REGULAR | S_ATTR_DEBUG, "__debug_line" },
1239 /*[sk_debug_aranges] =*/ { 3, S_REGULAR | S_ATTR_DEBUG, "__debug_aranges" },
1240 /*[sk_debug_str] =*/ { 3, S_REGULAR | S_ATTR_DEBUG, "__debug_str" },
1241 /*[sk_debug_line_str] =*/ { 3, S_REGULAR | S_ATTR_DEBUG, "__debug_line_str" },
1242 /*[sk_stab] =*/ { 4, S_REGULAR, "__stab" },
1243 /*[sk_stab_str] =*/ { 4, S_REGULAR, "__stab_str" },
1244 /*[sk_la_ptr] =*/ { 4, S_LAZY_SYMBOL_POINTERS, "__la_symbol_ptr" },
1245 /*[sk_init] =*/ { 4, S_MOD_INIT_FUNC_POINTERS, "__mod_init_func" },
1246 /*[sk_fini] =*/ { 4, S_MOD_TERM_FUNC_POINTERS, "__mod_term_func" },
1247 /*[sk_rw_data] =*/ { 4, S_REGULAR, "__data" },
1248 /*[sk_bss] =*/ { 4, S_ZEROFILL, "__bss" },
1249 /*[sk_linkedit] =*/ { 5, S_REGULAR, NULL },
1252 #define START ((uint64_t)1 << 32)
1254 const struct {
1255 int used;
1256 const char *name;
1257 uint64_t vmaddr;
1258 uint64_t vmsize;
1259 vm_prot_t maxprot;
1260 vm_prot_t initprot;
1261 uint32_t flags;
1262 } all_segment[] = {
1263 { 1, "__PAGEZERO", 0, START, 0, 0, 0 },
1264 { 0, "__TEXT", START, 0, 5, 5, 0 },
1265 { 0, "__DATA_CONST", -1, 0, 3, 3, SG_READ_ONLY },
1266 { 0, "__DWARF", -1, 0, 7, 3, 0 },
1267 { 0, "__DATA", -1, 0, 3, 3, 0 },
1268 { 1, "__LINKEDIT", -1, 0, 1, 1, 0 },
1271 #define N_SEGMENT (sizeof(all_segment)/sizeof(all_segment[0]))
1273 #ifdef CONFIG_NEW_MACHO
1274 static void calc_fixup_size(TCCState *s1, struct macho *mo)
1276 int i, size;
1278 size = (sizeof(struct dyld_chained_fixups_header) + 7) & -8;
1279 size += (sizeof(struct dyld_chained_starts_in_image) + (mo->nseg - 1) * sizeof(uint32_t) + 7) & -8;
1280 for (i = (s1->output_type == TCC_OUTPUT_EXE); i < mo->nseg - 1; i++) {
1281 int page_count = (get_segment(mo, i)->vmsize + SEG_PAGE_SIZE - 1) / SEG_PAGE_SIZE;
1282 size += (sizeof(struct dyld_chained_starts_in_segment) + (page_count - 1) * sizeof(uint16_t) + 7) & -8;
1284 size += mo->n_bind * sizeof (struct dyld_chained_import) + 1;
1285 for (i = 0; i < mo->n_bind_rebase; i++) {
1286 if (mo->bind_rebase[i].bind) {
1287 int sym_index = ELFW(R_SYM)(mo->bind_rebase[i].rel.r_info);
1288 ElfW(Sym) *sym = &((ElfW(Sym) *)symtab_section->data)[sym_index];
1289 const char *name = (char *) symtab_section->link->data + sym->st_name;
1290 size += strlen(name) + 1;
1293 size = (size + 7) & -8;
1294 section_ptr_add(mo->chained_fixups, size);
1297 #else
1299 static void set_segment_and_offset(TCCState *s1, struct macho *mo, addr_t addr,
1300 uint8_t *ptr, int opcode,
1301 Section *sec, addr_t offset)
1303 int i;
1304 struct segment_command_64 *seg = NULL;
1306 for (i = (s1->output_type == TCC_OUTPUT_EXE); i < mo->nseg - 1; i++) {
1307 seg = get_segment(mo, i);
1308 if (addr >= seg->vmaddr && addr < (seg->vmaddr + seg->vmsize))
1309 break;
1311 *ptr = opcode | i;
1312 write_uleb128(sec, offset - seg->vmaddr);
1315 static void bind_rebase(TCCState *s1, struct macho *mo)
1317 int i;
1318 uint8_t *ptr;
1319 ElfW(Sym) *sym;
1320 const char *name;
1322 for (i = 0; i < mo->n_lazy_bind; i++) {
1323 int sym_index = ELFW(R_SYM)(mo->s_lazy_bind[i].rel.r_info);
1325 sym = &((ElfW(Sym) *)symtab_section->data)[sym_index];
1326 name = (char *) symtab_section->link->data + sym->st_name;
1327 write32le(mo->stub_helper->data +
1328 mo->s_lazy_bind[i].bind_offset,
1329 mo->lazy_binding->data_offset);
1330 ptr = section_ptr_add(mo->lazy_binding, 1);
1331 set_segment_and_offset(s1, mo, mo->la_symbol_ptr->sh_addr, ptr,
1332 BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB,
1333 mo->lazy_binding,
1334 mo->s_lazy_bind[i].la_symbol_offset +
1335 mo->la_symbol_ptr->sh_addr);
1336 ptr = section_ptr_add(mo->lazy_binding, 5 + strlen(name));
1337 *ptr++ = BIND_OPCODE_SET_DYLIB_SPECIAL_IMM |
1338 (BIND_SPECIAL_DYLIB_FLAT_LOOKUP & 0xf);
1339 *ptr++ = BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM | 0;
1340 strcpy((char *)ptr, name);
1341 ptr += strlen(name) + 1;
1342 *ptr++ = BIND_OPCODE_DO_BIND;
1343 *ptr = BIND_OPCODE_DONE;
1345 for (i = 0; i < mo->n_rebase; i++) {
1346 Section *s = s1->sections[mo->s_rebase[i].section];
1348 ptr = section_ptr_add(mo->rebase, 2);
1349 *ptr++ = REBASE_OPCODE_SET_TYPE_IMM | REBASE_TYPE_POINTER;
1350 set_segment_and_offset(s1, mo, s->sh_addr, ptr,
1351 REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB,
1352 mo->rebase,
1353 mo->s_rebase[i].rel.r_offset +
1354 s->sh_addr);
1355 ptr = section_ptr_add(mo->rebase, 1);
1356 *ptr = REBASE_OPCODE_DO_REBASE_IMM_TIMES | 1;
1358 for (i = 0; i < mo->n_bind; i++) {
1359 int sym_index = ELFW(R_SYM)(mo->bind[i].rel.r_info);
1360 Section *s = s1->sections[mo->bind[i].section];
1361 Section *binding;
1363 sym = &((ElfW(Sym) *)symtab_section->data)[sym_index];
1364 name = (char *) symtab_section->link->data + sym->st_name;
1365 binding = ELFW(ST_BIND)(sym->st_info) == STB_WEAK
1366 ? mo->weak_binding : mo->binding;
1367 ptr = section_ptr_add(binding, 4 + (binding == mo->binding) +
1368 strlen(name));
1369 if (binding == mo->binding)
1370 *ptr++ = BIND_OPCODE_SET_DYLIB_SPECIAL_IMM |
1371 (BIND_SPECIAL_DYLIB_FLAT_LOOKUP & 0xf);
1372 *ptr++ = BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM |
1373 (binding == mo->weak_binding
1374 ? BIND_SYMBOL_FLAGS_WEAK_IMPORT : 0);
1375 strcpy((char *)ptr, name);
1376 ptr += strlen(name) + 1;
1377 *ptr++ = BIND_OPCODE_SET_TYPE_IMM | BIND_TYPE_POINTER;
1378 set_segment_and_offset(s1, mo, s->sh_addr, ptr,
1379 BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB,
1380 binding,
1381 mo->bind[i].rel.r_offset + s->sh_addr);
1382 ptr = section_ptr_add(binding, 1);
1383 *ptr++ = BIND_OPCODE_DO_BIND;
1385 if (mo->rebase->data_offset) {
1386 ptr = section_ptr_add(mo->rebase, 1);
1387 *ptr = REBASE_OPCODE_DONE;
1389 if (mo->binding->data_offset) {
1390 ptr = section_ptr_add(mo->binding, 1);
1391 *ptr = BIND_OPCODE_DONE;
1393 if (mo->weak_binding->data_offset) {
1394 ptr = section_ptr_add(mo->weak_binding, 1);
1395 *ptr = BIND_OPCODE_DONE;
1397 tcc_free(mo->s_lazy_bind);
1398 tcc_free(mo->s_rebase);
1399 tcc_free(mo->bind);
1401 #endif
1403 struct trie_info {
1404 const char *name;
1405 int flag;
1406 addr_t addr;
1407 int str_size;
1408 int term_size;
1411 struct trie_node {
1412 int start;
1413 int end;
1414 int index_start;
1415 int index_end;
1416 int n_child;
1417 struct trie_node *child;
1420 struct trie_seq {
1421 int n_child;
1422 struct trie_node *node;
1423 int offset;
1424 int nest_offset;
1427 static void create_trie(struct trie_node *node,
1428 int from, int to, int index_start,
1429 int n_trie, struct trie_info *trie)
1431 int i;
1432 int start, end, index_end;
1433 char cur;
1434 struct trie_node *child;
1436 for (i = from; i < to; i = end) {
1437 cur = trie[i].name[index_start];
1438 start = i++;
1439 for (; i < to; i++)
1440 if (cur != trie[i].name[index_start])
1441 break;
1442 end = i;
1443 if (start == end - 1 ||
1444 (trie[start].name[index_start] &&
1445 trie[start].name[index_start + 1] == 0))
1446 index_end = trie[start].str_size - 1;
1447 else {
1448 index_end = index_start + 1;
1449 for (;;) {
1450 cur = trie[start].name[index_end];
1451 for (i = start + 1; i < end; i++)
1452 if (cur != trie[i].name[index_end])
1453 break;
1454 if (trie[start].name[index_end] &&
1455 trie[start].name[index_end + 1] == 0) {
1456 end = start + 1;
1457 index_end = trie[start].str_size - 1;
1458 break;
1460 if (i != end)
1461 break;
1462 index_end++;
1465 node->child = tcc_realloc(node->child,
1466 (node->n_child + 1) *
1467 sizeof(struct trie_node));
1468 child = &node->child[node->n_child];
1469 child->start = start;
1470 child->end = end;
1471 child->index_start = index_start;
1472 child->index_end = index_end;
1473 child->n_child = 0;
1474 child->child = NULL;
1475 node->n_child++;
1476 if (start != end - 1)
1477 create_trie(child, start, end, index_end, n_trie, trie);
1481 static int create_seq(int *offset, int *n_seq, struct trie_seq **seq,
1482 struct trie_node *node,
1483 int n_trie, struct trie_info *trie)
1485 int i, nest_offset, last_seq = *n_seq, retval = *offset;
1486 struct trie_seq *p_seq;
1487 struct trie_node *p_nest;
1489 for (i = 0; i < node->n_child; i++) {
1490 p_nest = &node->child[i];
1491 *seq = tcc_realloc(*seq, (*n_seq + 1) * sizeof(struct trie_seq));
1492 p_seq = &(*seq)[(*n_seq)++];
1493 p_seq->n_child = i == 0 ? node->n_child : -1;
1494 p_seq->node = p_nest;
1495 p_seq->offset = *offset;
1496 p_seq->nest_offset = 0;
1497 *offset += (i == 0 ? 1 + 1 : 0) +
1498 p_nest->index_end - p_nest->index_start + 1 + 3;
1500 for (i = 0; i < node->n_child; i++) {
1501 nest_offset =
1502 create_seq(offset, n_seq, seq, &node->child[i], n_trie, trie);
1503 p_seq = &(*seq)[last_seq + i];
1504 p_seq->nest_offset = nest_offset;
1506 return retval;
1509 static void node_free(struct trie_node *node)
1511 int i;
1513 for (i = 0; i < node->n_child; i++)
1514 node_free(&node->child[i]);
1515 tcc_free(node->child);
1518 static int triecmp(const void *_a, const void *_b, void *arg)
1520 struct trie_info *a = (struct trie_info *) _a;
1521 struct trie_info *b = (struct trie_info *) _b;
1522 int len_a = strlen(a->name);
1523 int len_b = strlen(b->name);
1525 /* strange sorting needed. Name 'xx' should be after 'xx1' */
1526 if (!strncmp(a->name, b->name, len_a < len_b ? len_a : len_b))
1527 return len_a < len_b ? 1 : (len_a > len_b ? -1 : 0);
1528 return strcmp(a->name, b->name);
1531 static void export_trie(TCCState *s1, struct macho *mo)
1533 int i, size, offset = 0, save_offset;
1534 uint8_t *ptr;
1535 int sym_index;
1536 int sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
1537 int n_trie = 0, n_seq = 0;
1538 struct trie_info *trie = NULL, *p_trie;
1539 struct trie_node node, *p_node;
1540 struct trie_seq *seq = NULL;
1541 addr_t vm_addr = get_segment(mo, s1->output_type == TCC_OUTPUT_EXE)->vmaddr;
1543 for (sym_index = 1; sym_index < sym_end; ++sym_index) {
1544 ElfW(Sym) *sym = (ElfW(Sym) *)symtab_section->data + sym_index;
1545 const char *name = (char*)symtab_section->link->data + sym->st_name;
1547 if (sym->st_shndx != SHN_UNDEF && sym->st_shndx < SHN_LORESERVE &&
1548 (ELFW(ST_BIND)(sym->st_info) == STB_GLOBAL ||
1549 ELFW(ST_BIND)(sym->st_info) == STB_WEAK)) {
1550 int flag = EXPORT_SYMBOL_FLAGS_KIND_REGULAR;
1551 addr_t addr =
1552 sym->st_value + s1->sections[sym->st_shndx]->sh_addr - vm_addr;
1554 if (ELFW(ST_BIND)(sym->st_info) == STB_WEAK)
1555 flag |= EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;
1556 dprintf ("%s %d %llx\n", name, flag, (long long)addr + vm_addr);
1557 trie = tcc_realloc(trie, (n_trie + 1) * sizeof(struct trie_info));
1558 trie[n_trie].name = name;
1559 trie[n_trie].flag = flag;
1560 trie[n_trie].addr = addr;
1561 trie[n_trie].str_size = strlen(name) + 1;
1562 trie[n_trie].term_size = uleb128_size(flag) + uleb128_size(addr);
1563 n_trie++;
1566 if (n_trie) {
1567 tcc_qsort(trie, n_trie, sizeof(struct trie_info), triecmp, NULL);
1568 memset(&node, 0, sizeof(node));
1569 create_trie(&node, 0, n_trie, 0, n_trie, trie);
1570 create_seq(&offset, &n_seq, &seq, &node, n_trie, trie);
1571 save_offset = offset;
1572 for (i = 0; i < n_seq; i++) {
1573 p_node = seq[i].node;
1574 if (p_node->n_child == 0) {
1575 p_trie = &trie[p_node->start];
1576 seq[i].nest_offset = offset;
1577 offset += 1 + p_trie->term_size + 1;
1580 for (i = 0; i < n_seq; i++) {
1581 p_node = seq[i].node;
1582 p_trie = &trie[p_node->start];
1583 if (seq[i].n_child >= 0) {
1584 section_ptr_add(mo->exports,
1585 seq[i].offset - mo->exports->data_offset);
1586 ptr = section_ptr_add(mo->exports, 2);
1587 *ptr++ = 0;
1588 *ptr = seq[i].n_child;
1590 size = p_node->index_end - p_node->index_start;
1591 ptr = section_ptr_add(mo->exports, size + 1);
1592 memcpy(ptr, &p_trie->name[p_node->index_start], size);
1593 ptr[size] = 0;
1594 write_uleb128(mo->exports, seq[i].nest_offset);
1596 section_ptr_add(mo->exports, save_offset - mo->exports->data_offset);
1597 for (i = 0; i < n_seq; i++) {
1598 p_node = seq[i].node;
1599 if (p_node->n_child == 0) {
1600 p_trie = &trie[p_node->start];
1601 write_uleb128(mo->exports, p_trie->term_size);
1602 write_uleb128(mo->exports, p_trie->flag);
1603 write_uleb128(mo->exports, p_trie->addr);
1604 ptr = section_ptr_add(mo->exports, 1);
1605 *ptr = 0;
1608 section_ptr_add(mo->exports, -mo->exports->data_offset & 7);
1609 node_free(&node);
1610 tcc_free(seq);
1612 tcc_free(trie);
1615 static void collect_sections(TCCState *s1, struct macho *mo, const char *filename)
1617 int i, sk, numsec;
1618 int used_segment[N_SEGMENT];
1619 uint64_t curaddr, fileofs;
1620 Section *s;
1621 struct segment_command_64 *seg;
1622 struct dylib_command *dylib;
1623 #ifdef CONFIG_NEW_MACHO
1624 struct linkedit_data_command *chained_fixups_lc;
1625 struct linkedit_data_command *export_trie_lc;
1626 #endif
1627 struct build_version_command *dyldbv;
1628 struct source_version_command *dyldsv;
1629 struct rpath_command *rpath;
1630 struct dylinker_command *dyldlc;
1631 struct symtab_command *symlc;
1632 struct dysymtab_command *dysymlc;
1633 char *str;
1635 for (i = 0; i < N_SEGMENT; i++)
1636 used_segment[i] = all_segment[i].used;
1638 memset (mo->sk_to_sect, 0, sizeof(mo->sk_to_sect));
1639 for (i = s1->nb_sections; i-- > 1;) {
1640 int type, flags;
1641 s = s1->sections[i];
1642 type = s->sh_type;
1643 flags = s->sh_flags;
1644 sk = sk_unknown;
1645 /* debug sections have sometimes no SHF_ALLOC */
1646 if ((flags & SHF_ALLOC) || !strncmp(s->name, ".debug_", 7)) {
1647 switch (type) {
1648 default: sk = sk_unknown; break;
1649 case SHT_INIT_ARRAY: sk = sk_init; break;
1650 case SHT_FINI_ARRAY: sk = sk_fini; break;
1651 case SHT_NOBITS: sk = sk_bss; break;
1652 case SHT_SYMTAB: sk = sk_discard; break;
1653 case SHT_STRTAB:
1654 if (s == stabstr_section)
1655 sk = sk_stab_str;
1656 else
1657 sk = sk_discard;
1658 break;
1659 case SHT_RELX: sk = sk_discard; break;
1660 case SHT_LINKEDIT: sk = sk_linkedit; break;
1661 case SHT_PROGBITS:
1662 if (s == mo->stubs)
1663 sk = sk_stubs;
1664 #ifndef CONFIG_NEW_MACHO
1665 else if (s == mo->stub_helper)
1666 sk = sk_stub_helper;
1667 else if (s == mo->la_symbol_ptr)
1668 sk = sk_la_ptr;
1669 #endif
1670 else if (s == rodata_section)
1671 sk = sk_ro_data;
1672 else if (s == s1->got)
1673 sk = sk_nl_ptr;
1674 else if (s == stab_section)
1675 sk = sk_stab;
1676 else if (s == dwarf_info_section)
1677 sk = sk_debug_info;
1678 else if (s == dwarf_abbrev_section)
1679 sk = sk_debug_abbrev;
1680 else if (s == dwarf_line_section)
1681 sk = sk_debug_line;
1682 else if (s == dwarf_aranges_section)
1683 sk = sk_debug_aranges;
1684 else if (s == dwarf_str_section)
1685 sk = sk_debug_str;
1686 else if (s == dwarf_line_str_section)
1687 sk = sk_debug_line_str;
1688 else if (flags & SHF_EXECINSTR)
1689 sk = sk_text;
1690 else if (flags & SHF_WRITE)
1691 sk = sk_rw_data;
1692 else
1693 sk = sk_ro_data;
1694 break;
1696 } else
1697 sk = sk_discard;
1698 s->prev = mo->sk_to_sect[sk].s;
1699 mo->sk_to_sect[sk].s = s;
1700 used_segment[skinfo[sk].seg_initial] = 1;
1703 if (s1->output_type != TCC_OUTPUT_EXE)
1704 used_segment[0] = 0;
1706 for (i = 0; i < N_SEGMENT; i++)
1707 if (used_segment[i]) {
1708 seg = add_segment(mo, all_segment[i].name);
1709 if (i == 1 && s1->output_type != TCC_OUTPUT_EXE)
1710 seg->vmaddr = 0;
1711 else
1712 seg->vmaddr = all_segment[i].vmaddr;
1713 seg->vmsize = all_segment[i].vmsize;
1714 seg->maxprot = all_segment[i].maxprot;
1715 seg->initprot = all_segment[i].initprot;
1716 seg->flags = all_segment[i].flags;
1717 for (sk = sk_unknown; sk < sk_last; sk++)
1718 if (skinfo[sk].seg_initial == i)
1719 mo->segment[sk] = mo->nseg - 1;
1722 if (s1->output_type != TCC_OUTPUT_EXE) {
1723 const char *name = s1->install_name ? s1->install_name : filename;
1724 i = (sizeof(*dylib) + strlen(name) + 1 + 7) &-8;
1725 dylib = add_lc(mo, LC_ID_DYLIB, i);
1726 dylib->name = sizeof(*dylib);
1727 dylib->timestamp = 1;
1728 dylib->current_version =
1729 s1->current_version ? s1->current_version : 1 << 16;
1730 dylib->compatibility_version =
1731 s1->compatibility_version ? s1->compatibility_version : 1 << 16;
1732 str = (char*)dylib + dylib->name;
1733 strcpy(str, name);
1736 #ifdef CONFIG_NEW_MACHO
1737 chained_fixups_lc = add_lc(mo, LC_DYLD_CHAINED_FIXUPS,
1738 sizeof(struct linkedit_data_command));
1739 export_trie_lc = add_lc(mo, LC_DYLD_EXPORTS_TRIE,
1740 sizeof(struct linkedit_data_command));
1741 #else
1742 mo->dyldinfo = add_lc(mo, LC_DYLD_INFO_ONLY, sizeof(*mo->dyldinfo));
1743 #endif
1745 symlc = add_lc(mo, LC_SYMTAB, sizeof(*symlc));
1746 dysymlc = add_lc(mo, LC_DYSYMTAB, sizeof(*dysymlc));
1748 if (s1->output_type == TCC_OUTPUT_EXE) {
1749 i = (sizeof(*dyldlc) + strlen("/usr/lib/dyld") + 1 + 7) &-8;
1750 dyldlc = add_lc(mo, LC_LOAD_DYLINKER, i);
1751 dyldlc->name = sizeof(*dyldlc);
1752 str = (char*)dyldlc + dyldlc->name;
1753 strcpy(str, "/usr/lib/dyld");
1756 dyldbv = add_lc(mo, LC_BUILD_VERSION, sizeof(*dyldbv));
1757 dyldbv->platform = PLATFORM_MACOS;
1758 dyldbv->minos = (10 << 16) + (6 << 8);
1759 dyldbv->sdk = (10 << 16) + (6 << 8);
1760 dyldbv->ntools = 0;
1762 dyldsv = add_lc(mo, LC_SOURCE_VERSION, sizeof(*dyldsv));
1763 dyldsv->version = 0;
1765 if (s1->output_type == TCC_OUTPUT_EXE) {
1766 mo->ep = add_lc(mo, LC_MAIN, sizeof(*mo->ep));
1767 mo->ep->entryoff = 4096;
1770 for(i = 0; i < s1->nb_loaded_dlls; i++) {
1771 DLLReference *dllref = s1->loaded_dlls[i];
1772 if (dllref->level == 0)
1773 add_dylib(mo, dllref->name);
1776 if (s1->rpath) {
1777 char *path = s1->rpath, *end;
1778 do {
1779 end = strchr(path, ':');
1780 if (!end)
1781 end = strchr(path, 0);
1782 i = (sizeof(*rpath) + (end - path) + 1 + 7) &-8;
1783 rpath = add_lc(mo, LC_RPATH, i);
1784 rpath->path = sizeof(*rpath);
1785 str = (char*)rpath + rpath->path;
1786 memcpy(str, path, end - path);
1787 str[end - path] = 0;
1788 path = end + 1;
1789 } while (*end);
1792 fileofs = 4096; /* leave space for mach-o headers */
1793 curaddr = get_segment(mo, s1->output_type == TCC_OUTPUT_EXE)->vmaddr;
1794 curaddr += 4096;
1795 seg = NULL;
1796 numsec = 0;
1797 mo->elfsectomacho = tcc_mallocz(sizeof(*mo->elfsectomacho) * s1->nb_sections);
1798 for (sk = sk_unknown; sk < sk_last; sk++) {
1799 struct section_64 *sec = NULL;
1800 if (seg) {
1801 seg->vmsize = curaddr - seg->vmaddr;
1802 seg->filesize = fileofs - seg->fileoff;
1804 #ifdef CONFIG_NEW_MACHO
1805 if (sk == sk_linkedit) {
1806 calc_fixup_size(s1, mo);
1807 export_trie(s1, mo);
1809 #else
1810 if (sk == sk_linkedit) {
1811 bind_rebase(s1, mo);
1812 export_trie(s1, mo);
1814 #endif
1815 if (skinfo[sk].seg_initial &&
1816 (s1->output_type != TCC_OUTPUT_EXE || mo->segment[sk]) &&
1817 mo->sk_to_sect[sk].s) {
1818 uint64_t al = 0;
1819 int si;
1820 seg = get_segment(mo, mo->segment[sk]);
1821 if (skinfo[sk].name) {
1822 si = add_section(mo, &seg, skinfo[sk].name);
1823 numsec++;
1824 mo->lc[mo->seg2lc[mo->segment[sk]]] = (struct load_command*)seg;
1825 mo->sk_to_sect[sk].machosect = si;
1826 sec = get_section(seg, si);
1827 sec->flags = skinfo[sk].flags;
1828 if (sk == sk_stubs)
1829 #ifdef TCC_TARGET_X86_64
1830 sec->reserved2 = 6;
1831 #elif defined TCC_TARGET_ARM64
1832 sec->reserved2 = 12;
1833 #endif
1834 if (sk == sk_nl_ptr)
1835 sec->reserved1 = mo->nr_plt;
1836 #ifndef CONFIG_NEW_MACHO
1837 if (sk == sk_la_ptr)
1838 sec->reserved1 = mo->nr_plt + mo->n_got;
1839 #endif
1841 if (seg->vmaddr == -1) {
1842 curaddr = (curaddr + SEG_PAGE_SIZE - 1) & -SEG_PAGE_SIZE;
1843 seg->vmaddr = curaddr;
1844 fileofs = (fileofs + SEG_PAGE_SIZE - 1) & -SEG_PAGE_SIZE;
1845 seg->fileoff = fileofs;
1848 for (s = mo->sk_to_sect[sk].s; s; s = s->prev) {
1849 int a = exact_log2p1(s->sh_addralign);
1850 if (a && al < (a - 1))
1851 al = a - 1;
1852 s->sh_size = s->data_offset;
1854 if (sec)
1855 sec->align = al;
1856 al = 1ULL << al;
1857 if (al > 4096)
1858 tcc_warning("alignment > 4096"), sec->align = 12, al = 4096;
1859 curaddr = (curaddr + al - 1) & -al;
1860 fileofs = (fileofs + al - 1) & -al;
1861 if (sec) {
1862 sec->addr = curaddr;
1863 sec->offset = fileofs;
1865 for (s = mo->sk_to_sect[sk].s; s; s = s->prev) {
1866 al = s->sh_addralign;
1867 curaddr = (curaddr + al - 1) & -al;
1868 dprintf("%s: curaddr now 0x%lx\n", s->name, (long)curaddr);
1869 s->sh_addr = curaddr;
1870 curaddr += s->sh_size;
1871 if (s->sh_type != SHT_NOBITS) {
1872 fileofs = (fileofs + al - 1) & -al;
1873 s->sh_offset = fileofs;
1874 fileofs += s->sh_size;
1875 dprintf("%s: fileofs now %ld\n", s->name, (long)fileofs);
1877 if (sec)
1878 mo->elfsectomacho[s->sh_num] = numsec;
1880 if (sec)
1881 sec->size = curaddr - sec->addr;
1883 if (DEBUG_MACHO)
1884 for (s = mo->sk_to_sect[sk].s; s; s = s->prev) {
1885 int type = s->sh_type;
1886 int flags = s->sh_flags;
1887 printf("%d section %-16s %-10s %09lx %04x %02d %s,%s,%s\n",
1889 s->name,
1890 type == SHT_PROGBITS ? "progbits" :
1891 type == SHT_NOBITS ? "nobits" :
1892 type == SHT_SYMTAB ? "symtab" :
1893 type == SHT_STRTAB ? "strtab" :
1894 type == SHT_INIT_ARRAY ? "init" :
1895 type == SHT_FINI_ARRAY ? "fini" :
1896 type == SHT_RELX ? "rel" : "???",
1897 (long)s->sh_addr,
1898 (unsigned)s->data_offset,
1899 s->sh_addralign,
1900 flags & SHF_ALLOC ? "alloc" : "",
1901 flags & SHF_WRITE ? "write" : "",
1902 flags & SHF_EXECINSTR ? "exec" : ""
1906 if (seg) {
1907 seg->vmsize = curaddr - seg->vmaddr;
1908 seg->filesize = fileofs - seg->fileoff;
1911 /* Fill symtab info */
1912 symlc->symoff = mo->symtab->sh_offset;
1913 symlc->nsyms = mo->symtab->data_offset / sizeof(struct nlist_64);
1914 symlc->stroff = mo->strtab->sh_offset;
1915 symlc->strsize = mo->strtab->data_offset;
1917 dysymlc->iundefsym = mo->iundef == -1 ? symlc->nsyms : mo->iundef;
1918 dysymlc->iextdefsym = mo->iextdef == -1 ? dysymlc->iundefsym : mo->iextdef;
1919 dysymlc->ilocalsym = mo->ilocal == -1 ? dysymlc->iextdefsym : mo->ilocal;
1920 dysymlc->nlocalsym = dysymlc->iextdefsym - dysymlc->ilocalsym;
1921 dysymlc->nextdefsym = dysymlc->iundefsym - dysymlc->iextdefsym;
1922 dysymlc->nundefsym = symlc->nsyms - dysymlc->iundefsym;
1923 dysymlc->indirectsymoff = mo->indirsyms->sh_offset;
1924 dysymlc->nindirectsyms = mo->indirsyms->data_offset / sizeof(uint32_t);
1926 #ifdef CONFIG_NEW_MACHO
1927 if (mo->chained_fixups->data_offset) {
1928 chained_fixups_lc->dataoff = mo->chained_fixups->sh_offset;
1929 chained_fixups_lc->datasize = mo->chained_fixups->data_offset;
1931 if (mo->exports->data_offset) {
1932 export_trie_lc->dataoff = mo->exports->sh_offset;
1933 export_trie_lc->datasize = mo->exports->data_offset;
1935 #else
1936 if (mo->rebase->data_offset) {
1937 mo->dyldinfo->rebase_off = mo->rebase->sh_offset;
1938 mo->dyldinfo->rebase_size = mo->rebase->data_offset;
1940 if (mo->binding->data_offset) {
1941 mo->dyldinfo->bind_off = mo->binding->sh_offset;
1942 mo->dyldinfo->bind_size = mo->binding->data_offset;
1944 if (mo->weak_binding->data_offset) {
1945 mo->dyldinfo->weak_bind_off = mo->weak_binding->sh_offset;
1946 mo->dyldinfo->weak_bind_size = mo->weak_binding->data_offset;
1948 if (mo->lazy_binding->data_offset) {
1949 mo->dyldinfo->lazy_bind_off = mo->lazy_binding->sh_offset;
1950 mo->dyldinfo->lazy_bind_size = mo->lazy_binding->data_offset;
1952 if (mo->exports->data_offset) {
1953 mo->dyldinfo->export_off = mo->exports->sh_offset;
1954 mo->dyldinfo->export_size = mo->exports->data_offset;
1956 #endif
1959 static void macho_write(TCCState *s1, struct macho *mo, FILE *fp)
1961 int i, sk;
1962 uint64_t fileofs = 0;
1963 Section *s;
1964 mo->mh.mh.magic = MH_MAGIC_64;
1965 #ifdef TCC_TARGET_X86_64
1966 mo->mh.mh.cputype = CPU_TYPE_X86_64;
1967 mo->mh.mh.cpusubtype = CPU_SUBTYPE_LIB64 | CPU_SUBTYPE_X86_ALL;
1968 #elif defined TCC_TARGET_ARM64
1969 mo->mh.mh.cputype = CPU_TYPE_ARM64;
1970 mo->mh.mh.cpusubtype = CPU_SUBTYPE_ARM64_ALL;
1971 #endif
1972 if (s1->output_type == TCC_OUTPUT_EXE) {
1973 mo->mh.mh.filetype = MH_EXECUTE;
1974 mo->mh.mh.flags = MH_DYLDLINK | MH_PIE;
1976 else {
1977 mo->mh.mh.filetype = MH_DYLIB;
1978 mo->mh.mh.flags = MH_DYLDLINK;
1980 mo->mh.mh.ncmds = mo->nlc;
1981 mo->mh.mh.sizeofcmds = 0;
1982 for (i = 0; i < mo->nlc; i++)
1983 mo->mh.mh.sizeofcmds += mo->lc[i]->cmdsize;
1985 fwrite(&mo->mh, 1, sizeof(mo->mh), fp);
1986 fileofs += sizeof(mo->mh);
1987 for (i = 0; i < mo->nlc; i++) {
1988 fwrite(mo->lc[i], 1, mo->lc[i]->cmdsize, fp);
1989 fileofs += mo->lc[i]->cmdsize;
1992 for (sk = sk_unknown; sk < sk_last; sk++) {
1993 //struct segment_command_64 *seg;
1994 if (skinfo[sk].seg_initial == 0 ||
1995 (s1->output_type == TCC_OUTPUT_EXE && !mo->segment[sk]) ||
1996 !mo->sk_to_sect[sk].s)
1997 continue;
1998 /*seg =*/ get_segment(mo, mo->segment[sk]);
1999 for (s = mo->sk_to_sect[sk].s; s; s = s->prev) {
2000 if (s->sh_type != SHT_NOBITS) {
2001 while (fileofs < s->sh_offset)
2002 fputc(0, fp), fileofs++;
2003 if (s->sh_size) {
2004 fwrite(s->data, 1, s->sh_size, fp);
2005 fileofs += s->sh_size;
2012 #ifdef CONFIG_NEW_MACHO
2013 static int bind_rebase_cmp(const void *_a, const void *_b, void *arg)
2015 TCCState *s1 = arg;
2016 struct bind_rebase *a = (struct bind_rebase *) _a;
2017 struct bind_rebase *b = (struct bind_rebase *) _b;
2018 addr_t aa = s1->sections[a->section]->sh_addr + a->rel.r_offset;
2019 addr_t ab = s1->sections[b->section]->sh_addr + b->rel.r_offset;
2021 return aa > ab ? 1 : aa < ab ? -1 : 0;
2024 ST_FUNC void bind_rebase_import(TCCState *s1, struct macho *mo)
2026 int i, j, k, bind_index, size, page_count, sym_index;
2027 const char *name;
2028 ElfW(Sym) *sym;
2029 unsigned char *data = mo->chained_fixups->data;
2030 struct segment_command_64 *seg;
2031 struct dyld_chained_fixups_header *header;
2032 struct dyld_chained_starts_in_image *image;
2033 struct dyld_chained_starts_in_segment *segment;
2034 struct dyld_chained_import *import;
2036 tcc_qsort(mo->bind_rebase, mo->n_bind_rebase, sizeof(struct bind_rebase),
2037 bind_rebase_cmp, s1);
2038 for (i = 0; i < mo->n_bind_rebase - 1; i++)
2039 if (mo->bind_rebase[i].section == mo->bind_rebase[i + 1].section &&
2040 mo->bind_rebase[i].rel.r_offset == mo->bind_rebase[i + 1].rel.r_offset) {
2041 sym_index = ELFW(R_SYM)(mo->bind_rebase[i].rel.r_info);
2042 sym = &((ElfW(Sym) *)symtab_section->data)[sym_index];
2043 name = (char *) symtab_section->link->data + sym->st_name;
2044 tcc_error("Overlap %s/%s %s:%s",
2045 mo->bind_rebase[i].bind ? "bind" : "rebase",
2046 mo->bind_rebase[i + 1].bind ? "bind" : "rebase",
2047 s1->sections[mo->bind_rebase[i].section]->name, name);
2049 header = (struct dyld_chained_fixups_header *) data;
2050 data += (sizeof(struct dyld_chained_fixups_header) + 7) & -8;
2051 header->starts_offset = data - mo->chained_fixups->data;
2052 header->imports_count = mo->n_bind;
2053 header->imports_format = DYLD_CHAINED_IMPORT;
2054 header->symbols_format = 0;
2055 size = sizeof(struct dyld_chained_starts_in_image) +
2056 (mo->nseg - 1) * sizeof(uint32_t);
2057 image = (struct dyld_chained_starts_in_image *) data;
2058 data += (size + 7) & -8;
2059 image->seg_count = mo->nseg;
2060 for (i = (s1->output_type == TCC_OUTPUT_EXE); i < mo->nseg - 1; i++) {
2061 image->seg_info_offset[i] = (data - mo->chained_fixups->data) -
2062 header->starts_offset;
2063 seg = get_segment(mo, i);
2064 page_count = (seg->vmsize + SEG_PAGE_SIZE - 1) / SEG_PAGE_SIZE;
2065 size = sizeof(struct dyld_chained_starts_in_segment) +
2066 (page_count - 1) * sizeof(uint16_t);
2067 segment = (struct dyld_chained_starts_in_segment *) data;
2068 data += (size + 7) & -8;
2069 segment->size = size;
2070 segment->page_size = SEG_PAGE_SIZE;
2071 #if 1
2072 #define PTR_64_OFFSET 0
2073 #define PTR_64_MASK 0x7FFFFFFFFFFULL
2074 segment->pointer_format = DYLD_CHAINED_PTR_64;
2075 #else
2076 #define PTR_64_OFFSET 0x100000000ULL
2077 #define PTR_64_MASK 0xFFFFFFFFFFFFFFULL
2078 segment->pointer_format = DYLD_CHAINED_PTR_64_OFFSET;
2079 #endif
2080 segment->segment_offset = seg->fileoff;
2081 segment->max_valid_pointer = 0;
2082 segment->page_count = page_count;
2083 // add bind/rebase
2084 bind_index = 0;
2085 k = 0;
2086 for (j = 0; j < page_count; j++) {
2087 addr_t start = seg->vmaddr + j * SEG_PAGE_SIZE;
2088 addr_t end = start + SEG_PAGE_SIZE;
2089 void *last = NULL;
2090 addr_t last_o = 0;
2091 addr_t cur_o, cur;
2092 struct dyld_chained_ptr_64_rebase *rebase;
2093 struct dyld_chained_ptr_64_bind *bind;
2095 segment->page_start[j] = DYLD_CHAINED_PTR_START_NONE;
2096 for (; k < mo->n_bind_rebase; k++) {
2097 Section *s = s1->sections[mo->bind_rebase[k].section];
2098 addr_t r_offset = mo->bind_rebase[k].rel.r_offset;
2099 addr_t addr = s->sh_addr + r_offset;
2101 if ((addr & 3) ||
2102 (addr & (SEG_PAGE_SIZE - 1)) > SEG_PAGE_SIZE - PTR_SIZE)
2103 tcc_error("Illegal rel_offset %s %lld",
2104 s->name, (long long)r_offset);
2105 if (addr >= end)
2106 break;
2107 if (addr >= start) {
2108 cur_o = addr - start;
2109 if (mo->bind_rebase[k].bind) {
2110 if (segment->page_start[j] == DYLD_CHAINED_PTR_START_NONE)
2111 segment->page_start[j] = cur_o;
2112 else {
2113 bind = (struct dyld_chained_ptr_64_bind *) last;
2114 bind->next = (cur_o - last_o) / 4;
2116 bind = (struct dyld_chained_ptr_64_bind *)
2117 (s->data + r_offset);
2118 last = bind;
2119 last_o = cur_o;
2120 bind->ordinal = bind_index;
2121 bind->addend = 0;
2122 bind->reserved = 0;
2123 bind->next = 0;
2124 bind->bind = 1;
2126 else {
2127 if (segment->page_start[j] == DYLD_CHAINED_PTR_START_NONE)
2128 segment->page_start[j] = cur_o;
2129 else {
2130 rebase = (struct dyld_chained_ptr_64_rebase *) last;
2131 rebase->next = (cur_o - last_o) / 4;
2133 rebase = (struct dyld_chained_ptr_64_rebase *)
2134 (s->data + r_offset);
2135 last = rebase;
2136 last_o = cur_o;
2137 cur = (*(uint64_t *) (s->data + r_offset)) -
2138 PTR_64_OFFSET;
2139 rebase->target = cur & PTR_64_MASK;
2140 rebase->high8 = cur >> (64 - 8);
2141 if (cur != ((uint64_t)rebase->high8 << (64 - 8)) + rebase->target)
2142 tcc_error("rebase error");
2143 rebase->reserved = 0;
2144 rebase->next = 0;
2145 rebase->bind = 0;
2148 bind_index += mo->bind_rebase[k].bind;
2152 // add imports
2153 header->imports_offset = data - mo->chained_fixups->data;
2154 import = (struct dyld_chained_import *) data;
2155 data += mo->n_bind * sizeof (struct dyld_chained_import);
2156 header->symbols_offset = data - mo->chained_fixups->data;
2157 data++;
2158 for (i = 0, bind_index = 0; i < mo->n_bind_rebase; i++) {
2159 if (mo->bind_rebase[i].bind) {
2160 import[bind_index].lib_ordinal =
2161 BIND_SPECIAL_DYLIB_FLAT_LOOKUP & 0xffu;
2162 import[bind_index].name_offset =
2163 (data - mo->chained_fixups->data) - header->symbols_offset;
2164 sym_index = ELFW(R_SYM)(mo->bind_rebase[i].rel.r_info);
2165 sym = &((ElfW(Sym) *)symtab_section->data)[sym_index];
2166 import[bind_index].weak_import =
2167 ELFW(ST_BIND)(sym->st_info) == STB_WEAK;
2168 name = (char *) symtab_section->link->data + sym->st_name;
2169 strcpy((char *) data, name);
2170 data += strlen(name) + 1;
2171 bind_index++;
2174 tcc_free(mo->bind_rebase);
2176 #endif
2178 ST_FUNC int macho_output_file(TCCState *s1, const char *filename)
2180 int fd, mode, file_type;
2181 FILE *fp;
2182 int i, ret = -1;
2183 struct macho mo;
2185 (void)memset(&mo, 0, sizeof(mo));
2187 file_type = s1->output_type;
2188 if (file_type == TCC_OUTPUT_OBJ)
2189 mode = 0666;
2190 else
2191 mode = 0777;
2192 unlink(filename);
2193 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, mode);
2194 if (fd < 0 || (fp = fdopen(fd, "wb")) == NULL) {
2195 tcc_error_noabort("could not write '%s: %s'", filename, strerror(errno));
2196 return -1;
2198 if (s1->verbose)
2199 printf("<- %s\n", filename);
2201 tcc_add_runtime(s1);
2202 tcc_macho_add_destructor(s1);
2203 resolve_common_syms(s1);
2204 create_symtab(s1, &mo);
2205 check_relocs(s1, &mo);
2206 ret = check_symbols(s1, &mo);
2207 if (!ret) {
2208 int save_output = s1->output_type;
2210 collect_sections(s1, &mo, filename);
2211 relocate_syms(s1, s1->symtab, 0);
2212 if (s1->output_type == TCC_OUTPUT_EXE)
2213 mo.ep->entryoff = get_sym_addr(s1, "main", 1, 1)
2214 - get_segment(&mo, 1)->vmaddr;
2215 if (s1->nb_errors)
2216 goto do_ret;
2217 // Macho uses bind/rebase instead of dynsym
2218 s1->output_type = TCC_OUTPUT_EXE;
2219 relocate_sections(s1);
2220 s1->output_type = save_output;
2221 #ifdef CONFIG_NEW_MACHO
2222 bind_rebase_import(s1, &mo);
2223 #endif
2224 convert_symbols(s1, &mo);
2225 macho_write(s1, &mo, fp);
2228 do_ret:
2229 for (i = 0; i < mo.nlc; i++)
2230 tcc_free(mo.lc[i]);
2231 tcc_free(mo.seg2lc);
2232 tcc_free(mo.lc);
2233 tcc_free(mo.elfsectomacho);
2234 tcc_free(mo.e2msym);
2236 fclose(fp);
2237 #ifdef CONFIG_CODESIGN
2238 if (!ret) {
2239 char command[1024];
2240 int retval;
2242 snprintf(command, sizeof(command), "codesign -f -s - %s", filename);
2243 retval = system (command);
2244 if (retval == -1 || !(WIFEXITED(retval) && WEXITSTATUS(retval) == 0))
2245 tcc_error ("command failed '%s'", command);
2247 #endif
2248 return ret;
2251 static uint32_t macho_swap32(uint32_t x)
2253 return (x >> 24) | (x << 24) | ((x >> 8) & 0xff00) | ((x & 0xff00) << 8);
2255 #define SWAP(x) (swap ? macho_swap32(x) : (x))
2256 #define tbd_parse_movepast(s) \
2257 (pos = (pos = strstr(pos, s)) ? pos + strlen(s) : NULL)
2258 #define tbd_parse_movetoany(cs) (pos = strpbrk(pos, cs))
2259 #define tbd_parse_skipws while (*pos && (*pos==' '||*pos=='\n')) ++pos
2260 #define tbd_parse_tramplequote if(*pos=='\''||*pos=='"') tbd_parse_trample
2261 #define tbd_parse_tramplespace if(*pos==' ') tbd_parse_trample
2262 #define tbd_parse_trample *pos++=0
2264 #ifdef TCC_IS_NATIVE
2265 /* Looks for the active developer SDK set by xcode-select (or the default
2266 one set during installation.) */
2267 ST_FUNC void tcc_add_macos_sdkpath(TCCState* s)
2269 char *sdkroot = NULL, *pos = NULL;
2270 void* xcs = dlopen("libxcselect.dylib", RTLD_GLOBAL | RTLD_LAZY);
2271 CString path;
2272 int (*f)(unsigned int, char**) = dlsym(xcs, "xcselect_host_sdk_path");
2273 cstr_new(&path);
2274 if (f) f(1, &sdkroot);
2275 if (sdkroot)
2276 pos = strstr(sdkroot,"SDKs/MacOSX");
2277 if (pos)
2278 cstr_printf(&path, "%.*s.sdk/usr/lib", (int)(pos - sdkroot + 11), sdkroot);
2279 /* must use free from libc directly */
2280 #pragma push_macro("free")
2281 #undef free
2282 free(sdkroot);
2283 #pragma pop_macro("free")
2284 if (path.size)
2285 tcc_add_library_path(s, (char*)path.data);
2286 else
2287 tcc_add_library_path(s,
2288 "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib"
2289 ":" "/Applications/Xcode.app/Developer/SDKs/MacOSX.sdk/usr/lib"
2291 cstr_free(&path);
2294 ST_FUNC const char* macho_tbd_soname(const char* filename) {
2295 char *soname, *data, *pos;
2296 const char *ret = filename;
2298 int fd = open(filename,O_RDONLY);
2299 if (fd<0) return ret;
2300 pos = data = tcc_load_text(fd);
2301 if (!tbd_parse_movepast("install-name: ")) goto the_end;
2302 tbd_parse_skipws;
2303 tbd_parse_tramplequote;
2304 soname = pos;
2305 if (!tbd_parse_movetoany("\n \"'")) goto the_end;
2306 tbd_parse_trample;
2307 ret = tcc_strdup(soname);
2308 the_end:
2309 tcc_free(data);
2310 return ret;
2312 #endif /* TCC_IS_NATIVE */
2314 ST_FUNC int macho_load_tbd(TCCState* s1, int fd, const char* filename, int lev)
2316 char *soname, *data, *pos;
2317 int ret = -1;
2319 pos = data = tcc_load_text(fd);
2320 if (!tbd_parse_movepast("install-name: ")) goto the_end;
2321 tbd_parse_skipws;
2322 tbd_parse_tramplequote;
2323 soname = pos;
2324 if (!tbd_parse_movetoany("\n \"'")) goto the_end;
2325 tbd_parse_trample;
2326 ret = 0;
2327 if (tcc_add_dllref(s1, soname, lev)->found)
2328 goto the_end;
2329 while(pos) {
2330 char* sym = NULL;
2331 int cont = 1;
2332 if (!tbd_parse_movepast("symbols: ")) break;
2333 if (!tbd_parse_movepast("[")) break;
2334 while (cont) {
2335 tbd_parse_skipws;
2336 tbd_parse_tramplequote;
2337 sym = pos;
2338 if (!tbd_parse_movetoany(",] \"'")) break;
2339 tbd_parse_tramplequote;
2340 tbd_parse_tramplespace;
2341 tbd_parse_skipws;
2342 if (*pos==0||*pos==']') cont=0;
2343 tbd_parse_trample;
2344 set_elf_sym(s1->dynsymtab_section, 0, 0,
2345 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0, SHN_UNDEF, sym);
2349 the_end:
2350 tcc_free(data);
2351 return ret;
2354 ST_FUNC int macho_load_dll(TCCState * s1, int fd, const char* filename, int lev)
2356 unsigned char buf[sizeof(struct mach_header_64)];
2357 void *buf2;
2358 uint32_t machofs = 0;
2359 struct fat_header fh;
2360 struct mach_header mh;
2361 struct load_command *lc;
2362 int i, swap = 0;
2363 const char *soname = filename;
2364 struct nlist_64 *symtab = 0;
2365 uint32_t nsyms = 0;
2366 char *strtab = 0;
2367 uint32_t strsize = 0;
2368 uint32_t iextdef = 0;
2369 uint32_t nextdef = 0;
2371 again:
2372 if (full_read(fd, buf, sizeof(buf)) != sizeof(buf))
2373 return -1;
2374 memcpy(&fh, buf, sizeof(fh));
2375 if (fh.magic == FAT_MAGIC || fh.magic == FAT_CIGAM) {
2376 struct fat_arch *fa = load_data(fd, sizeof(fh),
2377 fh.nfat_arch * sizeof(*fa));
2378 swap = fh.magic == FAT_CIGAM;
2379 for (i = 0; i < SWAP(fh.nfat_arch); i++)
2380 #ifdef TCC_TARGET_X86_64
2381 if (SWAP(fa[i].cputype) == CPU_TYPE_X86_64
2382 && SWAP(fa[i].cpusubtype) == CPU_SUBTYPE_X86_ALL)
2383 #elif defined TCC_TARGET_ARM64
2384 if (SWAP(fa[i].cputype) == CPU_TYPE_ARM64
2385 && SWAP(fa[i].cpusubtype) == CPU_SUBTYPE_ARM64_ALL)
2386 #endif
2387 break;
2388 if (i == SWAP(fh.nfat_arch)) {
2389 tcc_free(fa);
2390 return -1;
2392 machofs = SWAP(fa[i].offset);
2393 tcc_free(fa);
2394 lseek(fd, machofs, SEEK_SET);
2395 goto again;
2396 } else if (fh.magic == FAT_MAGIC_64 || fh.magic == FAT_CIGAM_64) {
2397 tcc_warning("%s: Mach-O fat 64bit files of type 0x%x not handled",
2398 filename, fh.magic);
2399 return -1;
2402 memcpy(&mh, buf, sizeof(mh));
2403 if (mh.magic != MH_MAGIC_64)
2404 return -1;
2405 dprintf("found Mach-O at %d\n", machofs);
2406 buf2 = load_data(fd, machofs + sizeof(struct mach_header_64), mh.sizeofcmds);
2407 for (i = 0, lc = buf2; i < mh.ncmds; i++) {
2408 dprintf("lc %2d: 0x%08x\n", i, lc->cmd);
2409 switch (lc->cmd) {
2410 case LC_SYMTAB:
2412 struct symtab_command *sc = (struct symtab_command*)lc;
2413 nsyms = sc->nsyms;
2414 symtab = load_data(fd, machofs + sc->symoff, nsyms * sizeof(*symtab));
2415 strsize = sc->strsize;
2416 strtab = load_data(fd, machofs + sc->stroff, strsize);
2417 break;
2419 case LC_ID_DYLIB:
2421 struct dylib_command *dc = (struct dylib_command*)lc;
2422 soname = (char*)lc + dc->name;
2423 dprintf(" ID_DYLIB %d 0x%x 0x%x %s\n",
2424 dc->timestamp, dc->current_version,
2425 dc->compatibility_version, soname);
2426 break;
2428 case LC_REEXPORT_DYLIB:
2430 struct dylib_command *dc = (struct dylib_command*)lc;
2431 char *name = (char*)lc + dc->name;
2432 int subfd = open(name, O_RDONLY | O_BINARY);
2433 dprintf(" REEXPORT %s\n", name);
2434 if (subfd < 0)
2435 tcc_warning("can't open %s (reexported from %s)", name, filename);
2436 else {
2437 /* Hopefully the REEXPORTs never form a cycle, we don't check
2438 for that! */
2439 macho_load_dll(s1, subfd, name, lev + 1);
2440 close(subfd);
2442 break;
2444 case LC_DYSYMTAB:
2446 struct dysymtab_command *dc = (struct dysymtab_command*)lc;
2447 iextdef = dc->iextdefsym;
2448 nextdef = dc->nextdefsym;
2449 break;
2452 lc = (struct load_command*) ((char*)lc + lc->cmdsize);
2455 if (tcc_add_dllref(s1, soname, lev)->found)
2456 goto the_end;
2458 if (!nsyms || !nextdef)
2459 tcc_warning("%s doesn't export any symbols?", filename);
2461 //dprintf("symbols (all):\n");
2462 dprintf("symbols (exported):\n");
2463 dprintf(" n: typ sec desc value name\n");
2464 //for (i = 0; i < nsyms; i++) {
2465 for (i = iextdef; i < iextdef + nextdef; i++) {
2466 struct nlist_64 *sym = symtab + i;
2467 dprintf("%5d: %3d %3d 0x%04x 0x%016lx %s\n",
2468 i, sym->n_type, sym->n_sect, sym->n_desc, (long)sym->n_value,
2469 strtab + sym->n_strx);
2470 set_elf_sym(s1->dynsymtab_section, 0, 0,
2471 ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE),
2472 0, SHN_UNDEF, strtab + sym->n_strx);
2475 the_end:
2476 tcc_free(strtab);
2477 tcc_free(symtab);
2478 tcc_free(buf2);
2479 return 0;