BR3392231: Fix get_closest_section_symbol_by_offset
[nasm.git] / output / outmac64.c
blobb26ff24503d3b7ce3389323be1a05e4b3e2c02fa
1 /* ----------------------------------------------------------------------- *
2 *
3 * Copyright 1996-2009 The NASM Authors - All Rights Reserved
4 * See the file AUTHORS included with the NASM distribution for
5 * the specific copyright holders.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following
9 * conditions are met:
11 * * Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * * Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
19 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
20 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
29 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
30 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 * ----------------------------------------------------------------------- */
35 * outmac64.c output routines for the Netwide Assembler to produce
36 * NeXTstep/OpenStep/Rhapsody/Darwin/MacOS X (x86_64) object files
39 /* Most of this file is, like Mach-O itself, based on a.out. For more
40 * guidelines see outaout.c. */
42 #include "compiler.h"
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <ctype.h>
48 #include <inttypes.h>
50 #include "nasm.h"
51 #include "nasmlib.h"
52 #include "saa.h"
53 #include "raa.h"
54 #include "output/outform.h"
55 #include "output/outlib.h"
57 #if defined(OF_MACHO64)
59 /* Mach-O in-file header structure sizes */
60 #define MACHO_HEADER64_SIZE (32)
61 #define MACHO_SEGCMD64_SIZE (72)
62 #define MACHO_SECTCMD64_SIZE (80)
63 #define MACHO_SYMCMD_SIZE (24)
64 #define MACHO_NLIST64_SIZE (16)
65 #define MACHO_RELINFO64_SIZE (8)
67 /* Mach-O file header values */
68 #define MH_MAGIC_64 (0xfeedfacf)
69 #define CPU_TYPE_X86_64 (0x01000007) /* x86-64 platform */
70 #define CPU_SUBTYPE_I386_ALL (3) /* all-x86 compatible */
71 #define MH_OBJECT (0x1) /* object file */
73 #define LC_SEGMENT_64 (0x19) /* segment load command */
74 #define LC_SYMTAB (0x2) /* symbol table load command */
76 #define VM_PROT_NONE (0x00)
77 #define VM_PROT_READ (0x01)
78 #define VM_PROT_WRITE (0x02)
79 #define VM_PROT_EXECUTE (0x04)
81 #define VM_PROT_DEFAULT (VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE)
82 #define VM_PROT_ALL (VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE)
84 struct section {
85 /* nasm internal data */
86 struct section *next;
87 struct SAA *data;
88 int32_t index;
89 struct reloc *relocs;
90 int align;
92 /* data that goes into the file */
93 char sectname[16]; /* what this section is called */
94 char segname[16]; /* segment this section will be in */
95 uint64_t addr; /* in-memory address (subject to alignment) */
96 uint64_t size; /* in-memory and -file size */
97 uint32_t nreloc; /* relocation entry count */
98 uint32_t flags; /* type and attributes (masked) */
99 uint32_t extreloc; /* external relocations */
102 #define SECTION_TYPE 0x000000ff /* section type mask */
104 #define S_REGULAR (0x0) /* standard section */
105 #define S_ZEROFILL (0x1) /* zerofill, in-memory only */
107 #define SECTION_ATTRIBUTES_SYS 0x00ffff00 /* system setable attributes */
108 #define S_ATTR_SOME_INSTRUCTIONS 0x00000400 /* section contains some
109 machine instructions */
110 #define S_ATTR_EXT_RELOC 0x00000200 /* section has external
111 relocation entries */
112 #define S_ATTR_LOC_RELOC 0x00000100 /* section has local
113 relocation entries */
114 #define S_ATTR_PURE_INSTRUCTIONS 0x80000000 /* section uses pure
115 machine instructions */
117 static struct sectmap {
118 const char *nasmsect;
119 const char *segname;
120 const char *sectname;
121 const int32_t flags;
122 } sectmap[] = {
123 {".text", "__TEXT", "__text", S_REGULAR|S_ATTR_SOME_INSTRUCTIONS|S_ATTR_PURE_INSTRUCTIONS},
124 {".data", "__DATA", "__data", S_REGULAR},
125 {".rodata", "__DATA", "__const", S_REGULAR},
126 {".bss", "__DATA", "__bss", S_ZEROFILL},
127 {NULL, NULL, NULL, 0}
130 struct reloc {
131 /* nasm internal data */
132 struct reloc *next;
134 /* data that goes into the file */
135 int32_t addr; /* op's offset in section */
136 uint32_t snum:24, /* contains symbol index if
137 ** ext otherwise in-file
138 ** section number */
139 pcrel:1, /* relative relocation */
140 length:2, /* 0=byte, 1=word, 2=int32_t, 3=int64_t */
141 ext:1, /* external symbol referenced */
142 type:4; /* reloc type */
145 #define R_ABS 0 /* absolute relocation */
146 #define R_SCATTERED 0x80000000 /* reloc entry is scattered if
147 ** highest bit == 1 */
149 struct symbol {
150 /* nasm internal data */
151 struct symbol *next; /* next symbol in the list */
152 char *name; /* name of this symbol */
153 int32_t initial_snum; /* symbol number used above in
154 reloc */
155 int32_t snum; /* true snum for reloc */
157 /* data that goes into the file */
158 uint32_t strx; /* string table index */
159 uint8_t type; /* symbol type */
160 uint8_t sect; /* NO_SECT or section number */
161 uint16_t desc; /* for stab debugging, 0 for us */
162 uint64_t value; /* offset of symbol in section */
165 /* symbol type bits */
166 #define N_EXT 0x01 /* global or external symbol */
168 #define N_UNDF 0x0 /* undefined symbol | n_sect == */
169 #define N_ABS 0x2 /* absolute symbol | NO_SECT */
170 #define N_SECT 0xe /* defined symbol, n_sect holds
171 ** section number */
173 #define N_TYPE 0x0e /* type bit mask */
175 #define DEFAULT_SECTION_ALIGNMENT 0 /* byte (i.e. no) alignment */
177 /* special section number values */
178 #define NO_SECT 0 /* no section, invalid */
179 #define MAX_SECT 255 /* maximum number of sections */
181 static struct section *sects, **sectstail;
182 static struct symbol *syms, **symstail;
183 static uint32_t nsyms;
185 /* These variables are set by macho_layout_symbols() to organize
186 the symbol table and string table in order the dynamic linker
187 expects. They are then used in macho_write() to put out the
188 symbols and strings in that order.
190 The order of the symbol table is:
191 local symbols
192 defined external symbols (sorted by name)
193 undefined external symbols (sorted by name)
195 The order of the string table is:
196 strings for external symbols
197 strings for local symbols
199 static uint32_t ilocalsym = 0;
200 static uint32_t iextdefsym = 0;
201 static uint32_t iundefsym = 0;
202 static uint32_t nlocalsym;
203 static uint32_t nextdefsym;
204 static uint32_t nundefsym;
205 static struct symbol **extdefsyms = NULL;
206 static struct symbol **undefsyms = NULL;
208 static struct RAA *extsyms;
209 static struct SAA *strs;
210 static uint32_t strslen;
212 extern struct ofmt of_macho64;
214 /* Global file information. This should be cleaned up into either
215 a structure or as function arguments. */
216 uint32_t head_ncmds64 = 0;
217 uint32_t head_sizeofcmds64 = 0;
218 uint64_t seg_filesize64 = 0;
219 uint64_t seg_vmsize64 = 0;
220 uint32_t seg_nsects64 = 0;
221 uint64_t rel_padcnt64 = 0;
224 #define xstrncpy(xdst, xsrc) \
225 memset(xdst, '\0', sizeof(xdst)); /* zero out whole buffer */ \
226 strncpy(xdst, xsrc, sizeof(xdst)); /* copy over string */ \
227 xdst[sizeof(xdst) - 1] = '\0'; /* proper null-termination */
229 #define alignint32_t(x) \
230 ALIGN(x, sizeof(int32_t)) /* align x to int32_t boundary */
232 #define alignint64_t(x) \
233 ALIGN(x, sizeof(int64_t)) /* align x to int64_t boundary */
235 static void debug_reloc (struct reloc *);
236 static void debug_section_relocs (struct section *) _unused;
238 static struct section *get_section_by_name(const char *segname,
239 const char *sectname)
241 struct section *s;
243 for (s = sects; s != NULL; s = s->next)
244 if (!strcmp(s->segname, segname) && !strcmp(s->sectname, sectname))
245 break;
247 return s;
250 static struct section *get_section_by_index(const int32_t index)
252 struct section *s;
254 for (s = sects; s != NULL; s = s->next)
255 if (index == s->index)
256 break;
258 return s;
261 static int32_t get_section_index_by_name(const char *segname,
262 const char *sectname)
264 struct section *s;
266 for (s = sects; s != NULL; s = s->next)
267 if (!strcmp(s->segname, segname) && !strcmp(s->sectname, sectname))
268 return s->index;
270 return -1;
273 static char *get_section_name_by_index(const int32_t index)
275 struct section *s;
277 for (s = sects; s != NULL; s = s->next)
278 if (index == s->index)
279 return s->sectname;
281 return NULL;
284 static uint8_t get_section_fileindex_by_index(const int32_t index)
286 struct section *s;
287 uint8_t i = 1;
289 for (s = sects; s != NULL && i < MAX_SECT; s = s->next, ++i)
290 if (index == s->index)
291 return i;
293 if (i == MAX_SECT)
294 nasm_error(ERR_WARNING,
295 "too many sections (>255) - clipped by fileindex");
297 return NO_SECT;
300 static struct symbol *get_closest_section_symbol_by_offset(uint8_t fileindex, int64_t offset)
302 struct symbol *nearest = NULL;
303 struct symbol *sym;
305 for (sym = syms; sym; sym = sym->next) {
306 if ((sym->sect != NO_SECT) && (sym->sect == fileindex)) {
307 if ((int64_t)sym->value > offset)
308 break;
309 nearest = sym;
313 return nearest;
317 * Special section numbers which are used to define Mach-O special
318 * symbols, which can be used with WRT to provide PIC relocation
319 * types.
321 static int32_t macho_gotpcrel_sect;
323 static void macho_init(void)
325 char zero = 0;
327 maxbits = 64;
329 sects = NULL;
330 sectstail = &sects;
332 syms = NULL;
333 symstail = &syms;
334 nsyms = 0;
335 nlocalsym = 0;
336 nextdefsym = 0;
337 nundefsym = 0;
339 extsyms = raa_init();
340 strs = saa_init(1L);
342 /* string table starts with a zero byte - don't ask why */
343 saa_wbytes(strs, &zero, sizeof(char));
344 strslen = 1;
346 /* add special symbol for ..gotpcrel */
347 macho_gotpcrel_sect = seg_alloc();
348 macho_gotpcrel_sect++;
349 define_label("..gotpcrel", macho_gotpcrel_sect, 0L, NULL, false, false);
352 static void sect_write(struct section *sect,
353 const uint8_t *data, uint32_t len)
355 saa_wbytes(sect->data, data, len);
356 sect->size += len;
359 static int32_t add_reloc(struct section *sect, int32_t section,
360 int pcrel, int bytes, int64_t reloff)
362 struct reloc *r;
363 struct symbol *sym;
364 int32_t fi;
365 int32_t adjustment = 0;
367 /* NeXT as puts relocs in reversed order (address-wise) into the
368 ** files, so we do the same, doesn't seem to make much of a
369 ** difference either way */
370 r = nasm_malloc(sizeof(struct reloc));
371 r->next = sect->relocs;
372 sect->relocs = r;
374 /* the current end of the section will be the symbol's address for
375 ** now, might have to be fixed by macho_fixup_relocs() later on. make
376 ** sure we don't make the symbol scattered by setting the highest
377 ** bit by accident */
378 r->addr = sect->size & ~R_SCATTERED;
379 r->ext = 1;
380 r->pcrel = (pcrel ? 1 : 0);
382 /* match byte count 1, 2, 4, 8 to length codes 0, 1, 2, 3 respectively */
383 switch(bytes){
384 case 1:
385 r->length = 0;
386 break;
387 case 2:
388 r->length = 1;
389 break;
390 case 4:
391 r->length = 2;
392 break;
393 case 8:
394 r->length = 3;
395 break;
396 default:
397 break;
400 /* set default relocation values */
401 r->type = 0; // X86_64_RELOC_UNSIGNED
402 r->snum = R_ABS; // Absolute Symbol (indicates no relocation)
404 /* absolute relocation */
405 if (pcrel == 0) {
407 /* intra-section */
408 if (section == NO_SEG) {
409 // r->snum = R_ABS; // Set above
411 /* inter-section */
412 } else {
413 fi = get_section_fileindex_by_index(section);
415 /* external */
416 if (fi == NO_SECT) {
417 r->snum = raa_read(extsyms, section);
419 /* local */
420 } else {
421 sym = get_closest_section_symbol_by_offset(fi, reloff);
422 r->snum = sym->initial_snum;
423 adjustment = sym->value;
427 /* relative relocation */
428 } else if (pcrel == 1) {
430 /* intra-section */
431 if (section == NO_SEG) {
432 r->type = 1; // X86_64_RELOC_SIGNED
434 /* inter-section */
435 } else {
436 r->type = 2; // X86_64_RELOC_BRANCH
437 fi = get_section_fileindex_by_index(section);
439 /* external */
440 if (fi == NO_SECT) {
441 sect->extreloc = 1;
442 r->snum = raa_read(extsyms, section);
444 /* local */
445 } else {
446 sym = get_closest_section_symbol_by_offset(fi, reloff);
447 r->snum = sym->initial_snum;
448 adjustment = sym->value;
452 /* subtractor */
453 } else if (pcrel == 2) {
454 r->pcrel = 0;
455 r->type = 5; // X86_64_RELOC_SUBTRACTOR
457 /* gotpcrel */
458 } else if (pcrel == 3) {
459 r->type = 4; // X86_64_RELOC_GOT
460 r->snum = macho_gotpcrel_sect;
462 /* gotpcrel MOVQ load */
463 } else if (pcrel == 4) {
464 r->type = 3; // X86_64_RELOC_GOT_LOAD
465 r->snum = macho_gotpcrel_sect;
468 ++sect->nreloc;
470 return adjustment;
473 static void macho_output(int32_t secto, const void *data,
474 enum out_type type, uint64_t size,
475 int32_t section, int32_t wrt)
477 struct section *s, *sbss;
478 int64_t addr;
479 uint8_t mydata[16], *p, gotload;
481 if (secto == NO_SEG) {
482 if (type != OUT_RESERVE)
483 nasm_error(ERR_NONFATAL, "attempt to assemble code in "
484 "[ABSOLUTE] space");
486 return;
489 s = get_section_by_index(secto);
491 if (s == NULL) {
492 nasm_error(ERR_WARNING, "attempt to assemble code in"
493 " section %d: defaulting to `.text'", secto);
494 s = get_section_by_name("__TEXT", "__text");
496 /* should never happen */
497 if (s == NULL)
498 nasm_error(ERR_PANIC, "text section not found");
501 sbss = get_section_by_name("__DATA", "__bss");
503 if (s == sbss && type != OUT_RESERVE) {
504 nasm_error(ERR_WARNING, "attempt to initialize memory in the"
505 " BSS section: ignored");
506 s->size += realsize(type, size);
507 return;
510 switch (type) {
511 case OUT_RESERVE:
512 if (s != sbss) {
513 nasm_error(ERR_WARNING, "uninitialized space declared in"
514 " %s section: zeroing",
515 get_section_name_by_index(secto));
517 sect_write(s, NULL, size);
518 } else
519 s->size += size;
521 break;
523 case OUT_RAWDATA:
524 if (section != NO_SEG)
525 nasm_error(ERR_PANIC, "OUT_RAWDATA with other than NO_SEG");
527 sect_write(s, data, size);
528 break;
530 case OUT_ADDRESS:
531 addr = *(int64_t *)data;
532 if (section != NO_SEG) {
533 if (section % 2) {
534 nasm_error(ERR_NONFATAL, "Mach-O format does not support"
535 " section base references");
536 } else {
537 if (wrt == NO_SEG) {
538 if (size < 8) {
539 nasm_error(ERR_NONFATAL, "Mach-O 64-bit format does not support"
540 " 32-bit absolute addresses");
542 Seemingly, Mach-O's X86_64_RELOC_SUBTRACTOR would require
543 pre-determined knowledge of where the image base would be,
544 making it impractical for use in intermediate object files
546 } else {
547 addr -= add_reloc(s, section, 0, size, addr); // X86_64_RELOC_UNSIGNED
549 } else {
550 nasm_error(ERR_NONFATAL, "Mach-O format does not support"
551 " this use of WRT");
556 p = mydata;
557 WRITEADDR(p, addr, size);
558 sect_write(s, mydata, size);
559 break;
561 case OUT_REL2ADR:
562 p = mydata;
563 WRITESHORT(p, *(int64_t *)data);
565 if (section == secto)
566 nasm_error(ERR_PANIC, "intra-section OUT_REL2ADR");
568 if (section == NO_SEG) {
569 /* Do nothing */
570 } else if (section % 2) {
571 nasm_error(ERR_NONFATAL, "Mach-O format does not support"
572 " section base references");
573 } else {
574 nasm_error(ERR_NONFATAL, "Unsupported non-32-bit"
575 " Macho-O relocation [2]");
578 sect_write(s, mydata, 2L);
579 break;
581 case OUT_REL4ADR:
582 p = mydata;
583 WRITELONG(p, *(int64_t *)data);
585 if (section == secto)
586 nasm_error(ERR_PANIC, "intra-section OUT_REL4ADR");
588 if (section != NO_SEG && section % 2) {
589 nasm_error(ERR_NONFATAL, "Mach-O format does not support"
590 " section base references");
591 } else {
592 if (wrt == NO_SEG) {
593 *mydata -= add_reloc(s, section, 1, 4, (int64_t)*mydata); // X86_64_RELOC_SIGNED/BRANCH
594 } else if (wrt == macho_gotpcrel_sect) {
595 if (s->data->datalen > 1) {
596 saa_fread(s->data, s->data->datalen-2, &gotload, 1); // Retrieve Instruction Opcode
597 } else {
598 gotload = 0;
600 if (gotload == 0x8B) { // Check for MOVQ Opcode
601 *mydata -= add_reloc(s, section, 4, 4, (int64_t)*mydata); // X86_64_GOT_LOAD (MOVQ load)
602 } else {
603 *mydata -= add_reloc(s, section, 3, 4, (int64_t)*mydata); // X86_64_GOT
605 } else {
606 nasm_error(ERR_NONFATAL, "Mach-O format does not support"
607 " this use of WRT");
608 wrt = NO_SEG; /* we can at least _try_ to continue */
612 sect_write(s, mydata, 4L);
613 break;
615 default:
616 nasm_error(ERR_PANIC, "unknown output type?");
617 break;
621 static int32_t macho_section(char *name, int pass, int *bits)
623 int32_t index, originalIndex;
624 char *sectionAttributes;
625 struct sectmap *sm;
626 struct section *s;
628 (void)pass;
630 /* Default to 64 bits. */
631 if (!name) {
632 *bits = 64;
633 name = ".text";
634 sectionAttributes = NULL;
635 } else {
636 sectionAttributes = name;
637 name = nasm_strsep(&sectionAttributes, " \t");
640 for (sm = sectmap; sm->nasmsect != NULL; ++sm) {
641 /* make lookup into section name translation table */
642 if (!strcmp(name, sm->nasmsect)) {
643 char *currentAttribute;
645 /* try to find section with that name */
646 originalIndex = index = get_section_index_by_name(sm->segname,
647 sm->sectname);
649 /* create it if it doesn't exist yet */
650 if (index == -1) {
651 s = *sectstail = nasm_malloc(sizeof(struct section));
652 s->next = NULL;
653 sectstail = &s->next;
655 s->data = saa_init(1L);
656 s->index = seg_alloc();
657 s->relocs = NULL;
658 s->align = -1;
660 xstrncpy(s->segname, sm->segname);
661 xstrncpy(s->sectname, sm->sectname);
662 s->size = 0;
663 s->nreloc = 0;
664 s->flags = sm->flags;
666 index = s->index;
667 } else {
668 s = get_section_by_index(index);
671 while ((NULL != sectionAttributes)
672 && (currentAttribute = nasm_strsep(&sectionAttributes, " \t"))) {
673 if (0 != *currentAttribute) {
674 if (!nasm_strnicmp("align=", currentAttribute, 6)) {
675 char *end;
676 int newAlignment, value;
678 value = strtoul(currentAttribute + 6, (char**)&end, 0);
679 newAlignment = alignlog2_32(value);
681 if (0 != *end) {
682 nasm_error(ERR_PANIC,
683 "unknown or missing alignment value \"%s\" "
684 "specified for section \"%s\"",
685 currentAttribute + 6,
686 name);
687 return NO_SEG;
688 } else if (0 > newAlignment) {
689 nasm_error(ERR_PANIC,
690 "alignment of %d (for section \"%s\") is not "
691 "a power of two",
692 value,
693 name);
694 return NO_SEG;
697 if ((-1 != originalIndex)
698 && (s->align != newAlignment)
699 && (s->align != -1)) {
700 nasm_error(ERR_PANIC,
701 "section \"%s\" has already been specified "
702 "with alignment %d, conflicts with new "
703 "alignment of %d",
704 name,
705 (1 << s->align),
706 value);
707 return NO_SEG;
710 s->align = newAlignment;
711 } else if (!nasm_stricmp("data", currentAttribute)) {
712 /* Do nothing; 'data' is implicit */
713 } else {
714 nasm_error(ERR_PANIC,
715 "unknown section attribute %s for section %s",
716 currentAttribute,
717 name);
718 return NO_SEG;
723 return index;
727 nasm_error(ERR_PANIC, "invalid section name %s", name);
728 return NO_SEG;
731 static void macho_symdef(char *name, int32_t section, int64_t offset,
732 int is_global, char *special)
734 struct symbol *sym;
736 if (special) {
737 nasm_error(ERR_NONFATAL, "The Mach-O output format does "
738 "not support any special symbol types");
739 return;
742 if (is_global == 3) {
743 nasm_error(ERR_NONFATAL, "The Mach-O format does not "
744 "(yet) support forward reference fixups.");
745 return;
748 if (name[0] == '.' && name[1] == '.' && name[2] != '@') {
750 * This is a NASM special symbol. We never allow it into
751 * the Macho-O symbol table, even if it's a valid one. If it
752 * _isn't_ a valid one, we should barf immediately.
754 if (strcmp(name, "..gotpcrel"))
755 nasm_error(ERR_NONFATAL, "unrecognized special symbol `%s'", name);
756 return;
759 sym = *symstail = nasm_malloc(sizeof(struct symbol));
760 sym->next = NULL;
761 symstail = &sym->next;
763 sym->name = name;
764 sym->strx = strslen;
765 sym->type = 0;
766 sym->desc = 0;
767 sym->value = offset;
768 sym->initial_snum = -1;
770 /* external and common symbols get N_EXT */
771 if (is_global != 0) {
772 sym->type |= N_EXT;
775 if (section == NO_SEG) {
776 /* symbols in no section get absolute */
777 sym->type |= N_ABS;
778 sym->sect = NO_SECT;
779 } else {
780 sym->type |= N_SECT;
782 /* get the in-file index of the section the symbol was defined in */
783 sym->sect = get_section_fileindex_by_index(section);
785 /* track the initially allocated symbol number for use in future fix-ups */
786 sym->initial_snum = nsyms;
788 if (sym->sect == NO_SECT) {
790 /* remember symbol number of references to external
791 ** symbols, this works because every external symbol gets
792 ** its own section number allocated internally by nasm and
793 ** can so be used as a key */
794 extsyms = raa_write(extsyms, section, nsyms);
796 switch (is_global) {
797 case 1:
798 case 2:
799 /* there isn't actually a difference between global
800 ** and common symbols, both even have their size in
801 ** sym->value */
802 sym->type = N_EXT;
803 break;
805 default:
806 /* give an error on unfound section if it's not an
807 ** external or common symbol (assemble_file() does a
808 ** seg_alloc() on every call for them) */
809 nasm_error(ERR_PANIC, "in-file index for section %d not found",
810 section);
814 ++nsyms;
817 static void macho_sectalign(int32_t seg, unsigned int value)
819 struct section *s;
821 list_for_each(s, sects) {
822 if (s->index == seg)
823 break;
826 if (!s || !is_power2(value))
827 return;
829 value = alignlog2_32(value);
830 if (s->align < (int)value)
831 s->align = value;
834 static int32_t macho_segbase(int32_t section)
836 return section;
839 static void macho_filename(char *inname, char *outname)
841 standard_extension(inname, outname, ".o");
844 extern macros_t macho_stdmac[];
846 /* Comparison function for qsort symbol layout. */
847 static int layout_compare (const struct symbol **s1,
848 const struct symbol **s2)
850 return (strcmp ((*s1)->name, (*s2)->name));
853 /* The native assembler does a few things in a similar function
855 * Remove temporary labels
856 * Sort symbols according to local, external, undefined (by name)
857 * Order the string table
859 We do not remove temporary labels right now.
861 numsyms is the total number of symbols we have. strtabsize is the
862 number entries in the string table. */
864 static void macho_layout_symbols (uint32_t *numsyms,
865 uint32_t *strtabsize)
867 struct symbol *sym, **symp;
868 uint32_t i,j;
870 *numsyms = 0;
871 *strtabsize = sizeof (char);
873 symp = &syms;
875 while ((sym = *symp)) {
876 /* Undefined symbols are now external. */
877 if (sym->type == N_UNDF)
878 sym->type |= N_EXT;
880 if ((sym->type & N_EXT) == 0) {
881 sym->snum = *numsyms;
882 *numsyms = *numsyms + 1;
883 nlocalsym++;
885 else {
886 if ((sym->type & N_TYPE) != N_UNDF) {
887 nextdefsym++;
888 } else {
889 nundefsym++;
892 /* If we handle debug info we'll want
893 to check for it here instead of just
894 adding the symbol to the string table. */
895 sym->strx = *strtabsize;
896 saa_wbytes (strs, sym->name, (int32_t)(strlen(sym->name) + 1));
897 *strtabsize += strlen(sym->name) + 1;
899 symp = &(sym->next);
902 /* Next, sort the symbols. Most of this code is a direct translation from
903 the Apple cctools symbol layout. We need to keep compatibility with that. */
904 /* Set the indexes for symbol groups into the symbol table */
905 ilocalsym = 0;
906 iextdefsym = nlocalsym;
907 iundefsym = nlocalsym + nextdefsym;
909 /* allocate arrays for sorting externals by name */
910 extdefsyms = nasm_malloc(nextdefsym * sizeof(struct symbol *));
911 undefsyms = nasm_malloc(nundefsym * sizeof(struct symbol *));
913 i = 0;
914 j = 0;
916 symp = &syms;
918 while ((sym = *symp)) {
920 if((sym->type & N_EXT) == 0) {
921 sym->strx = *strtabsize;
922 saa_wbytes (strs, sym->name, (int32_t)(strlen (sym->name) + 1));
923 *strtabsize += strlen(sym->name) + 1;
925 else {
926 if((sym->type & N_TYPE) != N_UNDF) {
927 extdefsyms[i++] = sym;
928 } else {
929 undefsyms[j++] = sym;
932 symp = &(sym->next);
935 qsort(extdefsyms, nextdefsym, sizeof(struct symbol *),
936 (int (*)(const void *, const void *))layout_compare);
937 qsort(undefsyms, nundefsym, sizeof(struct symbol *),
938 (int (*)(const void *, const void *))layout_compare);
940 for(i = 0; i < nextdefsym; i++) {
941 extdefsyms[i]->snum = *numsyms;
942 *numsyms += 1;
944 for(j = 0; j < nundefsym; j++) {
945 undefsyms[j]->snum = *numsyms;
946 *numsyms += 1;
950 /* Calculate some values we'll need for writing later. */
952 static void macho_calculate_sizes (void)
954 struct section *s;
956 /* count sections and calculate in-memory and in-file offsets */
957 for (s = sects; s != NULL; s = s->next) {
958 uint64_t pad = 0;
960 /* zerofill sections aren't actually written to the file */
961 if ((s->flags & SECTION_TYPE) != S_ZEROFILL)
962 seg_filesize64 += s->size;
964 /* recalculate segment address based on alignment and vm size */
965 s->addr = seg_vmsize64;
966 /* we need section alignment to calculate final section address */
967 if (s->align == -1)
968 s->align = DEFAULT_SECTION_ALIGNMENT;
969 if(s->align) {
970 uint64_t newaddr = ALIGN(s->addr, 1 << s->align);
971 pad = newaddr - s->addr;
972 s->addr = newaddr;
975 seg_vmsize64 += s->size + pad;
976 ++seg_nsects64;
979 /* calculate size of all headers, load commands and sections to
980 ** get a pointer to the start of all the raw data */
981 if (seg_nsects64 > 0) {
982 ++head_ncmds64;
983 head_sizeofcmds64 +=
984 MACHO_SEGCMD64_SIZE + seg_nsects64 * MACHO_SECTCMD64_SIZE;
987 if (nsyms > 0) {
988 ++head_ncmds64;
989 head_sizeofcmds64 += MACHO_SYMCMD_SIZE;
993 /* Write out the header information for the file. */
995 static void macho_write_header (void)
997 fwriteint32_t(MH_MAGIC_64, ofile); /* magic */
998 fwriteint32_t(CPU_TYPE_X86_64, ofile); /* CPU type */
999 fwriteint32_t(CPU_SUBTYPE_I386_ALL, ofile); /* CPU subtype */
1000 fwriteint32_t(MH_OBJECT, ofile); /* Mach-O file type */
1001 fwriteint32_t(head_ncmds64, ofile); /* number of load commands */
1002 fwriteint32_t(head_sizeofcmds64, ofile); /* size of load commands */
1003 fwriteint32_t(0, ofile); /* no flags */
1004 fwriteint32_t(0, ofile); /* reserved for future use */
1007 /* Write out the segment load command at offset. */
1009 static uint32_t macho_write_segment (uint64_t offset)
1011 uint64_t rel_base = alignint64_t (offset + seg_filesize64);
1012 uint32_t s_reloff = 0;
1013 struct section *s;
1015 fwriteint32_t(LC_SEGMENT_64, ofile); /* cmd == LC_SEGMENT_64 */
1017 /* size of load command including section load commands */
1018 fwriteint32_t(MACHO_SEGCMD64_SIZE + seg_nsects64 *
1019 MACHO_SECTCMD64_SIZE, ofile);
1021 /* in an MH_OBJECT file all sections are in one unnamed (name
1022 ** all zeros) segment */
1023 fwritezero(16, ofile);
1024 fwriteint64_t(0, ofile); /* in-memory offset */
1025 fwriteint64_t(seg_vmsize64, ofile); /* in-memory size */
1026 fwriteint64_t(offset, ofile); /* in-file offset to data */
1027 fwriteint64_t(seg_filesize64, ofile); /* in-file size */
1028 fwriteint32_t(VM_PROT_DEFAULT, ofile); /* maximum vm protection */
1029 fwriteint32_t(VM_PROT_DEFAULT, ofile); /* initial vm protection */
1030 fwriteint32_t(seg_nsects64, ofile); /* number of sections */
1031 fwriteint32_t(0, ofile); /* no flags */
1033 /* emit section headers */
1034 for (s = sects; s != NULL; s = s->next) {
1035 fwrite(s->sectname, sizeof(s->sectname), 1, ofile);
1036 fwrite(s->segname, sizeof(s->segname), 1, ofile);
1037 fwriteint64_t(s->addr, ofile);
1038 fwriteint64_t(s->size, ofile);
1040 /* dummy data for zerofill sections or proper values */
1041 if ((s->flags & SECTION_TYPE) != S_ZEROFILL) {
1042 fwriteint32_t(offset, ofile);
1043 /* Write out section alignment, as a power of two.
1044 e.g. 32-bit word alignment would be 2 (2^2 = 4). */
1045 if (s->align == -1)
1046 s->align = DEFAULT_SECTION_ALIGNMENT;
1047 fwriteint32_t(s->align, ofile);
1048 /* To be compatible with cctools as we emit
1049 a zero reloff if we have no relocations. */
1050 fwriteint32_t(s->nreloc ? rel_base + s_reloff : 0, ofile);
1051 fwriteint32_t(s->nreloc, ofile);
1053 offset += s->size;
1054 s_reloff += s->nreloc * MACHO_RELINFO64_SIZE;
1055 } else {
1056 fwriteint32_t(0, ofile);
1057 fwriteint32_t(0, ofile);
1058 fwriteint32_t(0, ofile);
1059 fwriteint32_t(0, ofile);
1062 if (s->nreloc) {
1063 s->flags |= S_ATTR_LOC_RELOC;
1064 if (s->extreloc)
1065 s->flags |= S_ATTR_EXT_RELOC;
1068 fwriteint32_t(s->flags, ofile); /* flags */
1069 fwriteint32_t(0, ofile); /* reserved */
1070 fwriteint32_t(0, ofile); /* reserved */
1072 fwriteint32_t(0, ofile); /* align */
1075 rel_padcnt64 = rel_base - offset;
1076 offset = rel_base + s_reloff;
1078 return offset;
1081 /* For a given chain of relocs r, write out the entire relocation
1082 chain to the object file. */
1084 static void macho_write_relocs (struct reloc *r)
1086 while (r) {
1087 uint32_t word2;
1089 fwriteint32_t(r->addr, ofile); /* reloc offset */
1091 word2 = r->snum;
1092 word2 |= r->pcrel << 24;
1093 word2 |= r->length << 25;
1094 word2 |= r->ext << 27;
1095 word2 |= r->type << 28;
1096 fwriteint32_t(word2, ofile); /* reloc data */
1097 r = r->next;
1101 /* Write out the section data. */
1102 static void macho_write_section (void)
1104 struct section *s, *s2;
1105 struct reloc *r;
1106 uint8_t fi, *p, *q, blk[8];
1107 int32_t len;
1108 int64_t l;
1110 for (s = sects; s != NULL; s = s->next) {
1111 if ((s->flags & SECTION_TYPE) == S_ZEROFILL)
1112 continue;
1114 /* no padding needs to be done to the sections */
1116 /* Like a.out Mach-O references things in the data or bss
1117 * sections by addresses which are actually relative to the
1118 * start of the _text_ section, in the _file_. See outaout.c
1119 * for more information. */
1120 saa_rewind(s->data);
1121 for (r = s->relocs; r != NULL; r = r->next) {
1122 len = (int32_t)r->length << 1;
1123 if(len > 4) len = 8;
1124 saa_fread(s->data, r->addr, blk, len);
1125 p = q = blk;
1126 l = *p++;
1128 /* get offset based on relocation type */
1129 if (r->length > 0) {
1130 l += ((int64_t)*p++) << 8;
1132 if (r->length > 1) {
1133 l += ((int64_t)*p++) << 16;
1134 l += ((int64_t)*p++) << 24;
1137 if (r->length > 2) {
1138 l += ((int64_t)*p++) << 32;
1139 l += ((int64_t)*p++) << 40;
1140 l += ((int64_t)*p++) << 48;
1141 l += ((int64_t)*p++) << 56;
1147 /* If the relocation is internal add to the current section
1148 offset. Otherwise the only value we need is the symbol
1149 offset which we already have. The linker takes care
1150 of the rest of the address. */
1151 if (!r->ext) {
1152 /* generate final address by section address and offset */
1153 for (s2 = sects, fi = 1;
1154 s2 != NULL; s2 = s2->next, fi++) {
1155 if (fi == r->snum) {
1156 l += s2->addr;
1157 break;
1162 /* write new offset back */
1163 if (r->length == 3)
1164 WRITEDLONG(q, l);
1165 else if (r->length == 2)
1166 WRITELONG(q, l);
1167 else if (r->length == 1)
1168 WRITESHORT(q, l);
1169 else
1170 *q++ = l & 0xFF;
1172 saa_fwrite(s->data, r->addr, blk, len);
1175 /* dump the section data to file */
1176 saa_fpwrite(s->data, ofile);
1179 /* pad last section up to reloc entries on int64_t boundary */
1180 fwritezero(rel_padcnt64, ofile);
1182 /* emit relocation entries */
1183 for (s = sects; s != NULL; s = s->next)
1184 macho_write_relocs (s->relocs);
1187 /* Write out the symbol table. We should already have sorted this
1188 before now. */
1189 static void macho_write_symtab (void)
1191 struct symbol *sym;
1192 struct section *s;
1193 int64_t fi;
1194 uint64_t i;
1196 /* we don't need to pad here since MACHO_RELINFO_SIZE == 8 */
1198 for (sym = syms; sym != NULL; sym = sym->next) {
1199 if ((sym->type & N_EXT) == 0) {
1200 fwriteint32_t(sym->strx, ofile); /* string table entry number */
1201 fwrite(&sym->type, 1, 1, ofile); /* symbol type */
1202 fwrite(&sym->sect, 1, 1, ofile); /* section */
1203 fwriteint16_t(sym->desc, ofile); /* description */
1205 /* Fix up the symbol value now that we know the final section
1206 sizes. */
1207 if (((sym->type & N_TYPE) == N_SECT) && (sym->sect != NO_SECT)) {
1208 for (s = sects, fi = 1; s != NULL; s = s->next, fi++) {
1209 if (fi == sym->sect) {
1210 sym->value += s->addr;
1211 break;
1216 fwriteint64_t(sym->value, ofile); /* value (i.e. offset) */
1220 for (i = 0; i < nextdefsym; i++) {
1221 sym = extdefsyms[i];
1222 fwriteint32_t(sym->strx, ofile);
1223 fwrite(&sym->type, 1, 1, ofile); /* symbol type */
1224 fwrite(&sym->sect, 1, 1, ofile); /* section */
1225 fwriteint16_t(sym->desc, ofile); /* description */
1227 /* Fix up the symbol value now that we know the final section
1228 sizes. */
1229 if (((sym->type & N_TYPE) == N_SECT) && (sym->sect != NO_SECT)) {
1230 for (s = sects, fi = 1;
1231 s != NULL && fi < sym->sect; s = s->next, ++fi)
1232 sym->value += s->size;
1235 fwriteint64_t(sym->value, ofile); /* value (i.e. offset) */
1238 for (i = 0; i < nundefsym; i++) {
1239 sym = undefsyms[i];
1240 fwriteint32_t(sym->strx, ofile);
1241 fwrite(&sym->type, 1, 1, ofile); /* symbol type */
1242 fwrite(&sym->sect, 1, 1, ofile); /* section */
1243 fwriteint16_t(sym->desc, ofile); /* description */
1245 // Fix up the symbol value now that we know the final section sizes.
1246 if (((sym->type & N_TYPE) == N_SECT) && (sym->sect != NO_SECT)) {
1247 for (s = sects, fi = 1;
1248 s != NULL && fi < sym->sect; s = s->next, ++fi)
1249 sym->value += s->size;
1252 fwriteint64_t(sym->value, ofile); // value (i.e. offset)
1257 /* Fixup the snum in the relocation entries, we should be
1258 doing this only for externally referenced symbols. */
1259 static void macho_fixup_relocs (struct reloc *r)
1261 struct symbol *sym;
1263 while (r != NULL) {
1264 if (r->ext) {
1265 for (sym = syms; sym != NULL; sym = sym->next) {
1266 if (sym->initial_snum == r->snum) {
1267 r->snum = sym->snum;
1268 break;
1272 r = r->next;
1276 /* Write out the object file. */
1278 static void macho_write (void)
1280 uint64_t offset = 0;
1282 /* mach-o object file structure:
1284 ** mach header
1285 ** uint32_t magic
1286 ** int cpu type
1287 ** int cpu subtype
1288 ** uint32_t mach file type
1289 ** uint32_t number of load commands
1290 ** uint32_t size of all load commands
1291 ** (includes section struct size of segment command)
1292 ** uint32_t flags
1294 ** segment command
1295 ** uint32_t command type == LC_SEGMENT_64
1296 ** uint32_t size of load command
1297 ** (including section load commands)
1298 ** char[16] segment name
1299 ** uint64_t in-memory offset
1300 ** uint64_t in-memory size
1301 ** uint64_t in-file offset to data area
1302 ** uint64_t in-file size
1303 ** (in-memory size excluding zerofill sections)
1304 ** int maximum vm protection
1305 ** int initial vm protection
1306 ** uint32_t number of sections
1307 ** uint32_t flags
1309 ** section commands
1310 ** char[16] section name
1311 ** char[16] segment name
1312 ** uint64_t in-memory offset
1313 ** uint64_t in-memory size
1314 ** uint32_t in-file offset
1315 ** uint32_t alignment
1316 ** (irrelevant in MH_OBJECT)
1317 ** uint32_t in-file offset of relocation entires
1318 ** uint32_t number of relocations
1319 ** uint32_t flags
1320 ** uint32_t reserved
1321 ** uint32_t reserved
1323 ** symbol table command
1324 ** uint32_t command type == LC_SYMTAB
1325 ** uint32_t size of load command
1326 ** uint32_t symbol table offset
1327 ** uint32_t number of symbol table entries
1328 ** uint32_t string table offset
1329 ** uint32_t string table size
1331 ** raw section data
1333 ** padding to int64_t boundary
1335 ** relocation data (struct reloc)
1336 ** int32_t offset
1337 ** uint data (symbolnum, pcrel, length, extern, type)
1339 ** symbol table data (struct nlist)
1340 ** int32_t string table entry number
1341 ** uint8_t type
1342 ** (extern, absolute, defined in section)
1343 ** uint8_t section
1344 ** (0 for global symbols, section number of definition (>= 1, <=
1345 ** 254) for local symbols, size of variable for common symbols
1346 ** [type == extern])
1347 ** int16_t description
1348 ** (for stab debugging format)
1349 ** uint64_t value (i.e. file offset) of symbol or stab offset
1351 ** string table data
1352 ** list of null-terminated strings
1355 /* Emit the Mach-O header. */
1356 macho_write_header();
1358 offset = MACHO_HEADER64_SIZE + head_sizeofcmds64;
1360 /* emit the segment load command */
1361 if (seg_nsects64 > 0)
1362 offset = macho_write_segment (offset);
1363 else
1364 nasm_error(ERR_WARNING, "no sections?");
1366 if (nsyms > 0) {
1367 /* write out symbol command */
1368 fwriteint32_t(LC_SYMTAB, ofile); /* cmd == LC_SYMTAB */
1369 fwriteint32_t(MACHO_SYMCMD_SIZE, ofile); /* size of load command */
1370 fwriteint32_t(offset, ofile); /* symbol table offset */
1371 fwriteint32_t(nsyms, ofile); /* number of symbol
1372 ** table entries */
1374 offset += nsyms * MACHO_NLIST64_SIZE;
1375 fwriteint32_t(offset, ofile); /* string table offset */
1376 fwriteint32_t(strslen, ofile); /* string table size */
1379 /* emit section data */
1380 if (seg_nsects64 > 0)
1381 macho_write_section ();
1383 /* emit symbol table if we have symbols */
1384 if (nsyms > 0)
1385 macho_write_symtab ();
1387 /* we don't need to pad here since MACHO_NLIST64_SIZE == 16 */
1389 /* emit string table */
1390 saa_fpwrite(strs, ofile);
1392 /* We do quite a bit here, starting with finalizing all of the data
1393 for the object file, writing, and then freeing all of the data from
1394 the file. */
1396 static void macho_cleanup(int debuginfo)
1398 struct section *s;
1399 struct reloc *r;
1400 struct symbol *sym;
1402 (void)debuginfo;
1404 /* Sort all symbols. */
1405 macho_layout_symbols (&nsyms, &strslen);
1407 /* Fixup relocation entries */
1408 for (s = sects; s != NULL; s = s->next) {
1409 macho_fixup_relocs (s->relocs);
1412 /* First calculate and finalize needed values. */
1413 macho_calculate_sizes();
1414 macho_write();
1416 /* free up everything */
1417 while (sects->next) {
1418 s = sects;
1419 sects = sects->next;
1421 saa_free(s->data);
1422 while (s->relocs != NULL) {
1423 r = s->relocs;
1424 s->relocs = s->relocs->next;
1425 nasm_free(r);
1428 nasm_free(s);
1431 saa_free(strs);
1432 raa_free(extsyms);
1434 if (syms) {
1435 while (syms->next) {
1436 sym = syms;
1437 syms = syms->next;
1439 nasm_free (sym);
1444 /* Debugging routines. */
1445 static void debug_reloc (struct reloc *r)
1447 fprintf (stdout, "reloc:\n");
1448 fprintf (stdout, "\taddr: %"PRId32"\n", r->addr);
1449 fprintf (stdout, "\tsnum: %d\n", r->snum);
1450 fprintf (stdout, "\tpcrel: %d\n", r->pcrel);
1451 fprintf (stdout, "\tlength: %d\n", r->length);
1452 fprintf (stdout, "\text: %d\n", r->ext);
1453 fprintf (stdout, "\ttype: %d\n", r->type);
1456 static void debug_section_relocs (struct section *s)
1458 struct reloc *r = s->relocs;
1460 fprintf (stdout, "relocs for section %s:\n\n", s->sectname);
1462 while (r != NULL) {
1463 debug_reloc (r);
1464 r = r->next;
1468 struct ofmt of_macho64 = {
1469 "NeXTstep/OpenStep/Rhapsody/Darwin/MacOS X (x86_64) object files",
1470 "macho64",
1472 null_debug_arr,
1473 &null_debug_form,
1474 macho_stdmac,
1475 macho_init,
1476 null_setinfo,
1477 macho_output,
1478 macho_symdef,
1479 macho_section,
1480 macho_sectalign,
1481 macho_segbase,
1482 null_directive,
1483 macho_filename,
1484 macho_cleanup
1487 #endif
1490 * Local Variables:
1491 * mode:c
1492 * c-basic-offset:4
1493 * End:
1495 * end of file */