NASM 2.10rc5
[nasm/avx512.git] / output / outcoff.c
blob6c72806394e442fcf594cb4dc13daa3caed45948
1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2010 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 * outcoff.c output routines for the Netwide Assembler to produce
36 * COFF object files (for DJGPP and Win32)
39 #include "compiler.h"
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <ctype.h>
45 #include <time.h>
46 #include <inttypes.h>
48 #include "nasm.h"
49 #include "nasmlib.h"
50 #include "saa.h"
51 #include "raa.h"
52 #include "eval.h"
53 #include "output/outform.h"
54 #include "output/outlib.h"
55 #include "output/pecoff.h"
57 #if defined(OF_COFF) || defined(OF_WIN32) || defined(OF_WIN64)
60 * Notes on COFF:
62 * (0) When I say `standard COFF' below, I mean `COFF as output and
63 * used by DJGPP'. I assume DJGPP gets it right.
65 * (1) Win32 appears to interpret the term `relative relocation'
66 * differently from standard COFF. Standard COFF understands a
67 * relative relocation to mean that during relocation you add the
68 * address of the symbol you're referencing, and subtract the base
69 * address of the section you're in. Win32 COFF, by contrast, seems
70 * to add the address of the symbol and then subtract the address
71 * of THE BYTE AFTER THE RELOCATED DWORD. Hence the two formats are
72 * subtly incompatible.
74 * (2) Win32 doesn't bother putting any flags in the header flags
75 * field (at offset 0x12 into the file).
77 * (3) Win32 uses some extra flags into the section header table:
78 * it defines flags 0x80000000 (writable), 0x40000000 (readable)
79 * and 0x20000000 (executable), and uses them in the expected
80 * combinations. It also defines 0x00100000 through 0x00700000 for
81 * section alignments of 1 through 64 bytes.
83 * (4) Both standard COFF and Win32 COFF seem to use the DWORD
84 * field directly after the section name in the section header
85 * table for something strange: they store what the address of the
86 * section start point _would_ be, if you laid all the sections end
87 * to end starting at zero. Dunno why. Microsoft's documentation
88 * lists this field as "Virtual Size of Section", which doesn't
89 * seem to fit at all. In fact, Win32 even includes non-linked
90 * sections such as .drectve in this calculation.
92 * Newer versions of MASM seem to have changed this to be zero, and
93 * that apparently matches the COFF spec, so go with that.
95 * (5) Standard COFF does something very strange to common
96 * variables: the relocation point for a common variable is as far
97 * _before_ the variable as its size stretches out _after_ it. So
98 * we must fix up common variable references. Win32 seems to be
99 * sensible on this one.
102 /* Flag which version of COFF we are currently outputting. */
103 static bool win32, win64;
105 static int32_t imagebase_sect;
106 #define WRT_IMAGEBASE "..imagebase"
108 struct Reloc {
109 struct Reloc *next;
110 int32_t address; /* relative to _start_ of section */
111 int32_t symbol; /* symbol number */
112 enum {
113 SECT_SYMBOLS,
114 ABS_SYMBOL,
115 REAL_SYMBOLS
116 } symbase; /* relocation for symbol number :) */
117 int16_t type;
120 struct Symbol {
121 char name[9];
122 int32_t strpos; /* string table position of name */
123 int32_t value; /* address, or COMMON variable size */
124 int section; /* section number where it's defined
125 * - in COFF codes, not NASM codes */
126 bool is_global; /* is it a global symbol or not? */
127 int16_t type; /* 0 - notype, 0x20 - function */
128 int32_t namlen; /* full name length */
131 static char coff_infile[FILENAME_MAX];
133 struct Section {
134 struct SAA *data;
135 uint32_t len;
136 int nrelocs;
137 int32_t index;
138 struct Reloc *head, **tail;
139 uint32_t flags; /* section flags */
140 char name[9];
141 int32_t pos, relpos;
145 * Some common section flags by default
147 #define TEXT_FLAGS_WIN \
148 (IMAGE_SCN_CNT_CODE | \
149 IMAGE_SCN_ALIGN_16BYTES | \
150 IMAGE_SCN_MEM_EXECUTE | \
151 IMAGE_SCN_MEM_READ)
152 #define TEXT_FLAGS_DOS \
153 (IMAGE_SCN_CNT_CODE)
155 #define DATA_FLAGS_WIN \
156 (IMAGE_SCN_CNT_INITIALIZED_DATA | \
157 IMAGE_SCN_ALIGN_4BYTES | \
158 IMAGE_SCN_MEM_READ | \
159 IMAGE_SCN_MEM_WRITE)
160 #define DATA_FLAGS_DOS \
161 (IMAGE_SCN_CNT_INITIALIZED_DATA)
163 #define BSS_FLAGS_WIN \
164 (IMAGE_SCN_CNT_UNINITIALIZED_DATA | \
165 IMAGE_SCN_ALIGN_4BYTES | \
166 IMAGE_SCN_MEM_READ | \
167 IMAGE_SCN_MEM_WRITE)
168 #define BSS_FLAGS_DOS \
169 (IMAGE_SCN_CNT_UNINITIALIZED_DATA)
171 #define RDATA_FLAGS_WIN \
172 (IMAGE_SCN_CNT_INITIALIZED_DATA | \
173 IMAGE_SCN_ALIGN_8BYTES | \
174 IMAGE_SCN_MEM_READ)
176 #define RDATA_FLAGS_DOS \
177 (IMAGE_SCN_CNT_INITIALIZED_DATA)
179 #define PDATA_FLAGS \
180 (IMAGE_SCN_CNT_INITIALIZED_DATA | \
181 IMAGE_SCN_ALIGN_4BYTES | \
182 IMAGE_SCN_MEM_READ)
184 #define XDATA_FLAGS \
185 (IMAGE_SCN_CNT_INITIALIZED_DATA | \
186 IMAGE_SCN_ALIGN_8BYTES | \
187 IMAGE_SCN_MEM_READ)
189 #define INFO_FLAGS \
190 (IMAGE_SCN_ALIGN_1BYTES | \
191 IMAGE_SCN_LNK_INFO | \
192 IMAGE_SCN_LNK_REMOVE)
194 #define TEXT_FLAGS ((win32 | win64) ? TEXT_FLAGS_WIN : TEXT_FLAGS_DOS)
195 #define DATA_FLAGS ((win32 | win64) ? DATA_FLAGS_WIN : DATA_FLAGS_DOS)
196 #define BSS_FLAGS ((win32 | win64) ? BSS_FLAGS_WIN : BSS_FLAGS_DOS)
197 #define RDATA_FLAGS ((win32 | win64) ? RDATA_FLAGS_WIN : RDATA_FLAGS_DOS)
199 #define SECT_DELTA 32
200 static struct Section **sects;
201 static int nsects, sectlen;
203 static struct SAA *syms;
204 static uint32_t nsyms;
206 static int32_t def_seg;
208 static int initsym;
210 static struct RAA *bsym, *symval;
212 static struct SAA *strs;
213 static uint32_t strslen;
215 static void coff_gen_init(void);
216 static void coff_sect_write(struct Section *, const uint8_t *, uint32_t);
217 static void coff_write(void);
218 static void coff_section_header(char *, int32_t, int32_t, int32_t, int32_t, int, int32_t);
219 static void coff_write_relocs(struct Section *);
220 static void coff_write_symbols(void);
222 static void coff_win32_init(void)
224 win32 = true;
225 win64 = false;
226 coff_gen_init();
229 static void coff_win64_init(void)
231 maxbits = 64;
232 win32 = false;
233 win64 = true;
234 coff_gen_init();
235 imagebase_sect = seg_alloc()+1;
236 define_label(WRT_IMAGEBASE, imagebase_sect, 0, NULL, false, false);
239 static void coff_std_init(void)
241 win32 = win64 = false;
242 coff_gen_init();
245 static void coff_gen_init(void)
248 sects = NULL;
249 nsects = sectlen = 0;
250 syms = saa_init(sizeof(struct Symbol));
251 nsyms = 0;
252 bsym = raa_init();
253 symval = raa_init();
254 strs = saa_init(1);
255 strslen = 0;
256 def_seg = seg_alloc();
259 static void coff_cleanup(int debuginfo)
261 struct Reloc *r;
262 int i;
264 (void)debuginfo;
266 coff_write();
267 for (i = 0; i < nsects; i++) {
268 if (sects[i]->data)
269 saa_free(sects[i]->data);
270 while (sects[i]->head) {
271 r = sects[i]->head;
272 sects[i]->head = sects[i]->head->next;
273 nasm_free(r);
275 nasm_free(sects[i]);
277 nasm_free(sects);
278 saa_free(syms);
279 raa_free(bsym);
280 raa_free(symval);
281 saa_free(strs);
284 static int coff_make_section(char *name, uint32_t flags)
286 struct Section *s;
288 s = nasm_zalloc(sizeof(*s));
290 if (flags != BSS_FLAGS)
291 s->data = saa_init(1);
292 s->tail = &s->head;
293 if (!strcmp(name, ".text"))
294 s->index = def_seg;
295 else
296 s->index = seg_alloc();
297 strncpy(s->name, name, 8);
298 s->name[8] = '\0';
299 s->flags = flags;
301 if (nsects >= sectlen) {
302 sectlen += SECT_DELTA;
303 sects = nasm_realloc(sects, sectlen * sizeof(*sects));
305 sects[nsects++] = s;
307 return nsects - 1;
310 static inline int32_t coff_sectalign_flags(unsigned int align)
312 return (ilog2_32(align) + 1) << 20;
315 static int32_t coff_section_names(char *name, int pass, int *bits)
317 char *p;
318 uint32_t flags, align_and = ~0L, align_or = 0L;
319 int i;
322 * Set default bits.
324 if (!name) {
325 if(win64)
326 *bits = 64;
327 else
328 *bits = 32;
331 if (!name)
332 return def_seg;
334 p = name;
335 while (*p && !nasm_isspace(*p))
336 p++;
337 if (*p)
338 *p++ = '\0';
339 if (strlen(name) > 8) {
340 nasm_error(ERR_WARNING, "COFF section names limited to 8 characters:"
341 " truncating");
342 name[8] = '\0';
344 flags = 0;
346 while (*p && nasm_isspace(*p))
347 p++;
348 while (*p) {
349 char *q = p;
350 while (*p && !nasm_isspace(*p))
351 p++;
352 if (*p)
353 *p++ = '\0';
354 while (*p && nasm_isspace(*p))
355 p++;
357 if (!nasm_stricmp(q, "code") || !nasm_stricmp(q, "text")) {
358 flags = TEXT_FLAGS;
359 } else if (!nasm_stricmp(q, "data")) {
360 flags = DATA_FLAGS;
361 } else if (!nasm_stricmp(q, "rdata")) {
362 if (win32 | win64)
363 flags = RDATA_FLAGS;
364 else {
365 flags = DATA_FLAGS; /* gotta do something */
366 nasm_error(ERR_NONFATAL, "standard COFF does not support"
367 " read-only data sections");
369 } else if (!nasm_stricmp(q, "bss")) {
370 flags = BSS_FLAGS;
371 } else if (!nasm_stricmp(q, "info")) {
372 if (win32 | win64)
373 flags = INFO_FLAGS;
374 else {
375 flags = DATA_FLAGS; /* gotta do something */
376 nasm_error(ERR_NONFATAL, "standard COFF does not support"
377 " informational sections");
379 } else if (!nasm_strnicmp(q, "align=", 6)) {
380 if (!(win32 | win64))
381 nasm_error(ERR_NONFATAL, "standard COFF does not support"
382 " section alignment specification");
383 else {
384 if (q[6 + strspn(q + 6, "0123456789")])
385 nasm_error(ERR_NONFATAL,
386 "argument to `align' is not numeric");
387 else {
388 unsigned int align = atoi(q + 6);
389 if (!align || ((align - 1) & align))
390 nasm_error(ERR_NONFATAL, "argument to `align' is not a"
391 " power of two");
392 else if (align > 64)
393 nasm_error(ERR_NONFATAL, "Win32 cannot align sections"
394 " to better than 64-byte boundaries");
395 else {
396 align_and = ~0x00F00000L;
397 align_or = coff_sectalign_flags(align);
404 for (i = 0; i < nsects; i++)
405 if (!strcmp(name, sects[i]->name))
406 break;
407 if (i == nsects) {
408 if (!flags) {
409 if (!strcmp(name, ".data"))
410 flags = DATA_FLAGS;
411 else if (!strcmp(name, ".rdata"))
412 flags = RDATA_FLAGS;
413 else if (!strcmp(name, ".bss"))
414 flags = BSS_FLAGS;
415 else if (win64 && !strcmp(name, ".pdata"))
416 flags = PDATA_FLAGS;
417 else if (win64 && !strcmp(name, ".xdata"))
418 flags = XDATA_FLAGS;
419 else
420 flags = TEXT_FLAGS;
422 i = coff_make_section(name, flags);
423 if (flags)
424 sects[i]->flags = flags;
425 sects[i]->flags &= align_and;
426 sects[i]->flags |= align_or;
427 } else if (pass == 1) {
428 if (flags)
429 nasm_error(ERR_WARNING, "section attributes ignored on"
430 " redeclaration of section `%s'", name);
433 return sects[i]->index;
436 static void coff_deflabel(char *name, int32_t segment, int64_t offset,
437 int is_global, char *special)
439 int pos = strslen + 4;
440 struct Symbol *sym;
442 if (special)
443 nasm_error(ERR_NONFATAL, "COFF format does not support any"
444 " special symbol types");
446 if (name[0] == '.' && name[1] == '.' && name[2] != '@') {
447 if (strcmp(name,WRT_IMAGEBASE))
448 nasm_error(ERR_NONFATAL, "unrecognized special symbol `%s'", name);
449 return;
452 if (strlen(name) > 8) {
453 size_t nlen = strlen(name)+1;
454 saa_wbytes(strs, name, nlen);
455 strslen += nlen;
456 } else
457 pos = -1;
459 sym = saa_wstruct(syms);
461 sym->strpos = pos;
462 sym->namlen = strlen(name);
463 if (pos == -1)
464 strcpy(sym->name, name);
465 sym->is_global = !!is_global;
466 sym->type = 0; /* Default to T_NULL (no type) */
467 if (segment == NO_SEG)
468 sym->section = -1; /* absolute symbol */
469 else {
470 int i;
471 sym->section = 0;
472 for (i = 0; i < nsects; i++)
473 if (segment == sects[i]->index) {
474 sym->section = i + 1;
475 break;
477 if (!sym->section)
478 sym->is_global = true;
480 if (is_global == 2)
481 sym->value = offset;
482 else
483 sym->value = (sym->section == 0 ? 0 : offset);
486 * define the references from external-symbol segment numbers
487 * to these symbol records.
489 if (sym->section == 0)
490 bsym = raa_write(bsym, segment, nsyms);
492 if (segment != NO_SEG)
493 symval = raa_write(symval, segment, sym->section ? 0 : sym->value);
495 nsyms++;
498 static int32_t coff_add_reloc(struct Section *sect, int32_t segment,
499 int16_t type)
501 struct Reloc *r;
503 r = *sect->tail = nasm_malloc(sizeof(struct Reloc));
504 sect->tail = &r->next;
505 r->next = NULL;
507 r->address = sect->len;
508 if (segment == NO_SEG) {
509 r->symbol = 0, r->symbase = ABS_SYMBOL;
510 } else {
511 int i;
512 r->symbase = REAL_SYMBOLS;
513 for (i = 0; i < nsects; i++) {
514 if (segment == sects[i]->index) {
515 r->symbol = i * 2;
516 r->symbase = SECT_SYMBOLS;
517 break;
520 if (r->symbase == REAL_SYMBOLS)
521 r->symbol = raa_read(bsym, segment);
523 r->type = type;
525 sect->nrelocs++;
528 * Return the fixup for standard COFF common variables.
530 if (r->symbase == REAL_SYMBOLS && !(win32 | win64))
531 return raa_read(symval, segment);
533 return 0;
536 static void coff_out(int32_t segto, const void *data,
537 enum out_type type, uint64_t size,
538 int32_t segment, int32_t wrt)
540 struct Section *s;
541 uint8_t mydata[8], *p;
542 int i;
544 if (wrt != NO_SEG && !win64) {
545 wrt = NO_SEG; /* continue to do _something_ */
546 nasm_error(ERR_NONFATAL, "WRT not supported by COFF output formats");
550 * handle absolute-assembly (structure definitions)
552 if (segto == NO_SEG) {
553 if (type != OUT_RESERVE)
554 nasm_error(ERR_NONFATAL, "attempt to assemble code in [ABSOLUTE]"
555 " space");
556 return;
559 s = NULL;
560 for (i = 0; i < nsects; i++) {
561 if (segto == sects[i]->index) {
562 s = sects[i];
563 break;
566 if (!s) {
567 int tempint; /* ignored */
568 if (segto != coff_section_names(".text", 2, &tempint))
569 nasm_error(ERR_PANIC, "strange segment conditions in COFF driver");
570 else
571 s = sects[nsects - 1];
574 /* magically default to 'wrt ..imagebase' in .pdata and .xdata */
575 if (win64 && wrt == NO_SEG) {
576 if (!strcmp(s->name,".pdata") || !strcmp(s->name,".xdata"))
577 wrt = imagebase_sect;
580 if (!s->data && type != OUT_RESERVE) {
581 nasm_error(ERR_WARNING, "attempt to initialize memory in"
582 " BSS section `%s': ignored", s->name);
583 s->len += realsize(type, size);
584 return;
587 if (type == OUT_RESERVE) {
588 if (s->data) {
589 nasm_error(ERR_WARNING, "uninitialised space declared in"
590 " non-BSS section `%s': zeroing", s->name);
591 coff_sect_write(s, NULL, size);
592 } else
593 s->len += size;
594 } else if (type == OUT_RAWDATA) {
595 if (segment != NO_SEG)
596 nasm_error(ERR_PANIC, "OUT_RAWDATA with other than NO_SEG");
597 coff_sect_write(s, data, size);
598 } else if (type == OUT_ADDRESS) {
599 if (!(win64)) {
600 if (size != 4 && (segment != NO_SEG || wrt != NO_SEG)) {
601 nasm_error(ERR_NONFATAL, "COFF format does not support non-32-bit"
602 " relocations");
603 } else {
604 int32_t fix = 0;
605 if (segment != NO_SEG || wrt != NO_SEG) {
606 if (wrt != NO_SEG) {
607 nasm_error(ERR_NONFATAL, "COFF format does not support"
608 " WRT types");
609 } else if (segment % 2) {
610 nasm_error(ERR_NONFATAL, "COFF format does not support"
611 " segment base references");
612 } else
613 fix = coff_add_reloc(s, segment, IMAGE_REL_I386_DIR32);
615 p = mydata;
616 WRITELONG(p, *(int64_t *)data + fix);
617 coff_sect_write(s, mydata, size);
619 } else {
620 int32_t fix = 0;
621 p = mydata;
622 if (size == 8) {
623 if (wrt == imagebase_sect) {
624 nasm_error(ERR_NONFATAL, "operand size mismatch: 'wrt "
625 WRT_IMAGEBASE "' is a 32-bit operand");
627 fix = coff_add_reloc(s, segment, IMAGE_REL_AMD64_ADDR64);
628 WRITEDLONG(p, *(int64_t *)data + fix);
629 coff_sect_write(s, mydata, size);
630 } else {
631 fix = coff_add_reloc(s, segment,
632 wrt == imagebase_sect ? IMAGE_REL_AMD64_ADDR32NB:
633 IMAGE_REL_AMD64_ADDR32);
634 WRITELONG(p, *(int64_t *)data + fix);
635 coff_sect_write(s, mydata, size);
638 } else if (type == OUT_REL2ADR) {
639 nasm_error(ERR_NONFATAL, "COFF format does not support 16-bit"
640 " relocations");
641 } else if (type == OUT_REL4ADR) {
642 if (segment == segto && !(win64)) /* Acceptable for RIP-relative */
643 nasm_error(ERR_PANIC, "intra-segment OUT_REL4ADR");
644 else if (segment == NO_SEG && win32)
645 nasm_error(ERR_NONFATAL, "Win32 COFF does not correctly support"
646 " relative references to absolute addresses");
647 else {
648 int32_t fix = 0;
649 if (segment != NO_SEG && segment % 2) {
650 nasm_error(ERR_NONFATAL, "COFF format does not support"
651 " segment base references");
652 } else
653 fix = coff_add_reloc(s, segment,
654 win64 ? IMAGE_REL_AMD64_REL32 : IMAGE_REL_I386_REL32);
655 p = mydata;
656 if (win32 | win64) {
657 WRITELONG(p, *(int64_t *)data + 4 - size + fix);
658 } else {
659 WRITELONG(p, *(int64_t *)data - (size + s->len) + fix);
661 coff_sect_write(s, mydata, 4L);
667 static void coff_sect_write(struct Section *sect,
668 const uint8_t *data, uint32_t len)
670 saa_wbytes(sect->data, data, len);
671 sect->len += len;
674 typedef struct tagString {
675 struct tagString *next;
676 int len;
677 char *String;
678 } STRING;
680 #define EXPORT_SECTION_NAME ".drectve"
681 #define EXPORT_SECTION_FLAGS INFO_FLAGS
683 * #define EXPORT_SECTION_NAME ".text"
684 * #define EXPORT_SECTION_FLAGS TEXT_FLAGS
687 static STRING *Exports = NULL;
688 static struct Section *directive_sec;
689 void AddExport(char *name)
691 STRING *rvp = Exports, *newS;
693 newS = (STRING *) nasm_malloc(sizeof(STRING));
694 newS->len = strlen(name);
695 newS->next = NULL;
696 newS->String = (char *)nasm_malloc(newS->len + 1);
697 strcpy(newS->String, name);
698 if (rvp == NULL) {
699 int i;
701 for (i = 0; i < nsects; i++) {
702 if (!strcmp(EXPORT_SECTION_NAME, sects[i]->name))
703 break;
706 if (i == nsects)
707 i = coff_make_section(EXPORT_SECTION_NAME, EXPORT_SECTION_FLAGS);
709 directive_sec = sects[i];
710 Exports = newS;
711 } else {
712 while (rvp->next) {
713 if (!strcmp(rvp->String, name))
714 return;
715 rvp = rvp->next;
717 rvp->next = newS;
721 static void BuildExportTable(STRING **rvp)
723 STRING *p, *t;
725 if (!rvp || !*rvp)
726 return;
728 list_for_each_safe(p, t, *rvp) {
729 coff_sect_write(directive_sec, (uint8_t *)"-export:", 8);
730 coff_sect_write(directive_sec, (uint8_t *)p->String, p->len);
731 coff_sect_write(directive_sec, (uint8_t *)" ", 1);
732 nasm_free(p->String);
733 nasm_free(p);
736 *rvp = NULL;
739 static int coff_directives(enum directives directive, char *value, int pass)
741 switch (directive) {
742 case D_EXPORT:
744 char *q, *name;
746 if (pass == 2)
747 return 1; /* ignore in pass two */
748 name = q = value;
749 while (*q && !nasm_isspace(*q))
750 q++;
751 if (nasm_isspace(*q)) {
752 *q++ = '\0';
753 while (*q && nasm_isspace(*q))
754 q++;
757 if (!*name) {
758 nasm_error(ERR_NONFATAL, "`export' directive requires export name");
759 return 1;
761 if (*q) {
762 nasm_error(ERR_NONFATAL, "unrecognized export qualifier `%s'", q);
763 return 1;
765 AddExport(name);
766 return 1;
768 case D_SAFESEH:
770 static int sxseg=-1;
771 int i;
773 if (!win32) /* Only applicable for -f win32 */
774 return 0;
776 if (sxseg == -1) {
777 for (i = 0; i < nsects; i++)
778 if (!strcmp(".sxdata",sects[i]->name))
779 break;
780 if (i == nsects)
781 sxseg = coff_make_section(".sxdata", IMAGE_SCN_LNK_INFO);
782 else
783 sxseg = i;
786 * pass0 == 2 is the only time when the full set of symbols are
787 * guaranteed to be present; it is the final output pass.
789 if (pass0 == 2) {
790 uint32_t n;
791 saa_rewind(syms);
792 for (n = 0; n < nsyms; n++) {
793 struct Symbol *sym = saa_rstruct(syms);
794 bool equals;
797 * sym->strpos is biased by 4, because symbol
798 * table is prefixed with table length
800 if (sym->strpos >=4) {
801 char *name = nasm_malloc(sym->namlen+1);
802 saa_fread(strs, sym->strpos-4, name, sym->namlen);
803 name[sym->namlen] = '\0';
804 equals = !strcmp(value,name);
805 nasm_free(name);
806 } else {
807 equals = !strcmp(value,sym->name);
810 if (equals) {
812 * this value arithmetics effectively reflects
813 * initsym in coff_write(): 2 for file, 1 for
814 * .absolute and two per each section
816 unsigned char value[4],*p=value;
817 WRITELONG(p,n + 2 + 1 + nsects*2);
818 coff_sect_write(sects[sxseg],value,4);
819 sym->type = 0x20;
820 break;
823 if (n == nsyms) {
824 nasm_error(ERR_NONFATAL,
825 "`safeseh' directive requires valid symbol");
828 return 1;
830 default:
831 return 0;
835 /* handle relocations storm, valid for win32/64 only */
836 static inline void coff_adjust_relocs(struct Section *s)
838 if (s->nrelocs < IMAGE_SCN_MAX_RELOC)
839 return;
840 #ifdef OF_COFF
841 else
843 if (ofmt == &of_coff)
844 nasm_error(ERR_FATAL,
845 "Too many relocations (%d) for section `%s'",
846 s->nrelocs, s->name);
848 #endif
850 s->flags |= IMAGE_SCN_LNK_NRELOC_OVFL;
851 s->nrelocs++;
854 static void coff_write(void)
856 int32_t pos, sympos, vsize;
857 int i;
859 /* fill in the .drectve section with -export's */
860 BuildExportTable(&Exports);
862 if (win32) {
863 /* add default value for @feat.00, this allows to 'link /safeseh' */
864 uint32_t n;
866 saa_rewind(syms);
867 for (n = 0; n < nsyms; n++) {
868 struct Symbol *sym = saa_rstruct(syms);
869 if (sym->strpos == -1 && !strcmp("@feat.00",sym->name))
870 break;
872 if (n == nsyms)
873 coff_deflabel("@feat.00", NO_SEG, 1, 0, NULL);
877 * Work out how big the file will get.
878 * Calculate the start of the `real' symbols at the same time.
879 * Check for massive relocations.
881 pos = 0x14 + 0x28 * nsects;
882 initsym = 3; /* two for the file, one absolute */
883 for (i = 0; i < nsects; i++) {
884 if (sects[i]->data) {
885 coff_adjust_relocs(sects[i]);
886 sects[i]->pos = pos;
887 pos += sects[i]->len;
888 sects[i]->relpos = pos;
889 pos += 10 * sects[i]->nrelocs;
890 } else
891 sects[i]->pos = sects[i]->relpos = 0L;
892 initsym += 2; /* two for each section */
894 sympos = pos;
897 * Output the COFF header.
899 if (win64)
900 i = IMAGE_FILE_MACHINE_AMD64;
901 else
902 i = IMAGE_FILE_MACHINE_I386;
903 fwriteint16_t(i, ofile); /* machine type */
904 fwriteint16_t(nsects, ofile); /* number of sections */
905 fwriteint32_t(time(NULL), ofile); /* time stamp */
906 fwriteint32_t(sympos, ofile);
907 fwriteint32_t(nsyms + initsym, ofile);
908 fwriteint16_t(0, ofile); /* no optional header */
909 /* Flags: 32-bit, no line numbers. Win32 doesn't even bother with them. */
910 fwriteint16_t((win32 | win64) ? 0 : 0x104, ofile);
913 * Output the section headers.
915 vsize = 0L;
916 for (i = 0; i < nsects; i++) {
917 coff_section_header(sects[i]->name, vsize, sects[i]->len,
918 sects[i]->pos, sects[i]->relpos,
919 sects[i]->nrelocs, sects[i]->flags);
920 vsize += sects[i]->len;
924 * Output the sections and their relocations.
926 for (i = 0; i < nsects; i++)
927 if (sects[i]->data) {
928 saa_fpwrite(sects[i]->data, ofile);
929 coff_write_relocs(sects[i]);
933 * Output the symbol and string tables.
935 coff_write_symbols();
936 fwriteint32_t(strslen + 4, ofile); /* length includes length count */
937 saa_fpwrite(strs, ofile);
940 static void coff_section_header(char *name, int32_t vsize,
941 int32_t datalen, int32_t datapos,
942 int32_t relpos, int nrelocs, int32_t flags)
944 char padname[8];
946 (void)vsize;
948 memset(padname, 0, 8);
949 strncpy(padname, name, 8);
950 fwrite(padname, 8, 1, ofile);
952 fwriteint32_t(0, ofile); /* Virtual size field - set to 0 or vsize */
953 fwriteint32_t(0L, ofile); /* RVA/offset - we ignore */
954 fwriteint32_t(datalen, ofile);
955 fwriteint32_t(datapos, ofile);
956 fwriteint32_t(relpos, ofile);
957 fwriteint32_t(0L, ofile); /* no line numbers - we don't do 'em */
960 * a special case -- if there are too many relocs
961 * we have to put IMAGE_SCN_MAX_RELOC here and write
962 * the real relocs number into VirtualAddress of first
963 * relocation
965 if (flags & IMAGE_SCN_LNK_NRELOC_OVFL)
966 fwriteint16_t(IMAGE_SCN_MAX_RELOC, ofile);
967 else
968 fwriteint16_t(nrelocs, ofile);
970 fwriteint16_t(0, ofile); /* again, no line numbers */
971 fwriteint32_t(flags, ofile);
974 static void coff_write_relocs(struct Section *s)
976 struct Reloc *r;
978 /* a real number of relocations if needed */
979 if (s->flags & IMAGE_SCN_LNK_NRELOC_OVFL) {
980 fwriteint32_t(s->nrelocs, ofile);
981 fwriteint32_t(0, ofile);
982 fwriteint16_t(0, ofile);
985 for (r = s->head; r; r = r->next) {
986 fwriteint32_t(r->address, ofile);
987 fwriteint32_t(r->symbol + (r->symbase == REAL_SYMBOLS ? initsym :
988 r->symbase == ABS_SYMBOL ? initsym - 1 :
989 r->symbase == SECT_SYMBOLS ? 2 : 0),
990 ofile);
991 fwriteint16_t(r->type, ofile);
995 static void coff_symbol(char *name, int32_t strpos, int32_t value,
996 int section, int type, int storageclass, int aux)
998 char padname[8];
1000 if (name) {
1001 memset(padname, 0, 8);
1002 strncpy(padname, name, 8);
1003 fwrite(padname, 8, 1, ofile);
1004 } else {
1005 fwriteint32_t(0, ofile);
1006 fwriteint32_t(strpos, ofile);
1009 fwriteint32_t(value, ofile);
1010 fwriteint16_t(section, ofile);
1011 fwriteint16_t(type, ofile);
1013 fputc(storageclass, ofile);
1014 fputc(aux, ofile);
1017 static void coff_write_symbols(void)
1019 char filename[18];
1020 uint32_t i;
1023 * The `.file' record, and the file name auxiliary record.
1025 coff_symbol(".file", 0L, 0L, -2, 0, 0x67, 1);
1026 memset(filename, 0, 18);
1027 strncpy(filename, coff_infile, 18);
1028 fwrite(filename, 18, 1, ofile);
1031 * The section records, with their auxiliaries.
1033 memset(filename, 0, 18); /* useful zeroed buffer */
1035 for (i = 0; i < (uint32_t) nsects; i++) {
1036 coff_symbol(sects[i]->name, 0L, 0L, i + 1, 0, 3, 1);
1037 fwriteint32_t(sects[i]->len, ofile);
1038 fwriteint16_t(sects[i]->nrelocs,ofile);
1039 fwrite(filename, 12, 1, ofile);
1043 * The absolute symbol, for relative-to-absolute relocations.
1045 coff_symbol(".absolut", 0L, 0L, -1, 0, 3, 0);
1048 * The real symbols.
1050 saa_rewind(syms);
1051 for (i = 0; i < nsyms; i++) {
1052 struct Symbol *sym = saa_rstruct(syms);
1053 coff_symbol(sym->strpos == -1 ? sym->name : NULL,
1054 sym->strpos, sym->value, sym->section,
1055 sym->type, sym->is_global ? 2 : 3, 0);
1059 static void coff_sectalign(int32_t seg, unsigned int value)
1061 struct Section *s = NULL;
1062 uint32_t align;
1063 int i;
1065 for (i = 0; i < nsects; i++) {
1066 if (sects[i]->index == seg) {
1067 s = sects[i];
1068 break;
1072 if (!s || !is_power2(value))
1073 return;
1075 /* DOS has limitation on 64 bytes */
1076 if (!(win32 | win64) && value > 64)
1077 return;
1079 align = (s->flags & IMAGE_SCN_ALIGN_MASK);
1080 value = coff_sectalign_flags(value);
1081 if (value > align)
1082 s->flags = (s->flags & ~IMAGE_SCN_ALIGN_MASK) | value;
1085 static int32_t coff_segbase(int32_t segment)
1087 return segment;
1090 static void coff_std_filename(char *inname, char *outname)
1092 strcpy(coff_infile, inname);
1093 standard_extension(inname, outname, ".o");
1096 static void coff_win32_filename(char *inname, char *outname)
1098 strcpy(coff_infile, inname);
1099 standard_extension(inname, outname, ".obj");
1102 extern macros_t coff_stdmac[];
1104 static int coff_set_info(enum geninfo type, char **val)
1106 (void)type;
1107 (void)val;
1108 return 0;
1110 #endif /* defined(OF_COFF) || defined(OF_WIN32) */
1112 #ifdef OF_COFF
1114 struct ofmt of_coff = {
1115 "COFF (i386) object files (e.g. DJGPP for DOS)",
1116 "coff",
1118 null_debug_arr,
1119 &null_debug_form,
1120 coff_stdmac,
1121 coff_std_init,
1122 coff_set_info,
1123 coff_out,
1124 coff_deflabel,
1125 coff_section_names,
1126 coff_sectalign,
1127 coff_segbase,
1128 coff_directives,
1129 coff_std_filename,
1130 coff_cleanup
1133 #endif
1135 #ifdef OF_WIN32
1137 struct ofmt of_win32 = {
1138 "Microsoft Win32 (i386) object files",
1139 "win32",
1141 null_debug_arr,
1142 &null_debug_form,
1143 coff_stdmac,
1144 coff_win32_init,
1145 coff_set_info,
1146 coff_out,
1147 coff_deflabel,
1148 coff_section_names,
1149 coff_sectalign,
1150 coff_segbase,
1151 coff_directives,
1152 coff_win32_filename,
1153 coff_cleanup
1156 #endif
1158 #ifdef OF_WIN64
1160 struct ofmt of_win64 = {
1161 "Microsoft Win64 (x86-64) object files",
1162 "win64",
1164 null_debug_arr,
1165 &null_debug_form,
1166 coff_stdmac,
1167 coff_win64_init,
1168 coff_set_info,
1169 coff_out,
1170 coff_deflabel,
1171 coff_section_names,
1172 coff_sectalign,
1173 coff_segbase,
1174 coff_directives,
1175 coff_win32_filename,
1176 coff_cleanup
1179 #endif