coff: Use predefined macro in common section flags
[nasm.git] / output / outmacho32.c
blobb0c9560079d4f3828f46d3d0882a56c8a9051df1
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 * outmacho.c output routines for the Netwide Assembler to produce
36 * NeXTstep/OpenStep/Rhapsody/Darwin/MacOS X 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 "eval.h"
55 #include "output/outform.h"
56 #include "output/outlib.h"
58 #if defined(OF_MACHO32)
60 /* Mach-O in-file header structure sizes */
61 #define MACHO_HEADER_SIZE (28)
62 #define MACHO_SEGCMD_SIZE (56)
63 #define MACHO_SECTCMD_SIZE (68)
64 #define MACHO_SYMCMD_SIZE (24)
65 #define MACHO_NLIST_SIZE (12)
66 #define MACHO_RELINFO_SIZE (8)
68 /* Mach-O file header values */
69 #define MH_MAGIC (0xfeedface)
70 #define CPU_TYPE_I386 (7) /* x86 platform */
71 #define CPU_SUBTYPE_I386_ALL (3) /* all-x86 compatible */
72 #define MH_OBJECT (0x1) /* object file */
74 #define LC_SEGMENT (0x1) /* segment load command */
75 #define LC_SYMTAB (0x2) /* symbol table load command */
77 #define VM_PROT_NONE (0x00)
78 #define VM_PROT_READ (0x01)
79 #define VM_PROT_WRITE (0x02)
80 #define VM_PROT_EXECUTE (0x04)
82 #define VM_PROT_DEFAULT (VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE)
83 #define VM_PROT_ALL (VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE)
85 struct section {
86 /* nasm internal data */
87 struct section *next;
88 struct SAA *data;
89 int32_t index;
90 struct reloc *relocs;
91 int align;
93 /* data that goes into the file */
94 char sectname[16]; /* what this section is called */
95 char segname[16]; /* segment this section will be in */
96 uint32_t addr; /* in-memory address (subject to alignment) */
97 uint32_t size; /* in-memory and -file size */
98 uint32_t nreloc; /* relocation entry count */
99 uint32_t flags; /* type and attributes (masked) */
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 */
116 static struct sectmap {
117 const char *nasmsect;
118 const char *segname;
119 const char *sectname;
120 const int32_t flags;
121 } sectmap[] = {
122 {".text", "__TEXT", "__text", S_REGULAR|S_ATTR_SOME_INSTRUCTIONS},
123 {".data", "__DATA", "__data", S_REGULAR},
124 {".rodata", "__DATA", "__const", S_REGULAR},
125 {".bss", "__DATA", "__bss", S_ZEROFILL},
126 {NULL, NULL, NULL, 0}
129 struct reloc {
130 /* nasm internal data */
131 struct reloc *next;
133 /* data that goes into the file */
134 int32_t addr; /* op's offset in section */
135 unsigned int snum:24, /* contains symbol index if
136 ** ext otherwise in-file
137 ** section number */
138 pcrel:1, /* relative relocation */
139 length:2, /* 0=byte, 1=word, 2=int32_t */
140 ext:1, /* external symbol referenced */
141 type:4; /* reloc type, 0 for us */
144 #define R_ABS 0 /* absolute relocation */
145 #define R_SCATTERED 0x80000000 /* reloc entry is scattered if
146 ** highest bit == 1 */
148 struct symbol {
149 /* nasm internal data */
150 struct symbol *next; /* next symbol in the list */
151 char *name; /* name of this symbol */
152 int32_t initial_snum; /* symbol number used above in
153 reloc */
154 int32_t snum; /* true snum for reloc */
156 /* data that goes into the file */
157 int32_t strx; /* string table index */
158 uint8_t type; /* symbol type */
159 uint8_t sect; /* NO_SECT or section number */
160 int16_t desc; /* for stab debugging, 0 for us */
161 uint32_t value; /* offset of symbol in section */
164 /* symbol type bits */
165 #define N_EXT 0x01 /* global or external symbol */
167 #define N_UNDF 0x0 /* undefined symbol | n_sect == */
168 #define N_ABS 0x2 /* absolute symbol | NO_SECT */
169 #define N_SECT 0xe /* defined symbol, n_sect holds
170 ** section number */
172 #define N_TYPE 0x0e /* type bit mask */
174 #define DEFAULT_SECTION_ALIGNMENT 0 /* byte (i.e. no) alignment */
176 /* special section number values */
177 #define NO_SECT 0 /* no section, invalid */
178 #define MAX_SECT 255 /* maximum number of sections */
180 static struct section *sects, **sectstail;
181 static struct symbol *syms, **symstail;
182 static uint32_t nsyms;
184 /* These variables are set by macho_layout_symbols() to organize
185 the symbol table and string table in order the dynamic linker
186 expects. They are then used in macho_write() to put out the
187 symbols and strings in that order.
189 The order of the symbol table is:
190 local symbols
191 defined external symbols (sorted by name)
192 undefined external symbols (sorted by name)
194 The order of the string table is:
195 strings for external symbols
196 strings for local symbols
198 static uint32_t ilocalsym = 0;
199 static uint32_t iextdefsym = 0;
200 static uint32_t iundefsym = 0;
201 static uint32_t nlocalsym;
202 static uint32_t nextdefsym;
203 static uint32_t nundefsym;
204 static struct symbol **extdefsyms = NULL;
205 static struct symbol **undefsyms = NULL;
207 static struct RAA *extsyms;
208 static struct SAA *strs;
209 static uint32_t strslen;
211 /* Global file information. This should be cleaned up into either
212 a structure or as function arguments. */
213 uint32_t head_ncmds = 0;
214 uint32_t head_sizeofcmds = 0;
215 uint32_t seg_filesize = 0;
216 uint32_t seg_vmsize = 0;
217 uint32_t seg_nsects = 0;
218 uint32_t rel_padcnt = 0;
221 #define xstrncpy(xdst, xsrc) \
222 memset(xdst, '\0', sizeof(xdst)); /* zero out whole buffer */ \
223 strncpy(xdst, xsrc, sizeof(xdst)); /* copy over string */ \
224 xdst[sizeof(xdst) - 1] = '\0'; /* proper null-termination */
226 #define alignint32_t(x) \
227 ALIGN(x, sizeof(int32_t)) /* align x to int32_t boundary */
229 static void debug_reloc (struct reloc *);
230 static void debug_section_relocs (struct section *) _unused;
232 static int exact_log2 (uint32_t align)
234 if (align == 0) {
235 return 0;
236 } else if (align & (align-1)) {
237 return -1; /* Not a power of 2 */
238 } else {
239 #ifdef HAVE_GNUC_4
240 return __builtin_ctzl (align);
241 #else
242 uint32_t result = 0;
244 /* We know exactly one bit is set at this point. */
245 if (align & 0xffff0000)
246 result |= 16;
247 if (align & 0xff00ff00)
248 result |= 8;
249 if (align & 0xf0f0f0f0)
250 result |= 4;
251 if (align & 0xcccccccc)
252 result |= 2;
253 if (align & 0xaaaaaaaa)
254 result |= 1;
256 return result;
257 #endif
261 static struct section *get_section_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 break;
270 return s;
273 static struct section *get_section_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 break;
281 return s;
284 static int32_t get_section_index_by_name(const char *segname,
285 const char *sectname)
287 struct section *s;
289 for (s = sects; s != NULL; s = s->next)
290 if (!strcmp(s->segname, segname) && !strcmp(s->sectname, sectname))
291 return s->index;
293 return -1;
296 static char *get_section_name_by_index(const int32_t index)
298 struct section *s;
300 for (s = sects; s != NULL; s = s->next)
301 if (index == s->index)
302 return s->sectname;
304 return NULL;
307 static uint8_t get_section_fileindex_by_index(const int32_t index)
309 struct section *s;
310 uint8_t i = 1;
312 for (s = sects; s != NULL && i < MAX_SECT; s = s->next, ++i)
313 if (index == s->index)
314 return i;
316 if (i == MAX_SECT)
317 nasm_error(ERR_WARNING,
318 "too many sections (>255) - clipped by fileindex");
320 return NO_SECT;
323 static void macho_init(void)
325 char zero = 0;
327 sects = NULL;
328 sectstail = &sects;
330 syms = NULL;
331 symstail = &syms;
332 nsyms = 0;
333 nlocalsym = 0;
334 nextdefsym = 0;
335 nundefsym = 0;
337 extsyms = raa_init();
338 strs = saa_init(1L);
340 /* string table starts with a zero byte - don't ask why */
341 saa_wbytes(strs, &zero, sizeof(char));
342 strslen = 1;
345 static void sect_write(struct section *sect,
346 const uint8_t *data, uint32_t len)
348 saa_wbytes(sect->data, data, len);
349 sect->size += len;
352 static void add_reloc(struct section *sect, int32_t section,
353 int pcrel, int bytes)
355 struct reloc *r;
356 int32_t fi;
358 /* NeXT as puts relocs in reversed order (address-wise) into the
359 ** files, so we do the same, doesn't seem to make much of a
360 ** difference either way */
361 r = nasm_malloc(sizeof(struct reloc));
362 r->next = sect->relocs;
363 sect->relocs = r;
365 /* the current end of the section will be the symbol's address for
366 ** now, might have to be fixed by macho_fixup_relocs() later on. make
367 ** sure we don't make the symbol scattered by setting the highest
368 ** bit by accident */
369 r->addr = sect->size & ~R_SCATTERED;
370 r->ext = 0;
371 r->pcrel = pcrel;
373 /* match byte count 1, 2, 4 to length codes 0, 1, 2 respectively */
374 r->length = bytes >> 1;
376 /* vanilla relocation (GENERIC_RELOC_VANILLA) */
377 r->type = 0;
379 if (section == NO_SEG) {
380 /* absolute local symbol if no section index given */
381 r->snum = R_ABS;
382 } else {
383 fi = get_section_fileindex_by_index(section);
385 if (fi == NO_SECT) {
386 /* external symbol if no section with that index known,
387 ** symbol number was saved in macho_symdef() */
388 r->snum = raa_read(extsyms, section);
389 r->ext = 1;
390 } else {
391 /* local symbol in section fi */
392 r->snum = fi;
396 ++sect->nreloc;
399 static void macho_output(int32_t secto, const void *data,
400 enum out_type type, uint64_t size,
401 int32_t section, int32_t wrt)
403 struct section *s, *sbss;
404 int32_t addr;
405 uint8_t mydata[4], *p;
407 if (wrt != NO_SEG) {
408 wrt = NO_SEG;
409 nasm_error(ERR_NONFATAL, "WRT not supported by Mach-O output format");
410 /* continue to do _something_ */
413 if (secto == NO_SEG) {
414 if (type != OUT_RESERVE)
415 nasm_error(ERR_NONFATAL, "attempt to assemble code in "
416 "[ABSOLUTE] space");
418 return;
421 s = get_section_by_index(secto);
423 if (s == NULL) {
424 nasm_error(ERR_WARNING, "attempt to assemble code in"
425 " section %d: defaulting to `.text'", secto);
426 s = get_section_by_name("__TEXT", "__text");
428 /* should never happen */
429 if (s == NULL)
430 nasm_error(ERR_PANIC, "text section not found");
433 sbss = get_section_by_name("__DATA", "__bss");
435 if (s == sbss && type != OUT_RESERVE) {
436 nasm_error(ERR_WARNING, "attempt to initialize memory in the"
437 " BSS section: ignored");
438 s->size += realsize(type, size);
439 return;
442 switch (type) {
443 case OUT_RESERVE:
444 if (s != sbss) {
445 nasm_error(ERR_WARNING, "uninitialized space declared in"
446 " %s section: zeroing",
447 get_section_name_by_index(secto));
449 sect_write(s, NULL, size);
450 } else
451 s->size += size;
453 break;
455 case OUT_RAWDATA:
456 if (section != NO_SEG)
457 nasm_error(ERR_PANIC, "OUT_RAWDATA with other than NO_SEG");
459 sect_write(s, data, size);
460 break;
462 case OUT_ADDRESS:
463 addr = *(int64_t *)data;
465 if (section != NO_SEG) {
466 if (section % 2) {
467 nasm_error(ERR_NONFATAL, "Mach-O format does not support"
468 " section base references");
469 } else
470 add_reloc(s, section, 0, size);
473 p = mydata;
474 WRITEADDR(p, addr, size);
475 sect_write(s, mydata, size);
476 break;
478 case OUT_REL2ADR:
479 if (section == secto)
480 nasm_error(ERR_PANIC, "intra-section OUT_REL2ADR");
482 if (section != NO_SEG && section % 2) {
483 nasm_error(ERR_NONFATAL, "Mach-O format does not support"
484 " section base references");
485 } else
486 add_reloc(s, section, 1, 2);
488 p = mydata;
489 WRITESHORT(p, *(int32_t *)data - (size + s->size));
490 sect_write(s, mydata, 2L);
491 break;
493 case OUT_REL4ADR:
494 if (section == secto)
495 nasm_error(ERR_PANIC, "intra-section OUT_REL4ADR");
497 if (section != NO_SEG && section % 2) {
498 nasm_error(ERR_NONFATAL, "Mach-O format does not support"
499 " section base references");
500 } else
501 add_reloc(s, section, 1, 4);
503 p = mydata;
504 WRITELONG(p, *(int32_t *)data - (size + s->size));
505 sect_write(s, mydata, 4L);
506 break;
508 default:
509 nasm_error(ERR_PANIC, "unknown output type?");
510 break;
514 static int32_t macho_section(char *name, int pass, int *bits)
516 int32_t index, originalIndex;
517 char *sectionAttributes;
518 struct sectmap *sm;
519 struct section *s;
521 (void)pass;
523 /* Default to 32 bits. */
524 if (!name) {
525 *bits = 32;
526 name = ".text";
527 sectionAttributes = NULL;
528 } else {
529 sectionAttributes = name;
530 name = nasm_strsep(&sectionAttributes, " \t");
533 for (sm = sectmap; sm->nasmsect != NULL; ++sm) {
534 /* make lookup into section name translation table */
535 if (!strcmp(name, sm->nasmsect)) {
536 char *currentAttribute;
538 /* try to find section with that name */
539 originalIndex = index = get_section_index_by_name(sm->segname,
540 sm->sectname);
542 /* create it if it doesn't exist yet */
543 if (index == -1) {
544 s = *sectstail = nasm_malloc(sizeof(struct section));
545 s->next = NULL;
546 sectstail = &s->next;
548 s->data = saa_init(1L);
549 s->index = seg_alloc();
550 s->relocs = NULL;
551 s->align = -1;
553 xstrncpy(s->segname, sm->segname);
554 xstrncpy(s->sectname, sm->sectname);
555 s->size = 0;
556 s->nreloc = 0;
557 s->flags = sm->flags;
559 index = s->index;
560 } else {
561 s = get_section_by_index(index);
564 while ((NULL != sectionAttributes)
565 && (currentAttribute = nasm_strsep(&sectionAttributes, " \t"))) {
566 if (0 != *currentAttribute) {
567 if (!nasm_strnicmp("align=", currentAttribute, 6)) {
568 char *end;
569 int newAlignment, value;
571 value = strtoul(currentAttribute + 6, (char**)&end, 0);
572 newAlignment = exact_log2(value);
574 if (0 != *end) {
575 nasm_error(ERR_PANIC,
576 "unknown or missing alignment value \"%s\" "
577 "specified for section \"%s\"",
578 currentAttribute + 6,
579 name);
580 return NO_SEG;
581 } else if (0 > newAlignment) {
582 nasm_error(ERR_PANIC,
583 "alignment of %d (for section \"%s\") is not "
584 "a power of two",
585 value,
586 name);
587 return NO_SEG;
590 if ((-1 != originalIndex)
591 && (s->align != newAlignment)
592 && (s->align != -1)) {
593 nasm_error(ERR_PANIC,
594 "section \"%s\" has already been specified "
595 "with alignment %d, conflicts with new "
596 "alignment of %d",
597 name,
598 (1 << s->align),
599 value);
600 return NO_SEG;
603 s->align = newAlignment;
604 } else if (!nasm_stricmp("data", currentAttribute)) {
605 /* Do nothing; 'data' is implicit */
606 } else {
607 nasm_error(ERR_PANIC,
608 "unknown section attribute %s for section %s",
609 currentAttribute,
610 name);
611 return NO_SEG;
616 return index;
620 nasm_error(ERR_PANIC, "invalid section name %s", name);
621 return NO_SEG;
624 static void macho_symdef(char *name, int32_t section, int64_t offset,
625 int is_global, char *special)
627 struct symbol *sym;
629 if (special) {
630 nasm_error(ERR_NONFATAL, "The Mach-O output format does "
631 "not support any special symbol types");
632 return;
635 if (is_global == 3) {
636 nasm_error(ERR_NONFATAL, "The Mach-O format does not "
637 "(yet) support forward reference fixups.");
638 return;
641 sym = *symstail = nasm_malloc(sizeof(struct symbol));
642 sym->next = NULL;
643 symstail = &sym->next;
645 sym->name = name;
646 sym->strx = strslen;
647 sym->type = 0;
648 sym->desc = 0;
649 sym->value = offset;
650 sym->initial_snum = -1;
652 /* external and common symbols get N_EXT */
653 if (is_global != 0)
654 sym->type |= N_EXT;
656 if (section == NO_SEG) {
657 /* symbols in no section get absolute */
658 sym->type |= N_ABS;
659 sym->sect = NO_SECT;
660 } else {
661 sym->type |= N_SECT;
663 /* get the in-file index of the section the symbol was defined in */
664 sym->sect = get_section_fileindex_by_index(section);
666 if (sym->sect == NO_SECT) {
667 /* remember symbol number of references to external
668 ** symbols, this works because every external symbol gets
669 ** its own section number allocated internally by nasm and
670 ** can so be used as a key */
671 extsyms = raa_write(extsyms, section, nsyms);
672 sym->initial_snum = nsyms;
674 switch (is_global) {
675 case 1:
676 case 2:
677 /* there isn't actually a difference between global
678 ** and common symbols, both even have their size in
679 ** sym->value */
680 sym->type = N_EXT;
681 break;
683 default:
684 /* give an error on unfound section if it's not an
685 ** external or common symbol (assemble_file() does a
686 ** seg_alloc() on every call for them) */
687 nasm_error(ERR_PANIC, "in-file index for section %d not found",
688 section);
693 ++nsyms;
696 static int32_t macho_segbase(int32_t section)
698 return section;
701 static void macho_filename(char *inname, char *outname)
703 standard_extension(inname, outname, ".o");
706 extern macros_t macho_stdmac[];
708 /* Comparison function for qsort symbol layout. */
709 static int layout_compare (const struct symbol **s1,
710 const struct symbol **s2)
712 return (strcmp ((*s1)->name, (*s2)->name));
715 /* The native assembler does a few things in a similar function
717 * Remove temporary labels
718 * Sort symbols according to local, external, undefined (by name)
719 * Order the string table
721 We do not remove temporary labels right now.
723 numsyms is the total number of symbols we have. strtabsize is the
724 number entries in the string table. */
726 static void macho_layout_symbols (uint32_t *numsyms,
727 uint32_t *strtabsize)
729 struct symbol *sym, **symp;
730 uint32_t i,j;
732 *numsyms = 0;
733 *strtabsize = sizeof (char);
735 symp = &syms;
737 while ((sym = *symp)) {
738 /* Undefined symbols are now external. */
739 if (sym->type == N_UNDF)
740 sym->type |= N_EXT;
742 if ((sym->type & N_EXT) == 0) {
743 sym->snum = *numsyms;
744 *numsyms = *numsyms + 1;
745 nlocalsym++;
747 else {
748 if ((sym->type & N_TYPE) != N_UNDF)
749 nextdefsym++;
750 else
751 nundefsym++;
753 /* If we handle debug info we'll want
754 to check for it here instead of just
755 adding the symbol to the string table. */
756 sym->strx = *strtabsize;
757 saa_wbytes (strs, sym->name, (int32_t)(strlen(sym->name) + 1));
758 *strtabsize += strlen(sym->name) + 1;
760 symp = &(sym->next);
763 /* Next, sort the symbols. Most of this code is a direct translation from
764 the Apple cctools symbol layout. We need to keep compatibility with that. */
765 /* Set the indexes for symbol groups into the symbol table */
766 ilocalsym = 0;
767 iextdefsym = nlocalsym;
768 iundefsym = nlocalsym + nextdefsym;
770 /* allocate arrays for sorting externals by name */
771 extdefsyms = nasm_malloc(nextdefsym * sizeof(struct symbol *));
772 undefsyms = nasm_malloc(nundefsym * sizeof(struct symbol *));
774 i = 0;
775 j = 0;
777 symp = &syms;
779 while ((sym = *symp)) {
781 if((sym->type & N_EXT) == 0) {
782 sym->strx = *strtabsize;
783 saa_wbytes (strs, sym->name, (int32_t)(strlen (sym->name) + 1));
784 *strtabsize += strlen(sym->name) + 1;
786 else {
787 if((sym->type & N_TYPE) != N_UNDF)
788 extdefsyms[i++] = sym;
789 else
790 undefsyms[j++] = sym;
792 symp = &(sym->next);
795 qsort(extdefsyms, nextdefsym, sizeof(struct symbol *),
796 (int (*)(const void *, const void *))layout_compare);
797 qsort(undefsyms, nundefsym, sizeof(struct symbol *),
798 (int (*)(const void *, const void *))layout_compare);
800 for(i = 0; i < nextdefsym; i++) {
801 extdefsyms[i]->snum = *numsyms;
802 *numsyms += 1;
804 for(j = 0; j < nundefsym; j++) {
805 undefsyms[j]->snum = *numsyms;
806 *numsyms += 1;
810 /* Calculate some values we'll need for writing later. */
812 static void macho_calculate_sizes (void)
814 struct section *s;
816 /* count sections and calculate in-memory and in-file offsets */
817 for (s = sects; s != NULL; s = s->next) {
818 uint32_t pad = 0;
820 /* zerofill sections aren't actually written to the file */
821 if ((s->flags & SECTION_TYPE) != S_ZEROFILL)
822 seg_filesize += s->size;
824 /* recalculate segment address based on alignment and vm size */
825 s->addr = seg_vmsize;
826 /* we need section alignment to calculate final section address */
827 if (s->align == -1)
828 s->align = DEFAULT_SECTION_ALIGNMENT;
829 if(s->align) {
830 uint32_t newaddr = ALIGN(s->addr, 1 << s->align);
831 pad = newaddr - s->addr;
832 s->addr = newaddr;
835 seg_vmsize += s->size + pad;
836 ++seg_nsects;
839 /* calculate size of all headers, load commands and sections to
840 ** get a pointer to the start of all the raw data */
841 if (seg_nsects > 0) {
842 ++head_ncmds;
843 head_sizeofcmds +=
844 MACHO_SEGCMD_SIZE + seg_nsects * MACHO_SECTCMD_SIZE;
847 if (nsyms > 0) {
848 ++head_ncmds;
849 head_sizeofcmds += MACHO_SYMCMD_SIZE;
853 /* Write out the header information for the file. */
855 static void macho_write_header (void)
857 fwriteint32_t(MH_MAGIC, ofile); /* magic */
858 fwriteint32_t(CPU_TYPE_I386, ofile); /* CPU type */
859 fwriteint32_t(CPU_SUBTYPE_I386_ALL, ofile); /* CPU subtype */
860 fwriteint32_t(MH_OBJECT, ofile); /* Mach-O file type */
861 fwriteint32_t(head_ncmds, ofile); /* number of load commands */
862 fwriteint32_t(head_sizeofcmds, ofile); /* size of load commands */
863 fwriteint32_t(0, ofile); /* no flags */
866 /* Write out the segment load command at offset. */
868 static uint32_t macho_write_segment (uint32_t offset)
870 uint32_t rel_base = alignint32_t (offset + seg_filesize);
871 uint32_t s_reloff = 0;
872 struct section *s;
874 fwriteint32_t(LC_SEGMENT, ofile); /* cmd == LC_SEGMENT */
876 /* size of load command including section load commands */
877 fwriteint32_t(MACHO_SEGCMD_SIZE + seg_nsects *
878 MACHO_SECTCMD_SIZE, ofile);
880 /* in an MH_OBJECT file all sections are in one unnamed (name
881 ** all zeros) segment */
882 fwritezero(16, ofile);
883 fwriteint32_t(0, ofile); /* in-memory offset */
884 fwriteint32_t(seg_vmsize, ofile); /* in-memory size */
885 fwriteint32_t(offset, ofile); /* in-file offset to data */
886 fwriteint32_t(seg_filesize, ofile); /* in-file size */
887 fwriteint32_t(VM_PROT_DEFAULT, ofile); /* maximum vm protection */
888 fwriteint32_t(VM_PROT_DEFAULT, ofile); /* initial vm protection */
889 fwriteint32_t(seg_nsects, ofile); /* number of sections */
890 fwriteint32_t(0, ofile); /* no flags */
892 /* emit section headers */
893 for (s = sects; s != NULL; s = s->next) {
894 fwrite(s->sectname, sizeof(s->sectname), 1, ofile);
895 fwrite(s->segname, sizeof(s->segname), 1, ofile);
896 fwriteint32_t(s->addr, ofile);
897 fwriteint32_t(s->size, ofile);
899 /* dummy data for zerofill sections or proper values */
900 if ((s->flags & SECTION_TYPE) != S_ZEROFILL) {
901 fwriteint32_t(offset, ofile);
902 /* Write out section alignment, as a power of two.
903 e.g. 32-bit word alignment would be 2 (2^^2 = 4). */
904 if (s->align == -1)
905 s->align = DEFAULT_SECTION_ALIGNMENT;
906 fwriteint32_t(s->align, ofile);
907 /* To be compatible with cctools as we emit
908 a zero reloff if we have no relocations. */
909 fwriteint32_t(s->nreloc ? rel_base + s_reloff : 0, ofile);
910 fwriteint32_t(s->nreloc, ofile);
912 offset += s->size;
913 s_reloff += s->nreloc * MACHO_RELINFO_SIZE;
914 } else {
915 fwriteint32_t(0, ofile);
916 fwriteint32_t(0, ofile);
917 fwriteint32_t(0, ofile);
918 fwriteint32_t(0, ofile);
921 fwriteint32_t(s->flags, ofile); /* flags */
922 fwriteint32_t(0, ofile); /* reserved */
923 fwriteint32_t(0, ofile); /* reserved */
926 rel_padcnt = rel_base - offset;
927 offset = rel_base + s_reloff;
929 return offset;
932 /* For a given chain of relocs r, write out the entire relocation
933 chain to the object file. */
935 static void macho_write_relocs (struct reloc *r)
937 while (r) {
938 uint32_t word2;
940 fwriteint32_t(r->addr, ofile); /* reloc offset */
942 word2 = r->snum;
943 word2 |= r->pcrel << 24;
944 word2 |= r->length << 25;
945 word2 |= r->ext << 27;
946 word2 |= r->type << 28;
947 fwriteint32_t(word2, ofile); /* reloc data */
949 r = r->next;
953 /* Write out the section data. */
954 static void macho_write_section (void)
956 struct section *s, *s2;
957 struct reloc *r;
958 uint8_t fi, *p, *q, blk[4];
959 int32_t l;
961 for (s = sects; s != NULL; s = s->next) {
962 if ((s->flags & SECTION_TYPE) == S_ZEROFILL)
963 continue;
965 /* no padding needs to be done to the sections */
967 /* Like a.out Mach-O references things in the data or bss
968 * sections by addresses which are actually relative to the
969 * start of the _text_ section, in the _file_. See outaout.c
970 * for more information. */
971 saa_rewind(s->data);
972 for (r = s->relocs; r != NULL; r = r->next) {
973 saa_fread(s->data, r->addr, blk, (int32_t)r->length << 1);
974 p = q = blk;
975 l = *p++;
977 /* get offset based on relocation type */
978 if (r->length > 0) {
979 l += ((int32_t)*p++) << 8;
981 if (r->length == 2) {
982 l += ((int32_t)*p++) << 16;
983 l += ((int32_t)*p++) << 24;
987 /* If the relocation is internal add to the current section
988 offset. Otherwise the only value we need is the symbol
989 offset which we already have. The linker takes care
990 of the rest of the address. */
991 if (!r->ext) {
992 /* generate final address by section address and offset */
993 for (s2 = sects, fi = 1;
994 s2 != NULL; s2 = s2->next, fi++) {
995 if (fi == r->snum) {
996 l += s2->addr;
997 break;
1002 /* write new offset back */
1003 if (r->length == 2)
1004 WRITELONG(q, l);
1005 else if (r->length == 1)
1006 WRITESHORT(q, l);
1007 else
1008 *q++ = l & 0xFF;
1010 saa_fwrite(s->data, r->addr, blk, (int32_t)r->length << 1);
1013 /* dump the section data to file */
1014 saa_fpwrite(s->data, ofile);
1017 /* pad last section up to reloc entries on int32_t boundary */
1018 fwritezero(rel_padcnt, ofile);
1020 /* emit relocation entries */
1021 for (s = sects; s != NULL; s = s->next)
1022 macho_write_relocs (s->relocs);
1025 /* Write out the symbol table. We should already have sorted this
1026 before now. */
1027 static void macho_write_symtab (void)
1029 struct symbol *sym;
1030 struct section *s;
1031 int32_t fi;
1032 uint32_t i;
1034 /* we don't need to pad here since MACHO_RELINFO_SIZE == 8 */
1036 for (sym = syms; sym != NULL; sym = sym->next) {
1037 if ((sym->type & N_EXT) == 0) {
1038 fwriteint32_t(sym->strx, ofile); /* string table entry number */
1039 fwrite(&sym->type, 1, 1, ofile); /* symbol type */
1040 fwrite(&sym->sect, 1, 1, ofile); /* section */
1041 fwriteint16_t(sym->desc, ofile); /* description */
1043 /* Fix up the symbol value now that we know the final section
1044 sizes. */
1045 if (((sym->type & N_TYPE) == N_SECT) && (sym->sect != NO_SECT)) {
1046 for (s = sects, fi = 1; s != NULL; s = s->next, fi++) {
1047 if (fi == sym->sect) {
1048 sym->value += s->addr;
1049 break;
1054 fwriteint32_t(sym->value, ofile); /* value (i.e. offset) */
1058 for (i = 0; i < nextdefsym; i++) {
1059 sym = extdefsyms[i];
1060 fwriteint32_t(sym->strx, ofile);
1061 fwrite(&sym->type, 1, 1, ofile); /* symbol type */
1062 fwrite(&sym->sect, 1, 1, ofile); /* section */
1063 fwriteint16_t(sym->desc, ofile); /* description */
1065 /* Fix up the symbol value now that we know the final section
1066 sizes. */
1067 if (((sym->type & N_TYPE) == N_SECT) && (sym->sect != NO_SECT)) {
1068 for (s = sects, fi = 1;
1069 s != NULL && fi < sym->sect; s = s->next, ++fi)
1070 sym->value += s->size;
1073 fwriteint32_t(sym->value, ofile); /* value (i.e. offset) */
1076 for (i = 0; i < nundefsym; i++) {
1077 sym = undefsyms[i];
1078 fwriteint32_t(sym->strx, ofile);
1079 fwrite(&sym->type, 1, 1, ofile); /* symbol type */
1080 fwrite(&sym->sect, 1, 1, ofile); /* section */
1081 fwriteint16_t(sym->desc, ofile); /* description */
1083 /* Fix up the symbol value now that we know the final section
1084 sizes. */
1085 if (((sym->type & N_TYPE) == N_SECT) && (sym->sect != NO_SECT)) {
1086 for (s = sects, fi = 1;
1087 s != NULL && fi < sym->sect; s = s->next, ++fi)
1088 sym->value += s->size;
1091 fwriteint32_t(sym->value, ofile); /* value (i.e. offset) */
1095 /* Fixup the snum in the relocation entries, we should be
1096 doing this only for externally undefined symbols. */
1097 static void macho_fixup_relocs (struct reloc *r)
1099 struct symbol *sym;
1100 uint32_t i;
1102 while (r != NULL) {
1103 if (r->ext) {
1104 for (i = 0; i < nundefsym; i++) {
1105 sym = undefsyms[i];
1106 if (sym->initial_snum == r->snum) {
1107 r->snum = sym->snum;
1108 break;
1112 r = r->next;
1116 /* Write out the object file. */
1118 static void macho_write (void)
1120 uint32_t offset = 0;
1122 /* mach-o object file structure:
1124 ** mach header
1125 ** uint32_t magic
1126 ** int cpu type
1127 ** int cpu subtype
1128 ** uint32_t mach file type
1129 ** uint32_t number of load commands
1130 ** uint32_t size of all load commands
1131 ** (includes section struct size of segment command)
1132 ** uint32_t flags
1134 ** segment command
1135 ** uint32_t command type == LC_SEGMENT
1136 ** uint32_t size of load command
1137 ** (including section load commands)
1138 ** char[16] segment name
1139 ** uint32_t in-memory offset
1140 ** uint32_t in-memory size
1141 ** uint32_t in-file offset to data area
1142 ** uint32_t in-file size
1143 ** (in-memory size excluding zerofill sections)
1144 ** int maximum vm protection
1145 ** int initial vm protection
1146 ** uint32_t number of sections
1147 ** uint32_t flags
1149 ** section commands
1150 ** char[16] section name
1151 ** char[16] segment name
1152 ** uint32_t in-memory offset
1153 ** uint32_t in-memory size
1154 ** uint32_t in-file offset
1155 ** uint32_t alignment
1156 ** (irrelevant in MH_OBJECT)
1157 ** uint32_t in-file offset of relocation entires
1158 ** uint32_t number of relocations
1159 ** uint32_t flags
1160 ** uint32_t reserved
1161 ** uint32_t reserved
1163 ** symbol table command
1164 ** uint32_t command type == LC_SYMTAB
1165 ** uint32_t size of load command
1166 ** uint32_t symbol table offset
1167 ** uint32_t number of symbol table entries
1168 ** uint32_t string table offset
1169 ** uint32_t string table size
1171 ** raw section data
1173 ** padding to int32_t boundary
1175 ** relocation data (struct reloc)
1176 ** int32_t offset
1177 ** uint data (symbolnum, pcrel, length, extern, type)
1179 ** symbol table data (struct nlist)
1180 ** int32_t string table entry number
1181 ** uint8_t type
1182 ** (extern, absolute, defined in section)
1183 ** uint8_t section
1184 ** (0 for global symbols, section number of definition (>= 1, <=
1185 ** 254) for local symbols, size of variable for common symbols
1186 ** [type == extern])
1187 ** int16_t description
1188 ** (for stab debugging format)
1189 ** uint32_t value (i.e. file offset) of symbol or stab offset
1191 ** string table data
1192 ** list of null-terminated strings
1195 /* Emit the Mach-O header. */
1196 macho_write_header();
1198 offset = MACHO_HEADER_SIZE + head_sizeofcmds;
1200 /* emit the segment load command */
1201 if (seg_nsects > 0)
1202 offset = macho_write_segment (offset);
1203 else
1204 nasm_error(ERR_WARNING, "no sections?");
1206 if (nsyms > 0) {
1207 /* write out symbol command */
1208 fwriteint32_t(LC_SYMTAB, ofile); /* cmd == LC_SYMTAB */
1209 fwriteint32_t(MACHO_SYMCMD_SIZE, ofile); /* size of load command */
1210 fwriteint32_t(offset, ofile); /* symbol table offset */
1211 fwriteint32_t(nsyms, ofile); /* number of symbol
1212 ** table entries */
1214 offset += nsyms * MACHO_NLIST_SIZE;
1215 fwriteint32_t(offset, ofile); /* string table offset */
1216 fwriteint32_t(strslen, ofile); /* string table size */
1219 /* emit section data */
1220 if (seg_nsects > 0)
1221 macho_write_section ();
1223 /* emit symbol table if we have symbols */
1224 if (nsyms > 0)
1225 macho_write_symtab ();
1227 /* we don't need to pad here since MACHO_NLIST_SIZE == 12 */
1229 /* emit string table */
1230 saa_fpwrite(strs, ofile);
1232 /* We do quite a bit here, starting with finalizing all of the data
1233 for the object file, writing, and then freeing all of the data from
1234 the file. */
1236 static void macho_cleanup(int debuginfo)
1238 struct section *s;
1239 struct reloc *r;
1240 struct symbol *sym;
1242 (void)debuginfo;
1244 /* Sort all symbols. */
1245 macho_layout_symbols (&nsyms, &strslen);
1247 /* Fixup relocation entries */
1248 for (s = sects; s != NULL; s = s->next) {
1249 macho_fixup_relocs (s->relocs);
1252 /* First calculate and finalize needed values. */
1253 macho_calculate_sizes();
1254 macho_write();
1256 /* free up everything */
1257 while (sects->next) {
1258 s = sects;
1259 sects = sects->next;
1261 saa_free(s->data);
1262 while (s->relocs != NULL) {
1263 r = s->relocs;
1264 s->relocs = s->relocs->next;
1265 nasm_free(r);
1268 nasm_free(s);
1271 saa_free(strs);
1272 raa_free(extsyms);
1274 if (syms) {
1275 while (syms->next) {
1276 sym = syms;
1277 syms = syms->next;
1279 nasm_free (sym);
1284 /* Debugging routines. */
1285 static void debug_reloc (struct reloc *r)
1287 fprintf (stdout, "reloc:\n");
1288 fprintf (stdout, "\taddr: %"PRId32"\n", r->addr);
1289 fprintf (stdout, "\tsnum: %d\n", r->snum);
1290 fprintf (stdout, "\tpcrel: %d\n", r->pcrel);
1291 fprintf (stdout, "\tlength: %d\n", r->length);
1292 fprintf (stdout, "\text: %d\n", r->ext);
1293 fprintf (stdout, "\ttype: %d\n", r->type);
1296 static void debug_section_relocs (struct section *s)
1298 struct reloc *r = s->relocs;
1300 fprintf (stdout, "relocs for section %s:\n\n", s->sectname);
1302 while (r != NULL) {
1303 debug_reloc (r);
1304 r = r->next;
1308 struct ofmt of_macho32 = {
1309 "NeXTstep/OpenStep/Rhapsody/Darwin/MacOS X (i386) object files",
1310 "macho32",
1312 null_debug_arr,
1313 &null_debug_form,
1314 macho_stdmac,
1315 macho_init,
1316 null_setinfo,
1317 macho_output,
1318 macho_symdef,
1319 macho_section,
1320 null_sectalign,
1321 macho_segbase,
1322 null_directive,
1323 macho_filename,
1324 macho_cleanup
1327 #endif
1330 * Local Variables:
1331 * mode:c
1332 * c-basic-offset:4
1333 * End:
1335 * end of file */