1 /* outcoff.c output routines for the Netwide Assembler to produce
2 * COFF object files (for DJGPP and Win32)
4 * The Netwide Assembler is copyright (C) 1996 Simon Tatham and
5 * Julian Hall. All rights reserved. The software is
6 * redistributable under the licence given in the file "Licence"
7 * distributed in the NASM archive.
23 #if defined(OF_COFF) || defined(OF_WIN32) || defined(OF_WIN64)
28 * (0) When I say `standard COFF' below, I mean `COFF as output and
29 * used by DJGPP'. I assume DJGPP gets it right.
31 * (1) Win32 appears to interpret the term `relative relocation'
32 * differently from standard COFF. Standard COFF understands a
33 * relative relocation to mean that during relocation you add the
34 * address of the symbol you're referencing, and subtract the base
35 * address of the section you're in. Win32 COFF, by contrast, seems
36 * to add the address of the symbol and then subtract the address
37 * of THE BYTE AFTER THE RELOCATED DWORD. Hence the two formats are
38 * subtly incompatible.
40 * (2) Win32 doesn't bother putting any flags in the header flags
41 * field (at offset 0x12 into the file).
43 * (3) Win32 uses some extra flags into the section header table:
44 * it defines flags 0x80000000 (writable), 0x40000000 (readable)
45 * and 0x20000000 (executable), and uses them in the expected
46 * combinations. It also defines 0x00100000 through 0x00700000 for
47 * section alignments of 1 through 64 bytes.
49 * (4) Both standard COFF and Win32 COFF seem to use the DWORD
50 * field directly after the section name in the section header
51 * table for something strange: they store what the address of the
52 * section start point _would_ be, if you laid all the sections end
53 * to end starting at zero. Dunno why. Microsoft's documentation
54 * lists this field as "Virtual Size of Section", which doesn't
55 * seem to fit at all. In fact, Win32 even includes non-linked
56 * sections such as .drectve in this calculation.
58 * Newer versions of MASM seem to have changed this to be zero, and
59 * that apparently matches the COFF spec, so go with that.
61 * (5) Standard COFF does something very strange to common
62 * variables: the relocation point for a common variable is as far
63 * _before_ the variable as its size stretches out _after_ it. So
64 * we must fix up common variable references. Win32 seems to be
65 * sensible on this one.
68 /* Flag which version of COFF we are currently outputting. */
69 static bool win32, win64;
73 int32_t address; /* relative to _start_ of section */
74 int32_t symbol; /* symbol number */
79 } symbase; /* relocation for symbol number :) */
86 int32_t strpos; /* string table position of name */
87 int32_t value; /* address, or COMMON variable size */
88 int section; /* section number where it's defined
89 * - in COFF codes, not NASM codes */
90 bool is_global; /* is it a global symbol or not? */
95 static char coff_infile[FILENAME_MAX];
102 struct Reloc *head, **tail;
103 uint32_t flags; /* section flags */
108 #define TEXT_FLAGS ((win32 | win64) ? 0x60500020L : 0x20L)
109 #define DATA_FLAGS ((win32 | win64) ? 0xC0300040L : 0x40L)
110 #define BSS_FLAGS ((win32 | win64) ? 0xC0300080L : 0x80L)
111 #define INFO_FLAGS 0x00100A00L
112 #define RDATA_FLAGS ((win32 | win64) ? 0x40400040L : 0x40L)
114 #define SECT_DELTA 32
115 static struct Section **sects;
116 static int nsects, sectlen;
118 static struct SAA *syms;
119 static uint32_t nsyms;
121 static int32_t def_seg;
125 static struct RAA *bsym, *symval;
127 static struct SAA *strs;
128 static uint32_t strslen;
130 static void coff_gen_init(FILE *, efunc);
131 static void coff_sect_write(struct Section *, const uint8_t *,
133 static void coff_write(void);
134 static void coff_section_header(char *, int32_t, int32_t, int32_t, int32_t, int, int32_t);
135 static void coff_write_relocs(struct Section *);
136 static void coff_write_symbols(void);
138 static void coff_win32_init(FILE * fp, efunc errfunc,
139 ldfunc ldef, evalfunc eval)
141 win32 = true; win64 = false;
142 (void)ldef; /* placate optimizers */
144 coff_gen_init(fp, errfunc);
147 static void coff_win64_init(FILE * fp, efunc errfunc,
148 ldfunc ldef, evalfunc eval)
151 win32 = false; win64 = true;
152 (void)ldef; /* placate optimizers */
154 coff_gen_init(fp, errfunc);
157 static void coff_std_init(FILE * fp, efunc errfunc, ldfunc ldef,
160 win32 = win64 = false;
161 (void)ldef; /* placate optimizers */
163 coff_gen_init(fp, errfunc);
166 static void coff_gen_init(FILE * fp, efunc errfunc)
172 nsects = sectlen = 0;
173 syms = saa_init((int32_t)sizeof(struct Symbol));
179 def_seg = seg_alloc();
182 static void coff_cleanup(int debuginfo)
191 for (i = 0; i < nsects; i++) {
193 saa_free(sects[i]->data);
194 while (sects[i]->head) {
196 sects[i]->head = sects[i]->head->next;
208 static int coff_make_section(char *name, uint32_t flags)
212 s = nasm_malloc(sizeof(*s));
214 if (flags != BSS_FLAGS)
215 s->data = saa_init(1L);
222 if (!strcmp(name, ".text"))
225 s->index = seg_alloc();
226 strncpy(s->name, name, 8);
230 if (nsects >= sectlen)
232 nasm_realloc(sects, (sectlen += SECT_DELTA) * sizeof(*sects));
238 static int32_t coff_section_names(char *name, int pass, int *bits)
241 uint32_t flags, align_and = ~0L, align_or = 0L;
258 while (*p && !isspace(*p))
262 if (strlen(name) > 8) {
263 error(ERR_WARNING, "COFF section names limited to 8 characters:"
269 while (*p && isspace(*p))
273 while (*p && !isspace(*p))
277 while (*p && isspace(*p))
280 if (!nasm_stricmp(q, "code") || !nasm_stricmp(q, "text")) {
282 } else if (!nasm_stricmp(q, "data")) {
284 } else if (!nasm_stricmp(q, "rdata")) {
288 flags = DATA_FLAGS; /* gotta do something */
289 error(ERR_NONFATAL, "standard COFF does not support"
290 " read-only data sections");
292 } else if (!nasm_stricmp(q, "bss")) {
294 } else if (!nasm_stricmp(q, "info")) {
298 flags = DATA_FLAGS; /* gotta do something */
299 error(ERR_NONFATAL, "standard COFF does not support"
300 " informational sections");
302 } else if (!nasm_strnicmp(q, "align=", 6)) {
303 if (!(win32 | win64))
304 error(ERR_NONFATAL, "standard COFF does not support"
305 " section alignment specification");
307 if (q[6 + strspn(q + 6, "0123456789")])
309 "argument to `align' is not numeric");
311 unsigned int align = atoi(q + 6);
312 if (!align || ((align - 1) & align))
313 error(ERR_NONFATAL, "argument to `align' is not a"
316 error(ERR_NONFATAL, "Win32 cannot align sections"
317 " to better than 64-byte boundaries");
319 align_and = ~0x00F00000L;
320 align_or = (align == 1 ? 0x00100000L :
321 align == 2 ? 0x00200000L :
322 align == 4 ? 0x00300000L :
323 align == 8 ? 0x00400000L :
324 align == 16 ? 0x00500000L :
326 32 ? 0x00600000L : 0x00700000L);
333 for (i = 0; i < nsects; i++)
334 if (!strcmp(name, sects[i]->name))
338 if (!strcmp(name, ".data"))
340 else if (!strcmp(name, ".rdata"))
342 else if (!strcmp(name, ".bss"))
347 i = coff_make_section(name, flags);
349 sects[i]->flags = flags;
350 sects[i]->flags &= align_and;
351 sects[i]->flags |= align_or;
352 } else if (pass == 1) {
354 error(ERR_WARNING, "section attributes ignored on"
355 " redeclaration of section `%s'", name);
358 return sects[i]->index;
361 static void coff_deflabel(char *name, int32_t segment, int32_t offset,
362 int is_global, char *special)
364 int pos = strslen + 4;
368 error(ERR_NONFATAL, "binary format does not support any"
369 " special symbol types");
371 if (name[0] == '.' && name[1] == '.' && name[2] != '@') {
372 error(ERR_NONFATAL, "unrecognized special symbol `%s'", name);
376 if (strlen(name) > 8) {
377 saa_wbytes(strs, name, (int32_t)(1 + strlen(name)));
378 strslen += 1 + strlen(name);
382 sym = saa_wstruct(syms);
386 strcpy(sym->name, name);
387 sym->is_global = !!is_global;
388 if (segment == NO_SEG)
389 sym->section = -1; /* absolute symbol */
393 for (i = 0; i < nsects; i++)
394 if (segment == sects[i]->index) {
395 sym->section = i + 1;
399 sym->is_global = true;
404 sym->value = (sym->section == 0 ? 0 : offset);
407 * define the references from external-symbol segment numbers
408 * to these symbol records.
410 if (sym->section == 0) {
411 bsym = raa_write(bsym, segment, nsyms);
414 if (segment != NO_SEG)
415 symval = raa_write(symval, segment, sym->section ? 0 : sym->value);
420 static int32_t coff_add_reloc(struct Section *sect, int32_t segment,
421 int relative, int size64)
427 r = *sect->tail = nasm_malloc(sizeof(struct Reloc));
428 sect->tail = &r->next;
431 r->address = sect->len;
432 if (segment == NO_SEG)
433 r->symbol = 0, r->symbase = ABS_SYMBOL;
436 r->symbase = REAL_SYMBOLS;
437 for (i = 0; i < nsects; i++)
438 if (segment == sects[i]->index) {
440 r->symbase = SECT_SYMBOLS;
443 if (r->symbase == REAL_SYMBOLS)
444 r->symbol = raa_read(bsym, segment);
446 r->relative = relative;
451 * Return the fixup for standard COFF common variables.
453 if (r->symbase == REAL_SYMBOLS && !(win32 | win64))
454 return raa_read(symval, segment);
459 static void coff_out(int32_t segto, const void *data, uint32_t type,
460 int32_t segment, int32_t wrt)
463 int32_t realbytes = type & OUT_SIZMASK;
464 uint8_t mydata[8], *p;
468 wrt = NO_SEG; /* continue to do _something_ */
469 error(ERR_NONFATAL, "WRT not supported by COFF output formats");
475 * handle absolute-assembly (structure definitions)
477 if (segto == NO_SEG) {
478 if (type != OUT_RESERVE)
479 error(ERR_NONFATAL, "attempt to assemble code in [ABSOLUTE]"
485 for (i = 0; i < nsects; i++)
486 if (segto == sects[i]->index) {
491 int tempint; /* ignored */
492 if (segto != coff_section_names(".text", 2, &tempint))
493 error(ERR_PANIC, "strange segment conditions in COFF driver");
495 s = sects[nsects - 1];
498 if (!s->data && type != OUT_RESERVE) {
499 error(ERR_WARNING, "attempt to initialize memory in"
500 " BSS section `%s': ignored", s->name);
501 if (type == OUT_REL2ADR)
503 else if (type == OUT_REL4ADR)
509 if (type == OUT_RESERVE) {
511 error(ERR_WARNING, "uninitialised space declared in"
512 " non-BSS section `%s': zeroing", s->name);
513 coff_sect_write(s, NULL, realbytes);
516 } else if (type == OUT_RAWDATA) {
517 if (segment != NO_SEG)
518 error(ERR_PANIC, "OUT_RAWDATA with other than NO_SEG");
519 coff_sect_write(s, data, realbytes);
520 } else if (type == OUT_ADDRESS) {
522 if (realbytes != 4 && (segment != NO_SEG || wrt != NO_SEG))
523 error(ERR_NONFATAL, "COFF format does not support non-32-bit"
527 if (segment != NO_SEG || wrt != NO_SEG) {
529 error(ERR_NONFATAL, "COFF format does not support"
531 } else if (segment % 2) {
532 error(ERR_NONFATAL, "COFF format does not support"
533 " segment base references");
535 fix = coff_add_reloc(s, segment, false, false);
538 WRITELONG(p, *(int32_t *)data + fix);
539 coff_sect_write(s, mydata, realbytes);
544 if (realbytes == 8) {
545 /* if (segment != NO_SEG || wrt != NO_SEG) {
547 error(ERR_NONFATAL, "COFF format does not support"
549 } else if (segment % 2) {
550 error(ERR_NONFATAL, "COFF format does not support"
551 " segment base references");
553 fix = coff_add_reloc(s, segment, false);
555 fix = coff_add_reloc(s, segment, false, true);
556 WRITEDLONG(p, *(int64_t *)data + fix);
557 coff_sect_write(s, mydata, realbytes);
559 fix = coff_add_reloc(s, segment, false, false);
560 WRITELONG(p, *(int32_t *)data + fix);
561 coff_sect_write(s, mydata, realbytes);
564 } else if (type == OUT_REL2ADR) {
565 error(ERR_NONFATAL, "COFF format does not support 16-bit"
567 } else if (type == OUT_REL4ADR) {
568 if (segment == segto && !(win64)) /* Acceptable for RIP-relative */
569 error(ERR_PANIC, "intra-segment OUT_REL4ADR");
570 else if (segment == NO_SEG && win32)
571 error(ERR_NONFATAL, "Win32 COFF does not correctly support"
572 " relative references to absolute addresses");
575 if (segment != NO_SEG && segment % 2) {
576 error(ERR_NONFATAL, "COFF format does not support"
577 " segment base references");
579 fix = coff_add_reloc(s, segment, true, false);
582 WRITELONG(p, *(int32_t *)data + 4 - realbytes + fix);
584 WRITELONG(p, *(int32_t *)data - (realbytes + s->len) + fix);
586 coff_sect_write(s, mydata, 4L);
592 static void coff_sect_write(struct Section *sect,
593 const uint8_t *data, uint32_t len)
595 saa_wbytes(sect->data, data, len);
599 typedef struct tagString {
600 struct tagString *Next;
605 #define EXPORT_SECTION_NAME ".drectve"
606 #define EXPORT_SECTION_FLAGS INFO_FLAGS
608 #define EXPORT_SECTION_NAME ".text"
609 #define EXPORT_SECTION_FLAGS TEXT_FLAGS
612 static STRING *Exports = NULL;
613 static struct Section *directive_sec;
614 void AddExport(char *name)
616 STRING *rvp = Exports, *newS;
618 newS = (STRING *) nasm_malloc(sizeof(STRING));
619 newS->len = strlen(name);
621 newS->String = (char *)nasm_malloc(newS->len + 1);
622 strcpy(newS->String, name);
625 for (i = 0; i < nsects; i++)
627 if (!strcmp(EXPORT_SECTION_NAME, sects[i]->name))
631 sects[coff_make_section
632 (EXPORT_SECTION_NAME, EXPORT_SECTION_FLAGS)];
634 directive_sec = sects[i];
638 if (!strcmp(rvp->String, name))
646 void BuildExportTable(void)
648 STRING *rvp = Exports, *next;
654 len = sprintf((char *)buf, "-export:%s ", rvp->String);
655 coff_sect_write(directive_sec, buf, len);
660 while ((rvp = next)) {
662 nasm_free(rvp->String);
668 static int coff_directives(char *directive, char *value, int pass)
670 if (!strcmp(directive, "export")) {
674 return 1; /* ignore in pass two */
676 while (*q && !isspace(*q))
680 while (*q && isspace(*q))
685 error(ERR_NONFATAL, "`export' directive requires export name");
689 error(ERR_NONFATAL, "unrecognized export qualifier `%s'", q);
698 static void coff_write(void)
700 int32_t pos, sympos, vsize;
703 BuildExportTable(); /* fill in the .drectve section with -export's */
705 * Work out how big the file will get. Calculate the start of
706 * the `real' symbols at the same time.
708 pos = 0x14 + 0x28 * nsects;
709 initsym = 3; /* two for the file, one absolute */
710 for (i = 0; i < nsects; i++) {
711 if (sects[i]->data) {
713 pos += sects[i]->len;
714 sects[i]->relpos = pos;
715 pos += 10 * sects[i]->nrelocs;
717 sects[i]->pos = sects[i]->relpos = 0L;
718 initsym += 2; /* two for each section */
723 * Output the COFF header.
726 fwriteint16_t(0x8664, coffp); /* MACHINE_x86-64 */
728 fwriteint16_t(0x014C, coffp); /* MACHINE_i386 */
729 fwriteint16_t(nsects, coffp); /* number of sections */
730 fwriteint32_t(time(NULL), coffp); /* time stamp */
731 fwriteint32_t(sympos, coffp);
732 fwriteint32_t(nsyms + initsym, coffp);
733 fwriteint16_t(0, coffp); /* no optional header */
734 /* Flags: 32-bit, no line numbers. Win32 doesn't even bother with them. */
735 fwriteint16_t((win32 | win64) ? 0 : 0x104, coffp);
738 * Output the section headers.
741 for (i = 0; i < nsects; i++) {
742 coff_section_header(sects[i]->name, vsize, sects[i]->len,
743 sects[i]->pos, sects[i]->relpos,
744 sects[i]->nrelocs, sects[i]->flags);
745 vsize += sects[i]->len;
749 * Output the sections and their relocations.
751 for (i = 0; i < nsects; i++)
752 if (sects[i]->data) {
753 saa_fpwrite(sects[i]->data, coffp);
754 coff_write_relocs(sects[i]);
758 * Output the symbol and string tables.
760 coff_write_symbols();
761 fwriteint32_t(strslen + 4, coffp); /* length includes length count */
762 saa_fpwrite(strs, coffp);
765 static void coff_section_header(char *name, int32_t vsize,
766 int32_t datalen, int32_t datapos,
767 int32_t relpos, int nrelocs, int32_t flags)
773 memset(padname, 0, 8);
774 strncpy(padname, name, 8);
775 fwrite(padname, 8, 1, coffp);
776 fwriteint32_t(0, coffp); /* Virtual size field - set to 0 or vsize */
777 fwriteint32_t(0L, coffp); /* RVA/offset - we ignore */
778 fwriteint32_t(datalen, coffp);
779 fwriteint32_t(datapos, coffp);
780 fwriteint32_t(relpos, coffp);
781 fwriteint32_t(0L, coffp); /* no line numbers - we don't do 'em */
782 fwriteint16_t(nrelocs, coffp);
783 fwriteint16_t(0, coffp); /* again, no line numbers */
784 fwriteint32_t(flags, coffp);
787 static void coff_write_relocs(struct Section *s)
791 for (r = s->head; r; r = r->next) {
792 fwriteint32_t(r->address, coffp);
793 fwriteint32_t(r->symbol + (r->symbase == REAL_SYMBOLS ? initsym :
794 r->symbase == ABS_SYMBOL ? initsym - 1 :
795 r->symbase == SECT_SYMBOLS ? 2 : 0),
798 * Strange: Microsoft's COFF documentation says 0x03 for an
799 * absolute relocation, but both Visual C++ and DJGPP agree
800 * that in fact it's 0x06. I'll use 0x06 until someone
801 * argues. ***** UPDATE: PE/COFF Ver.8 docs confirm this -kkanios *****
804 fwriteint16_t(r->relative ? 0x04 : r->size64 ? 0x01 : 0x02, coffp);
806 fwriteint16_t(r->relative ? 0x14 : 0x06, coffp);
810 static void coff_symbol(char *name, int32_t strpos, int32_t value,
811 int section, int type, int aux)
816 memset(padname, 0, 8);
817 strncpy(padname, name, 8);
818 fwrite(padname, 8, 1, coffp);
820 fwriteint32_t(0L, coffp);
821 fwriteint32_t(strpos, coffp);
823 fwriteint32_t(value, coffp);
824 fwriteint16_t(section, coffp);
825 fwriteint16_t(0, coffp);
830 static void coff_write_symbols(void)
836 * The `.file' record, and the file name auxiliary record.
838 coff_symbol(".file", 0L, 0L, -2, 0x67, 1);
839 memset(filename, 0, 18);
840 strncpy(filename, coff_infile, 18);
841 fwrite(filename, 18, 1, coffp);
844 * The section records, with their auxiliaries.
846 memset(filename, 0, 18); /* useful zeroed buffer */
848 for (i = 0; i < nsects; i++) {
849 coff_symbol(sects[i]->name, 0L, 0L, i + 1, 3, 1);
850 fwriteint32_t(sects[i]->len, coffp);
851 fwriteint16_t(sects[i]->nrelocs, coffp);
852 fwrite(filename, 12, 1, coffp);
856 * The absolute symbol, for relative-to-absolute relocations.
858 coff_symbol(".absolut", 0L, 0L, -1, 3, 0);
864 for (i = 0; i < nsyms; i++) {
865 struct Symbol *sym = saa_rstruct(syms);
866 coff_symbol(sym->strpos == -1 ? sym->name : NULL,
867 sym->strpos, sym->value, sym->section,
868 sym->is_global ? 2 : 3, 0);
872 static int32_t coff_segbase(int32_t segment)
877 static void coff_std_filename(char *inname, char *outname, efunc error)
879 strcpy(coff_infile, inname);
880 standard_extension(inname, outname, ".o", error);
883 static void coff_win32_filename(char *inname, char *outname, efunc error)
885 strcpy(coff_infile, inname);
886 standard_extension(inname, outname, ".obj", error);
889 static const char *coff_stdmac[] = {
890 "%define __SECT__ [section .text]",
891 "%macro __NASM_CDecl__ 1",
893 "%imacro export 1+.nolist",
899 static int coff_set_info(enum geninfo type, char **val)
905 #endif /* defined(OF_COFF) || defined(OF_WIN32) */
909 struct ofmt of_coff = {
910 "COFF (i386) object files (e.g. DJGPP for DOS)",
931 struct ofmt of_win32 = {
932 "Microsoft Win32 (i386) object files",
953 struct ofmt of_win64 = {
954 "Microsoft Win64 (x86-64) object files",