Debian Codegraph @

output/outmacho.c

raw
1 /* SPDX-License-Identifier: BSD-2-Clause */
2 /* Copyright 1996-2025 The NASM Authors - All Rights Reserved */
3
4 /*
5 * outmacho.c output routines for the Netwide Assembler to produce
6 * NeXTstep/OpenStep/Rhapsody/Darwin/MacOS X object files
7 */
8
9 #include "compiler.h"
10
11 #include "nctype.h"
12
13 #include "nasm.h"
14 #include "nasmlib.h"
15 #include "ilog2.h"
16 #include "labels.h"
17 #include "error.h"
18 #include "saa.h"
19 #include "raa.h"
20 #include "rbtree.h"
21 #include "hashtbl.h"
22 #include "outform.h"
23 #include "outlib.h"
24 #include "ver.h"
25 #include "dwarf.h"
26 #include "macho.h"
27
28 #if defined(OF_MACHO) || defined(OF_MACHO64)
29
30 /* Mach-O in-file header structure sizes */
31 #define MACHO_HEADER_SIZE 28
32 #define MACHO_SEGCMD_SIZE 56
33 #define MACHO_SECTCMD_SIZE 68
34 #define MACHO_SYMCMD_SIZE 24
35 #define MACHO_NLIST_SIZE 12
36 #define MACHO_RELINFO_SIZE 8
37
38 #define MACHO_HEADER64_SIZE 32
39 #define MACHO_SEGCMD64_SIZE 72
40 #define MACHO_SECTCMD64_SIZE 80
41 #define MACHO_NLIST64_SIZE 16
42 #define MACHO_BUILD_VERSION_SIZE 24
43
44 /* Mach-O relocations numbers */
45
46 #define VM_PROT_DEFAULT (VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE)
47 #define VM_PROT_ALL (VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE)
48
49 /* Platforms enum */
50 enum macho_platform {
51 #define X(_platform, _id, _name) _platform = _id,
52 MACHO_ALL_PLATFORMS
53 #undef X
54 };
55
56 /* Our internal relocation types */
57 enum reltype {
58 RL_ABS, /* Absolute relocation */
59 RL_REL, /* Relative relocation */
60 RL_TLV, /* Thread local */
61 RL_BRANCH, /* Relative direct branch */
62 RL_SUB, /* X86_64_RELOC_SUBTRACT */
63 RL_GOT, /* X86_64_RELOC_GOT */
64 RL_GOTLOAD /* X86_64_RELOC_GOT_LOAD */
65 };
66 #define RL_MAX_32 RL_TLV
67 #define RL_MAX_64 RL_GOTLOAD
68
69 struct macho_fmt {
70 uint32_t ptrsize; /* Pointer size in bytes */
71 uint32_t mh_magic; /* Which magic number to use */
72 uint32_t cpu_type; /* Which CPU type */
73 uint32_t lc_segment; /* Which segment load command */
74 uint32_t header_size; /* Header size */
75 uint32_t segcmd_size; /* Segment command size */
76 uint32_t sectcmd_size; /* Section command size */
77 uint32_t nlist_size; /* Nlist (symbol) size */
78 enum reltype maxreltype; /* Maximum entry in enum reltype permitted */
79 uint32_t reloc_abs; /* Absolute relocation type */
80 uint32_t reloc_rel; /* Relative relocation type */
81 uint32_t reloc_tlv; /* Thread local relocation type */
82 bool forcesym; /* Always use "external" (symbol-relative) relocations */
83 };
84
85 static struct macho_fmt fmt;
86
87 static void fwriteptr(uint64_t data, FILE * fp)
88 {
89 fwriteaddr(data, fmt.ptrsize, fp);
90 }
91
92 struct section {
93 /* nasm internal data */
94 struct section *next;
95 struct SAA *data;
96 int32_t index; /* Main section index */
97 int32_t subsection; /* Current subsection index */
98 int32_t fileindex;
99 struct reloc *relocs;
100 struct rbtree *syms[2]; /* All/global symbols symbols in section */
101 int align;
102 bool by_name; /* This section was specified by full MachO name */
103 char namestr[34]; /* segment,section as a C string */
104
105 /* data that goes into the file */
106 char sectname[16]; /* what this section is called */
107 char segname[16]; /* segment this section will be in */
108 uint64_t addr; /* in-memory address (subject to alignment) */
109 uint64_t size; /* in-memory and -file size */
110 uint64_t offset; /* in-file offset */
111 uint32_t pad; /* padding bytes before section */
112 uint32_t nreloc; /* relocation entry count */
113 uint32_t flags; /* type and attributes (masked) */
114 uint32_t extreloc; /* external relocations */
115 };
116
117 #define S_NASM_TYPE_MASK 0x800004ff /* we consider these bits "section type" */
118
119 /* fake section for absolute symbols, *not* part of the section linked list */
120 static struct section absolute_sect;
121
122 struct reloc {
123 /* nasm internal data */
124 struct reloc *next;
125
126 /* data that goes into the file */
127 int32_t addr; /* op's offset in section */
128 uint32_t snum:24, /* contains symbol index if
129 ** ext otherwise in-file
130 ** section number */
131 pcrel:1, /* relative relocation */
132 length:2, /* 0=byte, 1=word, 2=int32_t, 3=int64_t */
133 ext:1, /* external symbol referenced */
134 type:4; /* reloc type */
135 };
136
137 struct symbol {
138 /* nasm internal data */
139 struct rbtree symv[2]; /* All/global symbol rbtrees; "key" contains the
140 symbol offset. */
141 struct symbol *next; /* next symbol in the list */
142 char *name; /* name of this symbol */
143 int32_t initial_snum; /* symbol number used above in reloc */
144 int32_t snum; /* true snum for reloc */
145
146 /* data that goes into the file */
147 uint32_t strx; /* string table index */
148 uint8_t type; /* symbol type */
149 uint8_t sect; /* NO_SECT or section number */
150 uint16_t desc; /* for stab debugging, 0 for us */
151 };
152
153 #define DEFAULT_SECTION_ALIGNMENT 0 /* byte (i.e. no) alignment */
154
155 static struct section *sects, **sectstail, **sectstab;
156 static struct symbol *syms, **symstail;
157 static uint32_t nsyms;
158
159 /* These variables are set by macho_layout_symbols() to organize
160 the symbol table and string table in order the dynamic linker
161 expects. They are then used in macho_write() to put out the
162 symbols and strings in that order.
163
164 The order of the symbol table is:
165 local symbols
166 defined external symbols (sorted by name)
167 undefined external symbols (sorted by name)
168
169 The order of the string table is:
170 strings for external symbols
171 strings for local symbols
172 */
173 static uint32_t ilocalsym = 0;
174 static uint32_t iextdefsym = 0;
175 static uint32_t iundefsym = 0;
176 static uint32_t nlocalsym;
177 static uint32_t nextdefsym;
178 static uint32_t nundefsym;
179 static struct symbol **extdefsyms = NULL;
180 static struct symbol **undefsyms = NULL;
181
182 static struct RAA *extsyms;
183 static struct SAA *strs;
184 static uint32_t strslen;
185
186 /* Global file information. This should be cleaned up into either
187 a structure or as function arguments. */
188 static uint32_t head_ncmds = 0;
189 static uint32_t head_sizeofcmds = 0;
190 static uint32_t head_flags = 0;
191 static uint64_t seg_filesize = 0;
192 static uint64_t seg_vmsize = 0;
193 static uint32_t seg_nsects = 0;
194 static uint64_t rel_padcnt = 0;
195
196 static uint32_t buildver_platform = PLATFORM_UNKNOWN;
197 static uint32_t buildver_minos = 0; // x.y.z is 0xXXXXYYZZ
198 static uint32_t buildver_sdk = 0; // x.y.z is 0xXXXXYYZZ
199
200 /*
201 * Functions for handling fixed-length zero-padded string
202 * fields, that may or may not be null-terminated.
203 */
204
205 /* Copy a string into a zero-padded fixed-length field */
206 #define xstrncpy(xdst, xsrc) strncpy(xdst, xsrc, sizeof(xdst))
207
208 /* Compare a fixed-length field with a string */
209 #define xstrncmp(xdst, xsrc) strncmp(xdst, xsrc, sizeof(xdst))
210
211 #define alignint32_t(x) \
212 ALIGN(x, sizeof(int32_t)) /* align x to int32_t boundary */
213
214 #define alignint64_t(x) \
215 ALIGN(x, sizeof(int64_t)) /* align x to int64_t boundary */
216
217 #define alignptr(x) \
218 ALIGN(x, fmt.ptrsize) /* align x to output format width */
219
220 static struct hash_table section_by_name;
221 static struct RAA *section_by_index;
222
223 static struct section * never_null
224 find_or_add_section(const char *segname, const char *sectname)
225 {
226 struct hash_insert hi;
227 void **sp;
228 struct section *s;
229 char sect[34];
230
231 snprintf(sect, sizeof sect, "%-16s,%-16s", segname, sectname);
232
233 sp = hash_find(&section_by_name, sect, &hi);
234 if (sp)
235 return (struct section *)(*sp);
236
237 s = nasm_zalloc(sizeof *s);
238 xstrncpy(s->segname, segname);
239 xstrncpy(s->sectname, sectname);
240 xstrncpy(s->namestr, sect);
241 hash_add(&hi, s->namestr, s);
242
243 s->index = s->subsection = seg_alloc();
244 section_by_index = raa_write_ptr(section_by_index, s->index >> 1, s);
245
246 return s;
247 }
248
249 static inline bool is_new_section(const struct section *s)
250 {
251 return !s->data;
252 }
253
254 static struct section *get_section_by_name(const char *segname,
255 const char *sectname)
256 {
257 char sect[34];
258 void **sp;
259
260 snprintf(sect, sizeof sect, "%-16s,%-16s", segname, sectname);
261
262 sp = hash_find(&section_by_name, sect, NULL);
263 return sp ? (struct section *)(*sp) : NULL;
264 }
265
266 static struct section *get_section_by_index(int32_t index)
267 {
268 if (index < 0 || index >= SEG_ABS || (index & 1))
269 return NULL;
270
271 return raa_read_ptr(section_by_index, index >> 1);
272 }
273
274 struct dir_list {
275 struct dir_list *next;
276 struct dir_list *last;
277 const char *dir_name;
278 uint32_t dir;
279 };
280
281 struct file_list {
282 struct file_list *next;
283 struct file_list *last;
284 const char *file_name;
285 uint32_t file;
286 struct dir_list *dir;
287 };
288
289 struct dw_sect_list {
290 struct SAA *psaa;
291 int32_t section;
292 uint32_t line;
293 uint64_t offset;
294 uint32_t file;
295 struct dw_sect_list *next;
296 struct dw_sect_list *last;
297 };
298
299 struct section_info {
300 uint64_t size;
301 int32_t secto;
302 };
303
304 #define DW_LN_BASE (-5)
305 #define DW_LN_RANGE 14
306 #define DW_OPCODE_BASE 13
307 #define DW_MAX_LN (DW_LN_BASE + DW_LN_RANGE)
308 #define DW_MAX_SP_OPCODE 256
309
310 static struct file_list *dw_head_file = 0, *dw_cur_file = 0, **dw_last_file_next = NULL;
311 static struct dir_list *dw_head_dir = 0, **dw_last_dir_next = NULL;
312 static struct dw_sect_list *dw_head_sect = 0, *dw_cur_sect = 0, *dw_last_sect = 0;
313 static uint32_t cur_line = 0, dw_num_files = 0, dw_num_dirs = 0, dw_num_sects = 0;
314 static bool dbg_immcall = false;
315 static const char *module_name = NULL;
316
317 /*
318 * Special section numbers which are used to define Mach-O special
319 * symbols, which can be used with WRT to provide PIC relocation
320 * types.
321 */
322 static int32_t macho_tlvp_sect;
323 static int32_t macho_gotpcrel_sect;
324
325 static void macho_init(void)
326 {
327 module_name = inname;
328 sects = NULL;
329 sectstail = &sects;
330
331 /* Fake section for absolute symbols */
332 absolute_sect.index = NO_SEG;
333
334 syms = NULL;
335 symstail = &syms;
336 nsyms = 0;
337 nlocalsym = 0;
338 nextdefsym = 0;
339 nundefsym = 0;
340
341 extsyms = raa_init();
342 strs = saa_init(1L);
343
344 section_by_index = raa_init();
345
346 /* string table starts with a zero byte so index 0 is an empty string */
347 saa_wbytes(strs, zero_buffer, 1);
348 strslen = 1;
349
350 /* add special symbol for TLVP */
351 macho_tlvp_sect = seg_alloc() + 1;
352 backend_label("..tlvp", macho_tlvp_sect, 0L);
353 }
354
355 static void sect_write(struct section *sect,
356 const uint8_t *data, uint32_t len)
357 {
358 saa_wbytes(sect->data, data, len);
359 sect->size += len;
360 }
361
362 /*
363 * Find a suitable global symbol for a ..gotpcrel or ..tlvp reference
364 */
365 static struct symbol *macho_find_sym(struct section *s, uint64_t offset,
366 bool global, bool exact)
367 {
368 struct rbtree *srb;
369
370 srb = rb_search(s->syms[global], offset);
371
372 if (!srb || (exact && srb->key != offset)) {
373 nasm_error(ERR_NONFATAL, "unable to find a suitable%s%s symbol"
374 " for this reference",
375 global ? " global" : "",
376 s == &absolute_sect ? " absolute " : "");
377 return NULL;
378 }
379
380 return container_of(srb - global, struct symbol, symv);
381 }
382
383 static int64_t add_reloc(struct section *sect, int32_t section,
384 int64_t offset,
385 enum reltype reltype, int bytes)
386 {
387 struct reloc *r;
388 struct section *s;
389 int32_t fi;
390 int64_t adjust;
391
392 /* Double check this is a valid relocation type for this platform */
393 nasm_assert(reltype <= fmt.maxreltype);
394
395 /* the current end of the section will be the symbol's address for
396 ** now, might have to be fixed by macho_fixup_relocs() later on. make
397 ** sure we don't make the symbol scattered by setting the highest
398 ** bit by accident */
399 r = nasm_malloc(sizeof(struct reloc));
400 r->addr = sect->size & ~R_SCATTERED;
401 r->ext = 1;
402 adjust = 0;
403
404 /* match byte count 1, 2, 4, 8 to length codes 0, 1, 2, 3 respectively */
405 r->length = ilog2_32(bytes);
406
407 /* set default relocation values */
408 r->type = fmt.reloc_abs;
409 r->pcrel = 0;
410 r->snum = R_ABS;
411
412 s = get_section_by_index(section);
413 fi = s ? s->fileindex : NO_SECT;
414
415 /* absolute relocation */
416 switch (reltype) {
417 case RL_ABS:
418 if (section == NO_SEG) {
419 /* absolute (can this even happen?) */
420 r->ext = 0;
421 } else if (fi == NO_SECT) {
422 /* external */
423 r->snum = raa_read(extsyms, section);
424 } else {
425 /* local */
426 r->ext = 0;
427 r->snum = fi;
428 }
429 break;
430
431 case RL_REL:
432 case RL_BRANCH:
433 r->type = fmt.reloc_rel;
434 r->pcrel = 1;
435 if (section == NO_SEG) {
436 /* may optionally be converted below by fmt.forcesym */
437 r->ext = 0;
438 } else if (fi == NO_SECT) {
439 /* external */
440 sect->extreloc = 1;
441 r->snum = raa_read(extsyms, section);
442 if (reltype == RL_BRANCH)
443 r->type = X86_64_RELOC_BRANCH;
444 } else {
445 /* local */
446 r->ext = 0;
447 r->snum = fi;
448 if (reltype == RL_BRANCH)
449 r->type = X86_64_RELOC_BRANCH;
450 }
451 break;
452
453 case RL_SUB: /* obsolete */
454 nasm_warn(WARN_OTHER, "relcation with subtraction"
455 " becomes to be obsolete");
456 r->ext = 0;
457 r->type = X86_64_RELOC_SUBTRACTOR;
458 break;
459
460 case RL_GOT:
461 r->type = X86_64_RELOC_GOT;
462 goto needsym;
463
464 case RL_GOTLOAD:
465 r->type = X86_64_RELOC_GOT_LOAD;
466 goto needsym;
467
468 case RL_TLV:
469 r->type = fmt.reloc_tlv;
470 goto needsym;
471
472 needsym:
473 r->pcrel = (fmt.ptrsize == 8 ? 1 : 0);
474 if (section == NO_SEG) {
475 nasm_error(ERR_NONFATAL, "Unsupported use of use of WRT");
476 goto bail;
477 } else if (fi == NO_SECT) {
478 /* external */
479 r->snum = raa_read(extsyms, section);
480 } else {
481 /* internal - GOTPCREL doesn't need to be in global */
482 struct symbol *sym = macho_find_sym(s, offset,
483 false, /* reltype != RL_TLV */
484 true);
485 if (!sym) {
486 nasm_error(ERR_NONFATAL, "Symbol for WRT not found");
487 goto bail;
488 }
489
490 adjust -= sym->symv[0].key;
491 r->snum = sym->initial_snum;
492 }
493 break;
494 }
495
496 /*
497 * For 64-bit Mach-O, force a symbol reference if at all possible
498 * Allow for r->snum == R_ABS by searching absolute_sect
499 */
500 if (!r->ext && fmt.forcesym) {
501 struct symbol *sym = macho_find_sym(s ? s : &absolute_sect,
502 offset, false, false);
503 if (sym) {
504 adjust -= sym->symv[0].key;
505 r->snum = sym->initial_snum;
506 r->ext = 1;
507 }
508 }
509
510 if (r->pcrel)
511 adjust += ((r->ext && fmt.ptrsize == 8) ? bytes : -(int64_t)sect->size);
512
513 /* NeXT as puts relocs in reversed order (address-wise) into the
514 ** files, so we do the same, doesn't seem to make much of a
515 ** difference either way */
516 r->next = sect->relocs;
517 sect->relocs = r;
518 if (r->ext)
519 sect->extreloc = 1;
520 ++sect->nreloc;
521
522 return adjust;
523
524 bail:
525 nasm_free(r);
526 return 0;
527 }
528
529 static void macho_output(const struct out_data *out)
530 {
531 OUT_LEGACY(out,secto,data,type,size,section,wrt);
532 struct section *s;
533 int64_t addr, offset;
534 uint8_t mydata[16], *p;
535 bool is_bss;
536 enum reltype reltype;
537
538 s = get_section_by_index(secto);
539 if (!s) {
540 nasm_warn(WARN_OTHER, "attempt to assemble code in"
541 " unknown section: defaulting to `.text'");
542 s = get_section_by_name("__TEXT", "__text");
543
544 /* should never happen */
545 if (!s)
546 nasm_panic("text section not found");
547 }
548
549 /* debug code generation only for sections tagged with
550 * instruction attribute */
551 if (s->flags & S_ATTR_SOME_INSTRUCTIONS)
552 {
553 struct section_info sinfo;
554 sinfo.size = s->size;
555 sinfo.secto = secto;
556 dfmt->debug_output(0, &sinfo);
557 }
558
559 is_bss = (s->flags & SECTION_TYPE) == S_ZEROFILL;
560
561 if (is_bss && type != OUT_RESERVE) {
562 nasm_warn(WARN_OTHER, "attempt to initialize memory in "
563 "BSS section: ignored");
564 /* FIXME */
565 nasm_warn(WARN_OTHER, "section size may be negative"
566 " with address symbols");
567 s->size += realsize(type, size);
568 return;
569 }
570
571 memset(mydata, 0, sizeof(mydata));
572
573 switch (type) {
574 case OUT_RESERVE:
575 if (!is_bss) {
576 nasm_warn(WARN_ZEROING, "uninitialized space declared in"
577 " %s,%s section: zeroing", s->segname, s->sectname);
578
579 sect_write(s, NULL, size);
580 } else
581 s->size += size;
582
583 break;
584
585 case OUT_RAWDATA:
586 sect_write(s, data, size);
587 break;
588
589 case OUT_ADDRESS:
590 {
591 int asize = abs((int)size);
592
593 addr = *(int64_t *)data;
594 if (section != NO_SEG) {
595 if (section % 2) {
596 nasm_error(ERR_NONFATAL, "Mach-O format does not support"
597 " section base references");
598 } else if (wrt == NO_SEG) {
599 if (fmt.ptrsize == 8 && asize != 8) {
600 nasm_error(ERR_NONFATAL,
601 "Mach-O 64-bit format does not support"
602 " 32-bit absolute addresses");
603 } else {
604 addr += add_reloc(s, section, addr, RL_ABS, asize);
605 }
606 } else if (wrt == macho_tlvp_sect && fmt.ptrsize != 8 &&
607 asize == (int) fmt.ptrsize) {
608 addr += add_reloc(s, section, addr, RL_TLV, asize);
609 } else {
610 nasm_error(ERR_NONFATAL, "Mach-O format does not support"
611 " this use of WRT");
612 }
613 }
614
615 p = mydata;
616 WRITEADDR(p, addr, asize);
617 sect_write(s, mydata, asize);
618 break;
619 }
620
621 case OUT_REL1ADR:
622 case OUT_REL2ADR:
623
624 p = mydata;
625 offset = *(int64_t *)data;
626 addr = offset - size;
627
628 if (section != NO_SEG && section % 2) {
629 nasm_error(ERR_NONFATAL, "Mach-O format does not support"
630 " section base references");
631 } else if (fmt.ptrsize == 8) {
632 nasm_error(ERR_NONFATAL, "Unsupported non-32-bit"
633 " Macho-O relocation [2]");
634 } else if (wrt != NO_SEG) {
635 nasm_error(ERR_NONFATAL, "Mach-O format does not support"
636 " this use of WRT");
637 wrt = NO_SEG; /* we can at least _try_ to continue */
638 } else {
639 addr += add_reloc(s, section, addr+size, RL_REL,
640 type == OUT_REL1ADR ? 1 : 2);
641 }
642
643 WRITESHORT(p, addr);
644 sect_write(s, mydata, type == OUT_REL1ADR ? 1 : 2);
645 break;
646
647 case OUT_REL4ADR:
648 case OUT_REL8ADR:
649
650 p = mydata;
651 offset = *(int64_t *)data;
652 addr = offset - size;
653 reltype = RL_REL;
654
655 if (section != NO_SEG && section % 2) {
656 nasm_error(ERR_NONFATAL, "Mach-O format does not support"
657 " section base references");
658 } else if (wrt == NO_SEG) {
659 if (fmt.ptrsize == 8 &&
660 (s->flags & S_ATTR_SOME_INSTRUCTIONS)) {
661 uint8_t opcode[2];
662
663 opcode[0] = opcode[1] = 0;
664
665 /* HACK: Retrieve instruction opcode */
666 if (likely(s->data->datalen >= 2)) {
667 saa_fread(s->data, s->data->datalen-2, opcode, 2);
668 } else if (s->data->datalen == 1) {
669 saa_fread(s->data, 0, opcode+1, 1);
670 }
671
672 if ((opcode[0] != 0x0f && (opcode[1] & 0xfe) == 0xe8) ||
673 (opcode[0] == 0x0f && (opcode[1] & 0xf0) == 0x80)) {
674 /* Direct call, jmp, or jcc */
675 reltype = RL_BRANCH;
676 }
677 }
678 } else if (wrt == macho_gotpcrel_sect) {
679 reltype = RL_GOT;
680
681 if ((s->flags & S_ATTR_SOME_INSTRUCTIONS) &&
682 s->data->datalen >= 3) {
683 uint8_t gotload[3];
684
685 /* HACK: Retrieve instruction opcode */
686 saa_fread(s->data, s->data->datalen-3, gotload, 3);
687 if ((gotload[0] & 0xf8) == 0x48 &&
688 gotload[1] == 0x8b &&
689 (gotload[2] & 0307) == 0005) {
690 /* movq <reg>,[rel sym wrt ..gotpcrel] */
691 reltype = RL_GOTLOAD;
692 }
693 }
694 } else if (wrt == macho_tlvp_sect && fmt.ptrsize == 8) {
695 reltype = RL_TLV;
696 } else {
697 nasm_error(ERR_NONFATAL, "Mach-O format does not support"
698 " this use of WRT");
699 /* continue with RL_REL */
700 }
701
702 addr += add_reloc(s, section, offset, reltype,
703 type == OUT_REL4ADR ? 4 : 8);
704 WRITELONG(p, addr);
705 sect_write(s, mydata, type == OUT_REL4ADR ? 4 : 8);
706 break;
707
708 default:
709 nasm_error(ERR_NONFATAL, "Unrepresentable relocation in Mach-O");
710 break;
711 }
712 }
713
714 #define S_CODE (S_REGULAR | S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS)
715 #define NO_TYPE S_NASM_TYPE_MASK
716
717 /* Translation table from traditional Unix section names to Mach-O */
718 static const struct macho_known_section {
719 const char *nasmsect;
720 const char *segname;
721 const char *sectname;
722 const uint32_t flags;
723 } known_sections[] = {
724 { ".text", "__TEXT", "__text", S_CODE },
725 { ".data", "__DATA", "__data", S_REGULAR },
726 { ".rodata", "__DATA", "__const", S_REGULAR },
727 { ".bss", "__DATA", "__bss", S_ZEROFILL },
728 { ".debug_abbrev", "__DWARF", "__debug_abbrev", S_ATTR_DEBUG },
729 { ".debug_info", "__DWARF", "__debug_info", S_ATTR_DEBUG },
730 { ".debug_line", "__DWARF", "__debug_line", S_ATTR_DEBUG },
731 { ".debug_str", "__DWARF", "__debug_str", S_ATTR_DEBUG },
732 };
733
734 /* Section type or attribute directives */
735 static const struct macho_known_section_attr {
736 const char *name;
737 uint32_t flags;
738 } sect_attribs[] = {
739 { "data", S_REGULAR },
740 { "code", S_CODE },
741 { "mixed", S_REGULAR | S_ATTR_SOME_INSTRUCTIONS },
742 { "bss", S_ZEROFILL },
743 { "zerofill", S_ZEROFILL },
744 { "no_dead_strip", NO_TYPE | S_ATTR_NO_DEAD_STRIP },
745 { "live_support", NO_TYPE | S_ATTR_LIVE_SUPPORT },
746 { "strip_static_syms", NO_TYPE | S_ATTR_STRIP_STATIC_SYMS },
747 { "debug", NO_TYPE | S_ATTR_DEBUG },
748 { NULL, 0 }
749 };
750
751 static const struct macho_known_section *
752 lookup_known_section(const char *name, bool by_sectname)
753 {
754 size_t i;
755
756 if (name && name[0]) {
757 for (i = 0; i < ARRAY_SIZE(known_sections); i++) {
758 const char *p = by_sectname ?
759 known_sections[i].sectname :
760 known_sections[i].nasmsect;
761 if (!strcmp(name, p))
762 return &known_sections[i];
763 }
764 }
765
766 return NULL;
767 }
768
769 static int32_t macho_section(char *name, int *bits)
770 {
771 const struct macho_known_section *known_section;
772 const struct macho_known_section_attr *sa;
773 char *sectionAttributes;
774 struct section *s;
775 const char *section, *segment;
776 uint32_t flags;
777 char *currentAttribute;
778 char *comma;
779
780 bool new_seg;
781
782 /* Default to the appropriate number of bits. */
783 if (!name) {
784 *bits = fmt.ptrsize << 3;
785 name = ".text";
786 sectionAttributes = NULL;
787 } else {
788 sectionAttributes = name;
789 name = nasm_strsep(&sectionAttributes, " \t");
790 }
791
792 section = segment = NULL;
793 flags = 0;
794
795 comma = strchr(name, ',');
796 if (comma) {
797 int len;
798
799 *comma = '\0';
800 segment = name;
801 section = comma+1;
802
803 len = strlen(segment);
804 if (len == 0) {
805 nasm_error(ERR_NONFATAL, "empty segment name\n");
806 } else if (len > 16) {
807 nasm_error(ERR_NONFATAL, "segment name %s too long\n", segment);
808 }
809
810 len = strlen(section);
811 if (len == 0) {
812 nasm_error(ERR_NONFATAL, "empty section name\n");
813 } else if (len > 16) {
814 nasm_error(ERR_NONFATAL, "section name %s too long\n", section);
815 }
816
817 known_section = lookup_known_section(section, true);
818 if (known_section)
819 flags = known_section->flags;
820 else
821 flags = S_REGULAR;
822 } else {
823 known_section = lookup_known_section(name, false);
824 if (!known_section) {
825 nasm_error(ERR_NONFATAL, "unknown section name %s\n", name);
826 return NO_SEG;
827 }
828
829 segment = known_section->segname;
830 section = known_section->sectname;
831 flags = known_section->flags;
832 }
833
834 /* try to find section with that name, or create it */
835 s = find_or_add_section(segment, section);
836 new_seg = is_new_section(s);
837
838 /* initialize it if it is a brand new section */
839 if (new_seg) {
840 *sectstail = s;
841 sectstail = &s->next;
842
843 s->data = saa_init(1L);
844 s->fileindex = ++seg_nsects;
845 s->align = -1;
846 s->pad = -1;
847 s->offset = -1;
848 s->by_name = false;
849
850 s->size = 0;
851 s->nreloc = 0;
852 s->flags = flags;
853 }
854
855 if (comma)
856 *comma = ','; /* Restore comma */
857
858 s->by_name = s->by_name || comma; /* Was specified by name */
859
860 flags = NO_TYPE;
861
862 while (sectionAttributes &&
863 (currentAttribute = nasm_strsep(&sectionAttributes, " \t"))) {
864 if (!*currentAttribute)
865 continue;
866
867 if (!nasm_strnicmp("align=", currentAttribute, 6)) {
868 char *end;
869 int newAlignment, value;
870
871 value = strtoul(currentAttribute + 6, (char**)&end, 0);
872 newAlignment = alignlog2_32(value);
873
874 if (0 != *end) {
875 nasm_error(ERR_NONFATAL,
876 "unknown or missing alignment value \"%s\" "
877 "specified for section \"%s\"",
878 currentAttribute + 6,
879 name);
880 } else if (0 > newAlignment) {
881 nasm_error(ERR_NONFATAL,
882 "alignment of %d (for section \"%s\") is not "
883 "a power of two",
884 value,
885 name);
886 }
887
888 if (s->align < newAlignment)
889 s->align = newAlignment;
890 } else {
891 for (sa = sect_attribs; sa->name; sa++) {
892 if (!nasm_stricmp(sa->name, currentAttribute)) {
893 if ((sa->flags & S_NASM_TYPE_MASK) != NO_TYPE) {
894 flags = (flags & ~S_NASM_TYPE_MASK)
895 | (sa->flags & S_NASM_TYPE_MASK);
896 }
897 flags |= sa->flags & ~S_NASM_TYPE_MASK;
898 break;
899 }
900 }
901
902 if (!sa->name) {
903 nasm_error(ERR_NONFATAL,
904 "unknown section attribute %s for section %s",
905 currentAttribute, name);
906 }
907 }
908 }
909
910 if ((flags & S_NASM_TYPE_MASK) != NO_TYPE) {
911 if (!new_seg && ((s->flags ^ flags) & S_NASM_TYPE_MASK)) {
912 nasm_error(ERR_NONFATAL,
913 "inconsistent section attributes for section %s\n",
914 name);
915 } else {
916 s->flags = (s->flags & ~S_NASM_TYPE_MASK) | flags;
917 }
918 } else {
919 s->flags |= flags & ~S_NASM_TYPE_MASK;
920 }
921
922 return s->subsection;
923 }
924
925 static int32_t macho_herelabel(const char *name, enum label_type type,
926 int32_t section, int32_t *subsection,
927 bool *copyoffset)
928 {
929 struct section *s;
930 int32_t subsec;
931 (void)name;
932
933 if (!(head_flags & MH_SUBSECTIONS_VIA_SYMBOLS))
934 return section;
935
936 /* No subsection only for local labels */
937 if (type == LBL_LOCAL)
938 return section;
939
940 s = get_section_by_index(section);
941 if (!s)
942 return section;
943
944 subsec = *subsection;
945 if (subsec == NO_SEG) {
946 /* Allocate a new subsection index */
947 subsec = *subsection = seg_alloc();
948 section_by_index = raa_write_ptr(section_by_index, subsec >> 1, s);
949 }
950
951 s->subsection = subsec;
952 *copyoffset = true; /* Maintain previous offset */
953 return subsec;
954 }
955
956 static void macho_symdef(char *name, int32_t section, int64_t offset,
957 int is_global, char *special)
958 {
959 struct symbol *sym;
960 struct section *s;
961 bool special_used = false;
962
963 #if defined(DEBUG) && DEBUG>2
964 nasm_error(ERR_DEBUG,
965 " macho_symdef: %s, pass=%"PRId64" type %s, sec=%"PRIx32", off=%"PRIx64", is_global=%d, %s\n",
966 name, pass_count(), pass_types[pass_type()],
967 section, offset, is_global, special);
968 #endif
969
970 if (is_global == 3) {
971 if (special) {
972 int n = strcspn(special, " \t");
973
974 if (!nasm_strnicmp(special, "private_extern", n)) {
975 for (sym = syms; sym != NULL; sym = sym->next) {
976 if (!strcmp(name, sym->name)) {
977 if (sym->type & N_PEXT)
978 return; /* nothing to be done */
979 else
980 break;
981 }
982 }
983 }
984 }
985 nasm_error(ERR_NONFATAL, "The Mach-O format does not "
986 "(yet) support forward reference fixups.");
987 return;
988 }
989
990 if (name[0] == '.' && name[1] == '.' && name[2] != '@') {
991 /*
992 * This is a NASM special symbol. We never allow it into
993 * the Macho-O symbol table, even if it's a valid one. If it
994 * _isn't_ a valid one, we should barf immediately.
995 */
996 if (strcmp(name, "..gotpcrel") && strcmp(name, "..tlvp"))
997 nasm_error(ERR_NONFATAL, "unrecognized special symbol `%s'", name);
998 return;
999 }
1000
1001 sym = *symstail = nasm_zalloc(sizeof(struct symbol));
1002 sym->next = NULL;
1003 symstail = &sym->next;
1004
1005 sym->name = name;
1006 sym->strx = strslen;
1007 sym->type = 0;
1008 sym->desc = 0;
1009 sym->symv[0].key = offset;
1010 sym->symv[1].key = offset;
1011 sym->initial_snum = -1;
1012
1013 /* external and common symbols get N_EXT */
1014 if (is_global != 0) {
1015 sym->type |= N_EXT;
1016 }
1017 if (is_global == 1) {
1018 /* check special to see if the global symbol shall be marked as private external: N_PEXT */
1019 if (special) {
1020 int n = strcspn(special, " \t");
1021
1022 if (!nasm_strnicmp(special, "private_extern", n))
1023 sym->type |= N_PEXT;
1024 else
1025 nasm_error(ERR_NONFATAL, "unrecognised symbol type `%.*s'", n, special);
1026 }
1027 special_used = true;
1028 }
1029
1030 /* track the initially allocated symbol number for use in future fix-ups */
1031 sym->initial_snum = nsyms;
1032
1033 if (section == NO_SEG) {
1034 /* symbols in no section get absolute */
1035 sym->type |= N_ABS;
1036 sym->sect = NO_SECT;
1037
1038 s = &absolute_sect;
1039 } else {
1040 s = get_section_by_index(section);
1041
1042 sym->type |= N_SECT;
1043
1044 /* get the in-file index of the section the symbol was defined in */
1045 sym->sect = s ? s->fileindex : NO_SECT;
1046
1047 if (!s) {
1048 /* remember symbol number of references to external
1049 ** symbols, this works because every external symbol gets
1050 ** its own section number allocated internally by nasm and
1051 ** can so be used as a key */
1052 extsyms = raa_write(extsyms, section, nsyms);
1053
1054 switch (is_global) {
1055 case 1:
1056 case 2:
1057 /* there isn't actually a difference between global
1058 ** and common symbols, both even have their size in
1059 ** sym->symv[0].key */
1060 sym->type = N_EXT;
1061 break;
1062
1063 default:
1064 /* give an error on unfound section if it's not an
1065 ** external or common symbol (assemble_file() does a
1066 ** seg_alloc() on every call for them) */
1067 nasm_panic("in-file index for section %"PRId32" not found, "
1068 "is_global = %d", section, is_global);
1069 break;
1070 }
1071 }
1072 }
1073
1074 if (s) {
1075 s->syms[0] = rb_insert(s->syms[0], &sym->symv[0]);
1076 if (is_global)
1077 s->syms[1] = rb_insert(s->syms[1], &sym->symv[1]);
1078 }
1079
1080 ++nsyms;
1081
1082 if (special && !special_used)
1083 nasm_error(ERR_NONFATAL, "no special symbol features supported here");
1084 }
1085
1086 static void macho_sectalign(int32_t seg, unsigned int value)
1087 {
1088 struct section *s;
1089 int align;
1090
1091 nasm_assert(!(seg & 1));
1092
1093 s = get_section_by_index(seg);
1094
1095 if (!s || !is_power2(value))
1096 return;
1097
1098 align = alignlog2_32(value);
1099 if (s->align < align)
1100 s->align = align;
1101 }
1102
1103 extern macros_t macho_stdmac[];
1104
1105 /* Comparison function for qsort symbol layout. */
1106 static int layout_compare (const struct symbol **s1,
1107 const struct symbol **s2)
1108 {
1109 return strcmp ((*s1)->name, (*s2)->name);
1110 }
1111
1112 /* The native assembler does a few things in a similar function
1113
1114 * Remove temporary labels
1115 * Sort symbols according to local, external, undefined (by name)
1116 * Order the string table
1117
1118 We do not remove temporary labels right now.
1119
1120 numsyms is the total number of symbols we have. strtabsize is the
1121 number entries in the string table. */
1122
1123 static void macho_layout_symbols (uint32_t *numsyms,
1124 uint32_t *strtabsize)
1125 {
1126 struct symbol *sym, **symp;
1127 uint32_t i,j;
1128
1129 *numsyms = 0;
1130 *strtabsize = sizeof (char);
1131
1132 symp = &syms;
1133
1134 while ((sym = *symp)) {
1135 /* Undefined symbols are now external. */
1136 if (sym->type == N_UNDF)
1137 sym->type |= N_EXT;
1138
1139 if ((sym->type & N_EXT) == 0) {
1140 sym->snum = *numsyms;
1141 *numsyms = *numsyms + 1;
1142 nlocalsym++;
1143 }
1144 else {
1145 if ((sym->type & N_TYPE) != N_UNDF) {
1146 nextdefsym++;
1147 } else {
1148 nundefsym++;
1149 }
1150
1151 /* If we handle debug info we'll want
1152 to check for it here instead of just
1153 adding the symbol to the string table. */
1154 sym->strx = *strtabsize;
1155 saa_wbytes (strs, sym->name, (int32_t)(strlen(sym->name) + 1));
1156 *strtabsize += strlen(sym->name) + 1;
1157 }
1158 symp = &(sym->next);
1159 }
1160
1161 /* Next, sort the symbols. Most of this code is a direct translation from
1162 the Apple cctools symbol layout. We need to keep compatibility with that. */
1163 /* Set the indexes for symbol groups into the symbol table */
1164 ilocalsym = 0;
1165 iextdefsym = nlocalsym;
1166 iundefsym = nlocalsym + nextdefsym;
1167
1168 /* allocate arrays for sorting externals by name */
1169 extdefsyms = nasm_malloc(nextdefsym * sizeof(struct symbol *));
1170 undefsyms = nasm_malloc(nundefsym * sizeof(struct symbol *));
1171
1172 i = 0;
1173 j = 0;
1174
1175 symp = &syms;
1176
1177 while ((sym = *symp)) {
1178
1179 if((sym->type & N_EXT) == 0) {
1180 sym->strx = *strtabsize;
1181 saa_wbytes (strs, sym->name, (int32_t)(strlen (sym->name) + 1));
1182 *strtabsize += strlen(sym->name) + 1;
1183 }
1184 else {
1185 if ((sym->type & N_TYPE) != N_UNDF) {
1186 extdefsyms[i++] = sym;
1187 } else {
1188 undefsyms[j++] = sym;
1189 }
1190 }
1191 symp = &(sym->next);
1192 }
1193
1194 qsort(extdefsyms, nextdefsym, sizeof(struct symbol *),
1195 (int (*)(const void *, const void *))layout_compare);
1196 qsort(undefsyms, nundefsym, sizeof(struct symbol *),
1197 (int (*)(const void *, const void *))layout_compare);
1198
1199 for(i = 0; i < nextdefsym; i++) {
1200 extdefsyms[i]->snum = *numsyms;
1201 *numsyms += 1;
1202 }
1203 for(j = 0; j < nundefsym; j++) {
1204 undefsyms[j]->snum = *numsyms;
1205 *numsyms += 1;
1206 }
1207 }
1208
1209 /* Calculate some values we'll need for writing later. */
1210
1211 static void macho_calculate_sizes (void)
1212 {
1213 struct section *s;
1214 int fi;
1215
1216 /* count sections and calculate in-memory and in-file offsets */
1217 for (s = sects; s != NULL; s = s->next) {
1218 uint64_t newaddr;
1219
1220 /* recalculate segment address based on alignment and vm size */
1221 s->addr = seg_vmsize;
1222
1223 /* we need section alignment to calculate final section address */
1224 if (s->align == -1)
1225 s->align = DEFAULT_SECTION_ALIGNMENT;
1226
1227 newaddr = ALIGN(s->addr, UINT64_C(1) << s->align);
1228 s->addr = newaddr;
1229
1230 seg_vmsize = newaddr + s->size;
1231
1232 /* zerofill sections aren't actually written to the file */
1233 if ((s->flags & SECTION_TYPE) != S_ZEROFILL) {
1234 /*
1235 * LLVM/Xcode as always aligns the section data to 4
1236 * bytes; there is a comment in the LLVM source code that
1237 * perhaps aligning to pointer size would be better.
1238 */
1239 s->pad = ALIGN(seg_filesize, 4) - seg_filesize;
1240 s->offset = seg_filesize + s->pad;
1241 seg_filesize += s->size + s->pad;
1242
1243 /* filesize and vmsize needs to be aligned */
1244 seg_vmsize += s->pad;
1245 }
1246 }
1247
1248 /* calculate size of all headers, load commands and sections to
1249 ** get a pointer to the start of all the raw data */
1250 if (buildver_platform != PLATFORM_UNKNOWN) {
1251 ++head_ncmds;
1252 head_sizeofcmds += MACHO_BUILD_VERSION_SIZE;
1253 }
1254
1255 if (seg_nsects > 0) {
1256 ++head_ncmds;
1257 head_sizeofcmds += fmt.segcmd_size + seg_nsects * fmt.sectcmd_size;
1258 }
1259
1260 if (nsyms > 0) {
1261 ++head_ncmds;
1262 head_sizeofcmds += MACHO_SYMCMD_SIZE;
1263 }
1264
1265 if (seg_nsects > MAX_SECT) {
1266 nasm_fatal("MachO output is limited to %d sections\n",
1267 MAX_SECT);
1268 }
1269
1270 /* Create a table of sections by file index to avoid linear search */
1271 sectstab = nasm_malloc((seg_nsects + 1) * sizeof(*sectstab));
1272 sectstab[NO_SECT] = &absolute_sect;
1273 for (s = sects, fi = 1; s != NULL; s = s->next, fi++)
1274 sectstab[fi] = s;
1275 }
1276
1277 /* Write out the header information for the file. */
1278
1279 static void macho_write_header (void)
1280 {
1281 fwriteint32_t(fmt.mh_magic, ofile); /* magic */
1282 fwriteint32_t(fmt.cpu_type, ofile); /* CPU type */
1283 fwriteint32_t(CPU_SUBTYPE_I386_ALL, ofile); /* CPU subtype */
1284 fwriteint32_t(MH_OBJECT, ofile); /* Mach-O file type */
1285 fwriteint32_t(head_ncmds, ofile); /* number of load commands */
1286 fwriteint32_t(head_sizeofcmds, ofile); /* size of load commands */
1287 fwriteint32_t(head_flags, ofile); /* flags, if any */
1288 fwritezero(fmt.header_size - 7*4, ofile); /* reserved fields */
1289 }
1290
1291 /* Write out the segment load command at offset. */
1292
1293 static uint32_t macho_write_segment (uint64_t offset)
1294 {
1295 uint64_t rel_base = alignptr(offset + seg_filesize);
1296 uint32_t s_reloff = 0;
1297 struct section *s;
1298
1299 fwriteint32_t(fmt.lc_segment, ofile); /* cmd == LC_SEGMENT_64 */
1300
1301 /* size of load command including section load commands */
1302 fwriteint32_t(fmt.segcmd_size + seg_nsects * fmt.sectcmd_size,
1303 ofile);
1304
1305 /* in an MH_OBJECT file all sections are in one unnamed (name
1306 ** all zeros) segment */
1307 fwritezero(16, ofile);
1308 fwriteptr(0, ofile); /* in-memory offset */
1309 fwriteptr(seg_vmsize, ofile); /* in-memory size */
1310 fwriteptr(offset, ofile); /* in-file offset to data */
1311 fwriteptr(seg_filesize, ofile); /* in-file size */
1312 fwriteint32_t(VM_PROT_DEFAULT, ofile); /* maximum vm protection */
1313 fwriteint32_t(VM_PROT_DEFAULT, ofile); /* initial vm protection */
1314 fwriteint32_t(seg_nsects, ofile); /* number of sections */
1315 fwriteint32_t(0, ofile); /* no flags */
1316
1317 /* emit section headers */
1318 for (s = sects; s != NULL; s = s->next) {
1319 if (s->nreloc) {
1320 nasm_assert((s->flags & SECTION_TYPE) != S_ZEROFILL);
1321 s->flags |= S_ATTR_LOC_RELOC;
1322 if (s->extreloc)
1323 s->flags |= S_ATTR_EXT_RELOC;
1324 } else if (!xstrncmp(s->segname, "__DATA") &&
1325 !xstrncmp(s->sectname, "__const") &&
1326 !s->by_name &&
1327 !get_section_by_name("__TEXT", "__const")) {
1328 /*
1329 * The MachO equivalent to .rodata can be either
1330 * __DATA,__const or __TEXT,__const; the latter only if
1331 * there are no relocations. However, when mixed it is
1332 * better to specify the segments explicitly.
1333 */
1334 xstrncpy(s->segname, "__TEXT");
1335 }
1336
1337 nasm_write(s->sectname, sizeof(s->sectname), ofile);
1338 nasm_write(s->segname, sizeof(s->segname), ofile);
1339 fwriteptr(s->addr, ofile);
1340 fwriteptr(s->size, ofile);
1341
1342 /* dummy data for zerofill sections or proper values */
1343 if ((s->flags & SECTION_TYPE) != S_ZEROFILL) {
1344 nasm_assert(s->pad != (uint32_t)-1);
1345 offset += s->pad;
1346 fwriteint32_t(offset, ofile);
1347 offset += s->size;
1348 /* Write out section alignment, as a power of two.
1349 e.g. 32-bit word alignment would be 2 (2^2 = 4). */
1350 fwriteint32_t(s->align, ofile);
1351 /* To be compatible with cctools as we emit
1352 a zero reloff if we have no relocations. */
1353 fwriteint32_t(s->nreloc ? rel_base + s_reloff : 0, ofile);
1354 fwriteint32_t(s->nreloc, ofile);
1355
1356 s_reloff += s->nreloc * MACHO_RELINFO_SIZE;
1357 } else {
1358 fwriteint32_t(0, ofile);
1359 fwriteint32_t(s->align, ofile);
1360 fwriteint32_t(0, ofile);
1361 fwriteint32_t(0, ofile);
1362 }
1363
1364 fwriteint32_t(s->flags, ofile); /* flags */
1365 fwriteint32_t(0, ofile); /* reserved */
1366 fwriteptr(0, ofile); /* reserved */
1367 }
1368
1369 rel_padcnt = rel_base - offset;
1370 offset = rel_base + s_reloff;
1371
1372 return offset;
1373 }
1374
1375 /* For a given chain of relocs r, write out the entire relocation
1376 chain to the object file. */
1377
1378 static void macho_write_relocs (struct reloc *r)
1379 {
1380 while (r) {
1381 uint32_t word2;
1382
1383 fwriteint32_t(r->addr, ofile); /* reloc offset */
1384
1385 word2 = r->snum;
1386 word2 |= r->pcrel << 24;
1387 word2 |= r->length << 25;
1388 word2 |= r->ext << 27;
1389 word2 |= r->type << 28;
1390 fwriteint32_t(word2, ofile); /* reloc data */
1391 r = r->next;
1392 }
1393 }
1394
1395 /* Write out the section data. */
1396 static void macho_write_section (void)
1397 {
1398 struct section *s;
1399 struct reloc *r;
1400 uint8_t *p;
1401 int32_t len;
1402 int64_t l;
1403 union offset {
1404 uint64_t val;
1405 uint8_t buf[8];
1406 } blk;
1407
1408 for (s = sects; s != NULL; s = s->next) {
1409 if ((s->flags & SECTION_TYPE) == S_ZEROFILL)
1410 continue;
1411
1412 /* Like a.out Mach-O references things in the data or bss
1413 * sections by addresses which are actually relative to the
1414 * start of the _text_ section, in the _file_. See outaout.c
1415 * for more information. */
1416 saa_rewind(s->data);
1417 for (r = s->relocs; r != NULL; r = r->next) {
1418 len = (uint32_t)1 << r->length;
1419 if (len > 4) /* Can this ever be an issue?! */
1420 len = 8;
1421 blk.val = 0;
1422 saa_fread(s->data, r->addr, blk.buf, len);
1423
1424 /* get offset based on relocation type */
1425 #ifdef WORDS_LITTLEENDIAN
1426 l = blk.val;
1427 #else
1428 l = blk.buf[0];
1429 l += ((int64_t)blk.buf[1]) << 8;
1430 l += ((int64_t)blk.buf[2]) << 16;
1431 l += ((int64_t)blk.buf[3]) << 24;
1432 l += ((int64_t)blk.buf[4]) << 32;
1433 l += ((int64_t)blk.buf[5]) << 40;
1434 l += ((int64_t)blk.buf[6]) << 48;
1435 l += ((int64_t)blk.buf[7]) << 56;
1436 #endif
1437
1438 /* If the relocation is internal add to the current section
1439 offset. Otherwise the only value we need is the symbol
1440 offset which we already have. The linker takes care
1441 of the rest of the address. */
1442 if (!r->ext) {
1443 /* generate final address by section address and offset */
1444 nasm_assert(r->snum <= seg_nsects);
1445 l += sectstab[r->snum]->addr;
1446 if (r->pcrel)
1447 l -= s->addr;
1448 } else if (r->pcrel && r->type == GENERIC_RELOC_VANILLA) {
1449 l -= s->addr;
1450 }
1451
1452 /* write new offset back */
1453 p = blk.buf;
1454 WRITEDLONG(p, l);
1455 saa_fwrite(s->data, r->addr, blk.buf, len);
1456 }
1457
1458 /* dump the section data to file */
1459 fwritezero(s->pad, ofile);
1460 saa_fpwrite(s->data, ofile);
1461 }
1462
1463 /* pad last section up to reloc entries on pointer boundary */
1464 fwritezero(rel_padcnt, ofile);
1465
1466 /* emit relocation entries */
1467 for (s = sects; s != NULL; s = s->next)
1468 macho_write_relocs (s->relocs);
1469 }
1470
1471 /* Write out the symbol table. We should already have sorted this
1472 before now. */
1473 static void macho_write_symtab (void)
1474 {
1475 struct symbol *sym;
1476 uint64_t i;
1477
1478 /* we don't need to pad here since MACHO_RELINFO_SIZE == 8 */
1479
1480 for (sym = syms; sym != NULL; sym = sym->next) {
1481 if ((sym->type & N_EXT) == 0) {
1482 fwriteint32_t(sym->strx, ofile); /* string table entry number */
1483 nasm_write(&sym->type, 1, ofile); /* symbol type */
1484 nasm_write(&sym->sect, 1, ofile); /* section */
1485 fwriteint16_t(sym->desc, ofile); /* description */
1486
1487 /* Fix up the symbol value now that we know the final section
1488 sizes. */
1489 if (((sym->type & N_TYPE) == N_SECT) && (sym->sect != NO_SECT)) {
1490 nasm_assert(sym->sect <= seg_nsects);
1491 sym->symv[0].key += sectstab[sym->sect]->addr;
1492 }
1493
1494 fwriteptr(sym->symv[0].key, ofile); /* value (i.e. offset) */
1495 }
1496 }
1497
1498 for (i = 0; i < nextdefsym; i++) {
1499 sym = extdefsyms[i];
1500 fwriteint32_t(sym->strx, ofile);
1501 nasm_write(&sym->type, 1, ofile); /* symbol type */
1502 nasm_write(&sym->sect, 1, ofile); /* section */
1503 fwriteint16_t(sym->desc, ofile); /* description */
1504
1505 /* Fix up the symbol value now that we know the final section
1506 sizes. */
1507 if (((sym->type & N_TYPE) == N_SECT) && (sym->sect != NO_SECT)) {
1508 nasm_assert(sym->sect <= seg_nsects);
1509 sym->symv[0].key += sectstab[sym->sect]->addr;
1510 }
1511
1512 fwriteptr(sym->symv[0].key, ofile); /* value (i.e. offset) */
1513 }
1514
1515 for (i = 0; i < nundefsym; i++) {
1516 sym = undefsyms[i];
1517 fwriteint32_t(sym->strx, ofile);
1518 nasm_write(&sym->type, 1, ofile); /* symbol type */
1519 nasm_write(&sym->sect, 1, ofile); /* section */
1520 fwriteint16_t(sym->desc, ofile); /* description */
1521
1522 /* Fix up the symbol value now that we know the final section
1523 sizes. */
1524 if (((sym->type & N_TYPE) == N_SECT) && (sym->sect != NO_SECT)) {
1525 nasm_assert(sym->sect <= seg_nsects);
1526 sym->symv[0].key += sectstab[sym->sect]->addr;
1527 }
1528
1529 fwriteptr(sym->symv[0].key, ofile); /* value (i.e. offset) */
1530 }
1531
1532 }
1533
1534 /* Fixup the snum in the relocation entries, we should be
1535 doing this only for externally referenced symbols. */
1536 static void macho_fixup_relocs (struct reloc *r)
1537 {
1538 struct symbol *sym;
1539
1540 while (r != NULL) {
1541 if (r->ext) {
1542 for (sym = syms; sym != NULL; sym = sym->next) {
1543 if (sym->initial_snum == r->snum) {
1544 r->snum = sym->snum;
1545 break;
1546 }
1547 }
1548 }
1549 r = r->next;
1550 }
1551 }
1552
1553 /* Write out the object file. */
1554
1555 static void macho_write (void)
1556 {
1557 uint64_t offset = 0;
1558
1559 /* mach-o object file structure:
1560 **
1561 ** mach header
1562 ** uint32_t magic
1563 ** int cpu type
1564 ** int cpu subtype
1565 ** uint32_t mach file type
1566 ** uint32_t number of load commands
1567 ** uint32_t size of all load commands
1568 ** (includes section struct size of segment command)
1569 ** uint32_t flags
1570 **
1571 ** segment command
1572 ** uint32_t command type == LC_SEGMENT[_64]
1573 ** uint32_t size of load command
1574 ** (including section load commands)
1575 ** char[16] segment name
1576 ** pointer in-memory offset
1577 ** pointer in-memory size
1578 ** pointer in-file offset to data area
1579 ** pointer in-file size
1580 ** (in-memory size excluding zerofill sections)
1581 ** int maximum vm protection
1582 ** int initial vm protection
1583 ** uint32_t number of sections
1584 ** uint32_t flags
1585 **
1586 ** section commands
1587 ** char[16] section name
1588 ** char[16] segment name
1589 ** pointer in-memory offset
1590 ** pointer in-memory size
1591 ** uint32_t in-file offset
1592 ** uint32_t alignment
1593 ** (irrelevant in MH_OBJECT)
1594 ** uint32_t in-file offset of relocation entries
1595 ** uint32_t number of relocations
1596 ** uint32_t flags
1597 ** uint32_t reserved
1598 ** uint32_t reserved
1599 **
1600 ** symbol table command
1601 ** uint32_t command type == LC_SYMTAB
1602 ** uint32_t size of load command
1603 ** uint32_t symbol table offset
1604 ** uint32_t number of symbol table entries
1605 ** uint32_t string table offset
1606 ** uint32_t string table size
1607 **
1608 ** raw section data
1609 **
1610 ** padding to pointer boundary
1611 **
1612 ** relocation data (struct reloc)
1613 ** int32_t offset
1614 ** uint data (symbolnum, pcrel, length, extern, type)
1615 **
1616 ** symbol table data (struct nlist)
1617 ** int32_t string table entry number
1618 ** uint8_t type
1619 ** (extern, absolute, defined in section)
1620 ** uint8_t section
1621 ** (0 for global symbols, section number of definition (>= 1, <=
1622 ** 254) for local symbols, size of variable for common symbols
1623 ** [type == extern])
1624 ** int16_t description
1625 ** (for stab debugging format)
1626 ** pointer value (i.e. file offset) of symbol or stab offset
1627 **
1628 ** string table data
1629 ** list of null-terminated strings
1630 */
1631
1632 /* Emit the Mach-O header. */
1633 macho_write_header();
1634
1635 offset = fmt.header_size + head_sizeofcmds;
1636
1637 /* emit the build_version command early, if desired */
1638 if (buildver_platform != PLATFORM_UNKNOWN) {
1639 fwriteint32_t(LC_BUILD_VERSION, ofile); /* cmd == LC_BUILD_VERSION */
1640 fwriteint32_t(MACHO_BUILD_VERSION_SIZE, ofile); /* size of load command */
1641 fwriteint32_t(buildver_platform, ofile); /* platform */
1642 fwriteint32_t(buildver_minos, ofile); /* minos */
1643 fwriteint32_t(buildver_sdk, ofile); /* sdk */
1644 fwriteint32_t(0, ofile); /* ntools */
1645 }
1646
1647 /* emit the segment load command */
1648 if (seg_nsects > 0)
1649 offset = macho_write_segment (offset);
1650 else
1651 nasm_warn(WARN_OTHER, "no sections?");
1652
1653 if (nsyms > 0) {
1654 /* write out symbol command */
1655 fwriteint32_t(LC_SYMTAB, ofile); /* cmd == LC_SYMTAB */
1656 fwriteint32_t(MACHO_SYMCMD_SIZE, ofile); /* size of load command */
1657 fwriteint32_t(offset, ofile); /* symbol table offset */
1658 fwriteint32_t(nsyms, ofile); /* number of symbol
1659 ** table entries */
1660 offset += nsyms * fmt.nlist_size;
1661 fwriteint32_t(offset, ofile); /* string table offset */
1662 fwriteint32_t(strslen, ofile); /* string table size */
1663 }
1664
1665 /* emit section data */
1666 if (seg_nsects > 0)
1667 macho_write_section ();
1668
1669 /* emit symbol table if we have symbols */
1670 if (nsyms > 0)
1671 macho_write_symtab ();
1672
1673 /* we don't need to pad here, we are already aligned */
1674
1675 /* emit string table */
1676 saa_fpwrite(strs, ofile);
1677 }
1678 /* We do quite a bit here, starting with finalizing all of the data
1679 for the object file, writing, and then freeing all of the data from
1680 the file. */
1681
1682 static void macho_cleanup(void)
1683 {
1684 struct section *s;
1685 struct reloc *r;
1686 struct symbol *sym;
1687
1688 dfmt->cleanup();
1689
1690 /* Sort all symbols. */
1691 macho_layout_symbols (&nsyms, &strslen);
1692
1693 /* Fixup relocation entries */
1694 for (s = sects; s != NULL; s = s->next) {
1695 macho_fixup_relocs (s->relocs);
1696 }
1697
1698 /* First calculate and finalize needed values. */
1699 macho_calculate_sizes();
1700 macho_write();
1701
1702 /* free up everything */
1703 while (sects->next) {
1704 s = sects;
1705 sects = sects->next;
1706
1707 saa_free(s->data);
1708 while (s->relocs != NULL) {
1709 r = s->relocs;
1710 s->relocs = s->relocs->next;
1711 nasm_free(r);
1712 }
1713
1714 nasm_free(s);
1715 }
1716
1717 saa_free(strs);
1718
1719 raa_free(extsyms);
1720
1721 while (syms) {
1722 sym = syms;
1723 syms = syms->next;
1724 nasm_free (sym);
1725 }
1726
1727 nasm_free(extdefsyms);
1728 nasm_free(undefsyms);
1729 nasm_free(sectstab);
1730 raa_free(section_by_index);
1731 hash_free(&section_by_name);
1732 }
1733
1734 static bool macho_set_section_attribute_by_symbol(const char *label, uint32_t flags)
1735 {
1736 struct section *s;
1737 int32_t nasm_seg;
1738 int64_t offset;
1739
1740 if (lookup_label(label, &nasm_seg, &offset) == LBL_none) {
1741 nasm_error(ERR_NONFATAL, "unknown symbol `%s' in no_dead_strip", label);
1742 return false;
1743 }
1744
1745 s = get_section_by_index(nasm_seg);
1746 if (!s) {
1747 nasm_error(ERR_NONFATAL, "symbol `%s' is external or absolute", label);
1748 return false;
1749 }
1750
1751 s->flags |= flags;
1752 return true;
1753 }
1754
1755 /*
1756 * Mark a symbol for no dead stripping
1757 */
1758 static enum directive_result macho_no_dead_strip(const char *labels)
1759 {
1760 char *s, *p, *ep;
1761 char ec;
1762 enum directive_result rv = DIRR_ERROR;
1763
1764 p = s = nasm_strdup(labels);
1765 while (*p) {
1766 ep = nasm_skip_identifier(p);
1767 if (!ep) {
1768 nasm_error(ERR_NONFATAL, "invalid symbol in NO_DEAD_STRIP");
1769 goto err;
1770 }
1771 ec = *ep;
1772 if (ec && ec != ',' && !nasm_isspace(ec)) {
1773 nasm_error(ERR_NONFATAL, "cannot parse contents after symbol");
1774 goto err;
1775 }
1776 *ep = '\0';
1777 if (!pass_first()) {
1778 if (!macho_set_section_attribute_by_symbol(p, S_ATTR_NO_DEAD_STRIP))
1779 rv = DIRR_ERROR;
1780 }
1781 *ep = ec;
1782 p = nasm_skip_spaces(ep);
1783 if (*p == ',')
1784 p = nasm_skip_spaces(++p);
1785 }
1786
1787 rv = DIRR_OK;
1788
1789 err:
1790 nasm_free(s);
1791 return rv;
1792 }
1793
1794 static bool macho_match_string(const char **pp, const char *target_name)
1795 {
1796 const char *p = *pp;
1797 while (*target_name) {
1798 if (*p++ != *target_name++)
1799 return false;
1800 }
1801
1802 /* must have exhausted the run of identifier characters */
1803 if (nasm_isidchar(*p)) {
1804 return false;
1805 }
1806
1807 *pp = p;
1808 return true;
1809 }
1810
1811 static bool macho_scan_number(const char **pp, int64_t *result)
1812 {
1813 bool error = false;
1814 const char *p = *pp;
1815 while (nasm_isdigit(*p))
1816 ++p;
1817
1818 if (p == *pp) {
1819 *result = 0;
1820 return false;
1821 }
1822
1823 *result = readnum(*pp, &error);
1824 *pp = p;
1825 return !error;
1826 }
1827
1828 static bool macho_scan_version(const char **pp, uint32_t *result)
1829 {
1830 int64_t major = 0;
1831 int64_t minor = 0;
1832 int64_t trailing = 0;
1833
1834 /* version: major, minor (, trailing)? */
1835 *result = 0;
1836
1837 if (!macho_scan_number(pp, &major) || major < 0 || major > 65535)
1838 return false;
1839 *pp = nasm_skip_spaces(*pp);
1840 if (**pp != ',') /* comma after major ver is required */
1841 return false;
1842 *pp = nasm_skip_spaces(*pp + 1);
1843
1844 if (!macho_scan_number(pp, &minor) || minor < 0 || minor > 255)
1845 return false;
1846 *pp = nasm_skip_spaces(*pp);
1847
1848 if (**pp == ',') {
1849 /* trailing version present */
1850 *pp = nasm_skip_spaces(*pp + 1);
1851 if (!macho_scan_number(pp, &trailing) || trailing < 0 || trailing > 255)
1852 return false;
1853 }
1854
1855 *result = (uint32_t) ((major << 16) | (minor << 8) | trailing);
1856 return true;
1857 }
1858
1859 /*
1860 * Specify a build version
1861 */
1862 static enum directive_result macho_build_version(const char *buildversion)
1863 {
1864 /* Matching .build_version directive in LLVM-MC */
1865 const char *p;
1866 uint32_t platform = PLATFORM_UNKNOWN;
1867 uint32_t minos = 0;
1868 uint32_t sdk = 0;
1869
1870 p = nasm_skip_spaces(buildversion);
1871
1872 #define X(_platform,_id,_name) if (macho_match_string(&p, _name)) platform = _platform;
1873 MACHO_ALL_PLATFORMS
1874 #undef X
1875
1876 if (platform == PLATFORM_UNKNOWN) {
1877 nasm_nonfatal("unknown platform name");
1878 return DIRR_ERROR;
1879 }
1880
1881 p = nasm_skip_spaces(p);
1882 if (*p != ',') {
1883 nasm_nonfatal("version number required, comma expected");
1884 return DIRR_ERROR;
1885 }
1886 p = nasm_skip_spaces(p + 1);
1887
1888 if (!macho_scan_version(&p, &minos)) {
1889 nasm_nonfatal("malformed version number");
1890 return DIRR_ERROR;
1891 }
1892
1893 p = nasm_skip_spaces(p);
1894 if (*p) {
1895 if (macho_match_string(&p, "sdk_version")) {
1896 p = nasm_skip_spaces(p);
1897
1898 if (!macho_scan_version(&p, &sdk)) {
1899 nasm_nonfatal("malformed sdk_version");
1900 return DIRR_ERROR;
1901 }
1902 } else
1903 nasm_nonfatal("extra characters in build_version");
1904 }
1905
1906 buildver_platform = platform;
1907 buildver_minos = minos;
1908 buildver_sdk = sdk;
1909 return DIRR_OK;
1910 }
1911
1912 /*
1913 * Mach-O pragmas
1914 */
1915 static enum directive_result
1916 macho_pragma(const struct pragma *pragma)
1917 {
1918 switch (pragma->opcode) {
1919 case D_SUBSECTIONS_VIA_SYMBOLS:
1920 if (*pragma->tail)
1921 return DIRR_BADPARAM;
1922
1923 if (!pass_first())
1924 head_flags |= MH_SUBSECTIONS_VIA_SYMBOLS;
1925
1926 /* Jmp-match optimization conflicts */
1927 optimizing |= OPTIM_DISABLE_JMP_MATCH;
1928
1929 return DIRR_OK;
1930
1931 case D_NO_DEAD_STRIP:
1932 return macho_no_dead_strip(pragma->tail);
1933
1934 case D_unknown:
1935 if (!strcmp(pragma->opname, "build_version"))
1936 return macho_build_version(pragma->tail);
1937
1938 return DIRR_UNKNOWN;
1939
1940 default:
1941 return DIRR_UNKNOWN; /* Not a Mach-O directive */
1942 }
1943 }
1944
1945 static const struct pragma_facility macho_pragma_list[] = {
1946 { "macho", macho_pragma },
1947 { NULL, macho_pragma } /* Implements macho32/macho64 namespaces */
1948 };
1949
1950 static void macho_dbg_generate(void)
1951 {
1952 uint8_t *p_buf = NULL, *p_buf_base = NULL;
1953 size_t saa_len = 0, high_addr = 0, total_len = 0;
1954 struct section *p_section = NULL;
1955 /* calculated at debug_str and referenced at debug_info */
1956 uint32_t producer_str_offset = 0, module_str_offset = 0, dir_str_offset = 0;
1957
1958 /* debug section defines */
1959 {
1960 int bits = 0;
1961 macho_section(".debug_abbrev", &bits);
1962 macho_section(".debug_info", &bits);
1963 macho_section(".debug_line", &bits);
1964 macho_section(".debug_str", &bits);
1965 }
1966
1967 /* dw section walk to find high_addr and total_len */
1968 {
1969 struct dw_sect_list *p_sect;
1970
1971 list_for_each(p_sect, dw_head_sect) {
1972 uint64_t offset = get_section_by_index(p_sect->section)->size;
1973 struct SAA *p_linep = p_sect->psaa;
1974
1975 saa_write8(p_linep, 2); /* std op 2 */
1976 saa_write8(p_linep, offset - p_sect->offset);
1977 saa_write8(p_linep, DW_LNS_extended_op);
1978 saa_write8(p_linep, 1); /* operand length */
1979 saa_write8(p_linep, DW_LNE_end_sequence);
1980
1981 total_len += p_linep->datalen;
1982 high_addr += offset;
1983 }
1984 }
1985
1986 /* debug line */
1987 {
1988 struct dw_sect_list *p_sect;
1989 size_t linep_off, buf_size;
1990 struct SAA *p_lines = saa_init(1L);
1991 struct dir_list *p_dir;
1992 struct file_list *p_file;
1993
1994 p_section = get_section_by_name("__DWARF", "__debug_line");
1995 nasm_assert(p_section != NULL);
1996
1997 saa_write8(p_lines, 1); /* minimum instruction length */
1998 saa_write8(p_lines, 1); /* initial value of "is_stmt" */
1999 saa_write8(p_lines, DW_LN_BASE); /* line base */
2000 saa_write8(p_lines, DW_LN_RANGE); /* line range */
2001 saa_write8(p_lines, DW_OPCODE_BASE); /* opcode base */
2002 saa_write8(p_lines, 0); /* std opcode 1 length */
2003 saa_write8(p_lines, 1); /* std opcode 2 length */
2004 saa_write8(p_lines, 1); /* std opcode 3 length */
2005 saa_write8(p_lines, 1); /* std opcode 4 length */
2006 saa_write8(p_lines, 1); /* std opcode 5 length */
2007 saa_write8(p_lines, 0); /* std opcode 6 length */
2008 saa_write8(p_lines, 0); /* std opcode 7 length */
2009 saa_write8(p_lines, 0); /* std opcode 8 length */
2010 saa_write8(p_lines, 1); /* std opcode 9 length */
2011 saa_write8(p_lines, 0); /* std opcode 10 length */
2012 saa_write8(p_lines, 0); /* std opcode 11 length */
2013 saa_write8(p_lines, 1); /* std opcode 12 length */
2014 list_for_each(p_dir, dw_head_dir) {
2015 saa_wcstring(p_lines, p_dir->dir_name);
2016 }
2017 saa_write8(p_lines, 0); /* end of table */
2018
2019 list_for_each(p_file, dw_head_file) {
2020 saa_wcstring(p_lines, p_file->file_name);
2021 saa_write8(p_lines, p_file->dir->dir); /* directory id */
2022 saa_write8(p_lines, 0); /* time */
2023 saa_write8(p_lines, 0); /* size */
2024 }
2025 saa_write8(p_lines, 0); /* end of table */
2026
2027 linep_off = p_lines->datalen;
2028 /* 10 bytes for initial & prolong length, and dwarf version info */
2029 buf_size = saa_len = linep_off + total_len + 10;
2030 p_buf_base = p_buf = nasm_malloc(buf_size);
2031
2032 WRITELONG(p_buf, saa_len - 4); /* initial length; size excluding itself */
2033 WRITESHORT(p_buf, 2); /* dwarf version */
2034 WRITELONG(p_buf, linep_off); /* prolong length */
2035
2036 saa_rnbytes(p_lines, p_buf, linep_off);
2037 p_buf += linep_off;
2038 saa_free(p_lines);
2039
2040 list_for_each(p_sect, dw_head_sect) {
2041 struct SAA *p_linep = p_sect->psaa;
2042
2043 saa_len = p_linep->datalen;
2044 saa_rnbytes(p_linep, p_buf, saa_len);
2045 p_buf += saa_len;
2046
2047 saa_free(p_linep);
2048 }
2049
2050 sect_write(p_section, p_buf_base, buf_size);
2051 nasm_free(p_buf_base);
2052 }
2053
2054 /* string section */
2055 {
2056 struct SAA *p_str = saa_init(1L);
2057 char *cur_path = nasm_realpath(module_name);
2058 char *cur_file = nasm_basename(cur_path);
2059 char *cur_dir = nasm_dirname(cur_path);
2060
2061 p_section = get_section_by_name("__DWARF", "__debug_str");
2062 nasm_assert(p_section != NULL);
2063
2064 producer_str_offset = 0;
2065 module_str_offset = dir_str_offset = saa_wcstring(p_str, nasm_signature());
2066 dir_str_offset += saa_wcstring(p_str, cur_file);
2067 saa_wcstring(p_str, cur_dir);
2068
2069 saa_len = p_str->datalen;
2070 p_buf = nasm_malloc(saa_len);
2071 saa_rnbytes(p_str, p_buf, saa_len);
2072 sect_write(p_section, p_buf, saa_len);
2073
2074 nasm_free(cur_path);
2075 nasm_free(cur_file);
2076 nasm_free(cur_dir);
2077 saa_free(p_str);
2078 nasm_free(p_buf);
2079 }
2080
2081 /* debug info */
2082 {
2083 struct SAA *p_info = saa_init(1L);
2084
2085 p_section = get_section_by_name("__DWARF", "__debug_info");
2086 nasm_assert(p_section != NULL);
2087
2088 /* size will be overwritten once determined, so skip in p_info layout */
2089 saa_write16(p_info, 2); /* dwarf version */
2090 saa_write32(p_info, 0); /* offset info abbrev */
2091 saa_write8(p_info, (ofmt == &of_macho64) ? 8 : 4); /* pointer size */
2092
2093 saa_write8(p_info, 1); /* abbrev entry number */
2094
2095 saa_write32(p_info, producer_str_offset); /* offset from string table for DW_AT_producer */
2096 saa_write16(p_info, DW_LANG_Mips_Assembler); /* DW_AT_language */
2097 saa_write32(p_info, module_str_offset); /* offset from string table for DW_AT_name */
2098 saa_write32(p_info, dir_str_offset); /* offset from string table for DW_AT_comp_dir */
2099 saa_write32(p_info, 0); /* DW_AT_stmt_list */
2100
2101 if (ofmt == &of_macho64) {
2102 saa_write64(p_info, 0); /* DW_AT_low_pc */
2103 saa_write64(p_info, high_addr); /* DW_AT_high_pc */
2104 } else {
2105 saa_write32(p_info, 0); /* DW_AT_low_pc */
2106 saa_write32(p_info, high_addr); /* DW_AT_high_pc */
2107 }
2108
2109 saa_write8(p_info, 2); /* abbrev entry number */
2110
2111 if (ofmt == &of_macho64) {
2112 saa_write64(p_info, 0); /* DW_AT_low_pc */
2113 saa_write64(p_info, 0); /* DW_AT_frame_base */
2114 } else {
2115 saa_write32(p_info, 0); /* DW_AT_low_pc */
2116 saa_write32(p_info, 0); /* DW_AT_frame_base */
2117 }
2118 saa_write8(p_info, DW_END_default);
2119
2120 saa_len = p_info->datalen;
2121 p_buf_base = p_buf = nasm_malloc(saa_len + 4); /* 4B for size info */
2122
2123 WRITELONG(p_buf, saa_len);
2124 saa_rnbytes(p_info, p_buf, saa_len);
2125 sect_write(p_section, p_buf_base, saa_len + 4);
2126
2127 saa_free(p_info);
2128 nasm_free(p_buf_base);
2129 }
2130
2131 /* abbrev section */
2132 {
2133 struct SAA *p_abbrev = saa_init(1L);
2134
2135 p_section = get_section_by_name("__DWARF", "__debug_abbrev");
2136 nasm_assert(p_section != NULL);
2137
2138 saa_write8(p_abbrev, 1); /* entry number */
2139
2140 saa_write8(p_abbrev, DW_TAG_compile_unit);
2141 saa_write8(p_abbrev, DW_CHILDREN_yes);
2142
2143 saa_write8(p_abbrev, DW_AT_producer);
2144 saa_write8(p_abbrev, DW_FORM_strp);
2145
2146 saa_write8(p_abbrev, DW_AT_language);
2147 saa_write8(p_abbrev, DW_FORM_data2);
2148
2149 saa_write8(p_abbrev, DW_AT_name);
2150 saa_write8(p_abbrev, DW_FORM_strp);
2151
2152 saa_write8(p_abbrev, DW_AT_comp_dir);
2153 saa_write8(p_abbrev, DW_FORM_strp);
2154
2155 saa_write8(p_abbrev, DW_AT_stmt_list);
2156 saa_write8(p_abbrev, DW_FORM_data4);
2157
2158 saa_write8(p_abbrev, DW_AT_low_pc);
2159 saa_write8(p_abbrev, DW_FORM_addr);
2160
2161 saa_write8(p_abbrev, DW_AT_high_pc);
2162 saa_write8(p_abbrev, DW_FORM_addr);
2163
2164 saa_write16(p_abbrev, DW_END_default);
2165
2166 saa_write8(p_abbrev, 2); /* entry number */
2167
2168 saa_write8(p_abbrev, DW_TAG_subprogram);
2169 saa_write8(p_abbrev, DW_CHILDREN_no);
2170
2171 saa_write8(p_abbrev, DW_AT_low_pc);
2172 saa_write8(p_abbrev, DW_FORM_addr);
2173
2174 saa_write8(p_abbrev, DW_AT_frame_base);
2175 saa_write8(p_abbrev, DW_FORM_addr);
2176
2177 saa_write16(p_abbrev, DW_END_default);
2178
2179 saa_write8(p_abbrev, 0); /* Terminal zero entry */
2180
2181 saa_len = p_abbrev->datalen;
2182
2183 p_buf = nasm_malloc(saa_len);
2184
2185 saa_rnbytes(p_abbrev, p_buf, saa_len);
2186 sect_write(p_section, p_buf, saa_len);
2187
2188 saa_free(p_abbrev);
2189 nasm_free(p_buf);
2190 }
2191 }
2192
2193 static void new_file_list (const char *file_name, const char *dir_name)
2194 {
2195 struct dir_list *dir_list;
2196 bool need_new_dir_list = true;
2197
2198 nasm_new(dw_cur_file);
2199 dw_cur_file->file = ++dw_num_files;
2200 dw_cur_file->file_name = file_name;
2201 if(!dw_head_file) {
2202 dw_head_file = dw_cur_file;
2203 } else {
2204 *dw_last_file_next = dw_cur_file;
2205 }
2206 dw_last_file_next = &(dw_cur_file->next);
2207
2208 if(dw_head_dir) {
2209 list_for_each(dir_list, dw_head_dir) {
2210 if(!(strcmp(dir_name, dir_list->dir_name))) {
2211 dw_cur_file->dir = dir_list;
2212 need_new_dir_list = false;
2213 break;
2214 }
2215 }
2216 }
2217
2218 if(need_new_dir_list)
2219 {
2220 nasm_new(dir_list);
2221 dir_list->dir = dw_num_dirs++;
2222 dir_list->dir_name = dir_name;
2223 if(!dw_head_dir) {
2224 dw_head_dir = dir_list;
2225 } else {
2226 *dw_last_dir_next = dir_list;
2227 }
2228 dw_last_dir_next = &(dir_list->next);
2229 dw_cur_file->dir = dir_list;
2230 }
2231 }
2232
2233 static void macho_dbg_init(void)
2234 {
2235 }
2236
2237 static void macho_dbg_linenum(const char *file_name, int32_t line_num, int32_t segto)
2238 {
2239 bool need_new_list = true;
2240 const char *cur_file = nasm_basename(file_name);
2241 const char *cur_dir = nasm_dirname(file_name);
2242 (void)segto;
2243
2244 if(!dw_cur_file || strcmp(cur_file, dw_cur_file->file_name) ||
2245 strcmp(cur_dir, dw_cur_file->dir->dir_name)) {
2246 if(dw_head_file) {
2247 struct file_list *match;
2248
2249 list_for_each(match, dw_head_file) {
2250 if(!(strcmp(cur_file, match->file_name)) &&
2251 !(strcmp(cur_dir, match->dir->dir_name))) {
2252 dw_cur_file = match;
2253 dw_cur_file->dir = match->dir;
2254 need_new_list = false;
2255 break;
2256 }
2257 }
2258 }
2259
2260 if (need_new_list)
2261 new_file_list(cur_file, cur_dir);
2262 }
2263
2264 if (!need_new_list) {
2265 nasm_free((void *)cur_file);
2266 nasm_free((void *)cur_dir);
2267 }
2268
2269 dbg_immcall = true;
2270 cur_line = line_num;
2271 }
2272
2273 static void macho_dbg_output(int type, void *param)
2274 {
2275 struct section_info *sinfo_param = (struct section_info *)param;
2276 int32_t secto = sinfo_param->secto;
2277 bool need_new_sect = false;
2278 struct SAA *p_linep = NULL;
2279 (void)type;
2280
2281 if(!(dw_cur_sect && (dw_cur_sect->section == secto))) {
2282 need_new_sect = true;
2283 if(dw_head_sect) {
2284 struct dw_sect_list *match = dw_head_sect;
2285 uint32_t idx = 0;
2286
2287 for(; idx < dw_num_sects; idx++) {
2288 if(match->section == secto) {
2289 dw_cur_sect = match;
2290 need_new_sect = false;
2291 break;
2292 }
2293 match = match->next;
2294 }
2295 }
2296 }
2297
2298 if(need_new_sect) {
2299 nasm_new(dw_cur_sect);
2300 dw_num_sects ++;
2301 p_linep = dw_cur_sect->psaa = saa_init(1L);
2302 dw_cur_sect->line = dw_cur_sect->file = 1;
2303 dw_cur_sect->offset = 0;
2304 dw_cur_sect->next = NULL;
2305 dw_cur_sect->section = secto;
2306
2307 saa_write8(p_linep, DW_LNS_extended_op);
2308 saa_write8(p_linep, (ofmt == &of_macho64) ? 9 : 5);
2309 saa_write8(p_linep, DW_LNE_set_address);
2310 if (ofmt == &of_macho64) {
2311 saa_write64(p_linep, 0);
2312 } else {
2313 saa_write32(p_linep, 0);
2314 }
2315
2316 if(!dw_head_sect) {
2317 dw_head_sect = dw_last_sect = dw_cur_sect;
2318 } else {
2319 dw_last_sect->next = dw_cur_sect;
2320 dw_last_sect = dw_cur_sect;
2321 }
2322 }
2323
2324 if(dbg_immcall == true) {
2325 int32_t line_delta = cur_line - dw_cur_sect->line;
2326 int32_t offset_delta = sinfo_param->size - dw_cur_sect->offset;
2327 uint32_t cur_file = dw_cur_file->file;
2328 p_linep = dw_cur_sect->psaa;
2329
2330 if(cur_file != dw_cur_sect->file) {
2331 saa_write8(p_linep, DW_LNS_set_file);
2332 saa_write8(p_linep, cur_file);
2333 dw_cur_sect->file = cur_file;
2334 }
2335
2336 if(line_delta) {
2337 int special_opcode = (line_delta - DW_LN_BASE) + (DW_LN_RANGE * offset_delta) +
2338 DW_OPCODE_BASE;
2339
2340 if((line_delta >= DW_LN_BASE) && (line_delta < DW_MAX_LN) &&
2341 (special_opcode < DW_MAX_SP_OPCODE)) {
2342 saa_write8(p_linep, special_opcode);
2343 } else {
2344 saa_write8(p_linep, DW_LNS_advance_line);
2345 saa_wleb128s(p_linep, line_delta);
2346 if(offset_delta) {
2347 saa_write8(p_linep, DW_LNS_advance_pc);
2348 saa_wleb128u(p_linep, offset_delta);
2349 }
2350 saa_write8(p_linep, DW_LNS_copy);
2351 }
2352
2353 dw_cur_sect->line = cur_line;
2354 dw_cur_sect->offset = sinfo_param->size;
2355 }
2356
2357 dbg_immcall = false;
2358 }
2359 }
2360
2361 static void macho_dbg_cleanup(void)
2362 {
2363 /* dwarf sectors generation */
2364 macho_dbg_generate();
2365
2366 {
2367 struct dw_sect_list *p_sect = dw_head_sect;
2368 struct file_list *p_file = dw_head_file;
2369 uint32_t idx = 0;
2370
2371 for(; idx < dw_num_sects; idx++) {
2372 struct dw_sect_list *next = p_sect->next;
2373 nasm_free(p_sect);
2374 p_sect = next;
2375 }
2376
2377 for(idx = 0; idx < dw_num_files; idx++) {
2378 struct file_list *next = p_file->next;
2379 nasm_free(p_file);
2380 p_file = next;
2381 }
2382 }
2383 }
2384
2385 #ifdef OF_MACHO32
2386 static const struct macho_fmt macho32_fmt = {
2387 4,
2388 MH_MAGIC,
2389 CPU_TYPE_I386,
2390 LC_SEGMENT,
2391 MACHO_HEADER_SIZE,
2392 MACHO_SEGCMD_SIZE,
2393 MACHO_SECTCMD_SIZE,
2394 MACHO_NLIST_SIZE,
2395 RL_MAX_32,
2396 GENERIC_RELOC_VANILLA,
2397 GENERIC_RELOC_VANILLA,
2398 GENERIC_RELOC_TLV,
2399 false /* Allow segment-relative relocations */
2400 };
2401
2402 static void macho32_init(void)
2403 {
2404 fmt = macho32_fmt;
2405 macho_init();
2406
2407 macho_gotpcrel_sect = NO_SEG;
2408 }
2409
2410 static const struct dfmt macho32_df_dwarf = {
2411 "Mach-O i386 dwarf for Darwin/MacOS",
2412 "dwarf",
2413 macho_dbg_init,
2414 macho_dbg_linenum,
2415 null_debug_deflabel,
2416 NULL, /* .debug_smacros */
2417 NULL, /* .debug_include */
2418 NULL, /* .debug_mmacros */
2419 null_debug_directive,
2420 null_debug_typevalue,
2421 macho_dbg_output,
2422 macho_dbg_cleanup,
2423 NULL /*pragma list*/
2424 };
2425
2426 static const struct dfmt * const macho32_df_arr[2] =
2427 { &macho32_df_dwarf, NULL };
2428
2429 const struct ofmt of_macho32 = {
2430 "Mach-O i386 (Mach, including MacOS X and variants)",
2431 "macho32",
2432 ".o",
2433 0,
2434 32,
2435 macho32_df_arr,
2436 &macho32_df_dwarf,
2437 macho_stdmac,
2438 macho32_init,
2439 null_reset,
2440 macho_output,
2441 macho_symdef,
2442 macho_section,
2443 macho_herelabel,
2444 macho_sectalign,
2445 null_segbase,
2446 null_directive,
2447 macho_cleanup,
2448 macho_pragma_list
2449 };
2450 #endif
2451
2452 #ifdef OF_MACHO64
2453 static const struct macho_fmt macho64_fmt = {
2454 8,
2455 MH_MAGIC_64,
2456 CPU_TYPE_X86_64,
2457 LC_SEGMENT_64,
2458 MACHO_HEADER64_SIZE,
2459 MACHO_SEGCMD64_SIZE,
2460 MACHO_SECTCMD64_SIZE,
2461 MACHO_NLIST64_SIZE,
2462 RL_MAX_64,
2463 X86_64_RELOC_UNSIGNED,
2464 X86_64_RELOC_SIGNED,
2465 X86_64_RELOC_TLV,
2466 true /* Force symbol-relative relocations */
2467 };
2468
2469 static void macho64_init(void)
2470 {
2471 fmt = macho64_fmt;
2472 macho_init();
2473
2474 /* add special symbol for ..gotpcrel */
2475 macho_gotpcrel_sect = seg_alloc() + 1;
2476 backend_label("..gotpcrel", macho_gotpcrel_sect, 0L);
2477 }
2478
2479 static const struct dfmt macho64_df_dwarf = {
2480 "Mach-O x86-64 dwarf for Darwin/MacOS",
2481 "dwarf",
2482 macho_dbg_init,
2483 macho_dbg_linenum,
2484 null_debug_deflabel,
2485 NULL, /* .debug_smacros */
2486 NULL, /* .debug_include */
2487 NULL, /* .debug_mmacros */
2488 null_debug_directive,
2489 null_debug_typevalue,
2490 macho_dbg_output,
2491 macho_dbg_cleanup,
2492 NULL /*pragma list*/
2493 };
2494
2495 static const struct dfmt * const macho64_df_arr[2] =
2496 { &macho64_df_dwarf, NULL };
2497
2498 const struct ofmt of_macho64 = {
2499 "Mach-O x86-64 (Mach, including MacOS X and variants)",
2500 "macho64",
2501 ".o",
2502 0,
2503 64,
2504 macho64_df_arr,
2505 &macho64_df_dwarf,
2506 macho_stdmac,
2507 macho64_init,
2508 null_reset,
2509 macho_output,
2510 macho_symdef,
2511 macho_section,
2512 macho_herelabel,
2513 macho_sectalign,
2514 null_segbase,
2515 null_directive,
2516 macho_cleanup,
2517 macho_pragma_list,
2518 };
2519 #endif
2520
2521 #endif
2522
2523 /*
2524 * Local Variables:
2525 * mode:c
2526 * c-basic-offset:4
2527 * End:
2528 *
2529 * end of file */