output: coff -- Use nasm_error helpers
[nasm.git] / output / outcoff.c
blobc23431513c650d2036f3f16a0269646670cee631
1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2017 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>
47 #include "nasm.h"
48 #include "nasmlib.h"
49 #include "ilog2.h"
50 #include "error.h"
51 #include "saa.h"
52 #include "raa.h"
53 #include "eval.h"
54 #include "outform.h"
55 #include "outlib.h"
56 #include "pecoff.h"
58 #if defined(OF_COFF) || defined(OF_WIN32) || defined(OF_WIN64)
61 * Notes on COFF:
63 * (0) When I say `standard COFF' below, I mean `COFF as output and
64 * used by DJGPP'. I assume DJGPP gets it right.
66 * (1) Win32 appears to interpret the term `relative relocation'
67 * differently from standard COFF. Standard COFF understands a
68 * relative relocation to mean that during relocation you add the
69 * address of the symbol you're referencing, and subtract the base
70 * address of the section you're in. Win32 COFF, by contrast, seems
71 * to add the address of the symbol and then subtract the address
72 * of THE BYTE AFTER THE RELOCATED DWORD. Hence the two formats are
73 * subtly incompatible.
75 * (2) Win32 doesn't bother putting any flags in the header flags
76 * field (at offset 0x12 into the file).
78 * (3) Win32 uses some extra flags into the section header table:
79 * it defines flags 0x80000000 (writable), 0x40000000 (readable)
80 * and 0x20000000 (executable), and uses them in the expected
81 * combinations. It also defines 0x00100000 through 0x00700000 for
82 * section alignments of 1 through 64 bytes.
84 * (4) Both standard COFF and Win32 COFF seem to use the DWORD
85 * field directly after the section name in the section header
86 * table for something strange: they store what the address of the
87 * section start point _would_ be, if you laid all the sections end
88 * to end starting at zero. Dunno why. Microsoft's documentation
89 * lists this field as "Virtual Size of Section", which doesn't
90 * seem to fit at all. In fact, Win32 even includes non-linked
91 * sections such as .drectve in this calculation.
93 * Newer versions of MASM seem to have changed this to be zero, and
94 * that apparently matches the COFF spec, so go with that.
96 * (5) Standard COFF does something very strange to common
97 * variables: the relocation point for a common variable is as far
98 * _before_ the variable as its size stretches out _after_ it. So
99 * we must fix up common variable references. Win32 seems to be
100 * sensible on this one.
103 /* Flag which version of COFF we are currently outputting. */
104 bool win32, win64;
106 static int32_t imagebase_sect;
107 #define WRT_IMAGEBASE "..imagebase"
110 * Some common section flags by default
112 #define TEXT_FLAGS_WIN \
113 (IMAGE_SCN_CNT_CODE | \
114 IMAGE_SCN_ALIGN_16BYTES | \
115 IMAGE_SCN_MEM_EXECUTE | \
116 IMAGE_SCN_MEM_READ)
117 #define TEXT_FLAGS_DOS \
118 (IMAGE_SCN_CNT_CODE)
120 #define DATA_FLAGS_WIN \
121 (IMAGE_SCN_CNT_INITIALIZED_DATA | \
122 IMAGE_SCN_ALIGN_4BYTES | \
123 IMAGE_SCN_MEM_READ | \
124 IMAGE_SCN_MEM_WRITE)
125 #define DATA_FLAGS_DOS \
126 (IMAGE_SCN_CNT_INITIALIZED_DATA)
128 #define BSS_FLAGS_WIN \
129 (IMAGE_SCN_CNT_UNINITIALIZED_DATA | \
130 IMAGE_SCN_ALIGN_4BYTES | \
131 IMAGE_SCN_MEM_READ | \
132 IMAGE_SCN_MEM_WRITE)
133 #define BSS_FLAGS_DOS \
134 (IMAGE_SCN_CNT_UNINITIALIZED_DATA)
136 #define RDATA_FLAGS_WIN \
137 (IMAGE_SCN_CNT_INITIALIZED_DATA | \
138 IMAGE_SCN_ALIGN_8BYTES | \
139 IMAGE_SCN_MEM_READ)
141 #define RDATA_FLAGS_DOS \
142 (IMAGE_SCN_CNT_INITIALIZED_DATA)
144 #define PDATA_FLAGS \
145 (IMAGE_SCN_CNT_INITIALIZED_DATA | \
146 IMAGE_SCN_ALIGN_4BYTES | \
147 IMAGE_SCN_MEM_READ)
149 #define XDATA_FLAGS \
150 (IMAGE_SCN_CNT_INITIALIZED_DATA | \
151 IMAGE_SCN_ALIGN_8BYTES | \
152 IMAGE_SCN_MEM_READ)
154 #define INFO_FLAGS \
155 (IMAGE_SCN_ALIGN_1BYTES | \
156 IMAGE_SCN_LNK_INFO | \
157 IMAGE_SCN_LNK_REMOVE)
159 #define TEXT_FLAGS ((win32 | win64) ? TEXT_FLAGS_WIN : TEXT_FLAGS_DOS)
160 #define DATA_FLAGS ((win32 | win64) ? DATA_FLAGS_WIN : DATA_FLAGS_DOS)
161 #define BSS_FLAGS ((win32 | win64) ? BSS_FLAGS_WIN : BSS_FLAGS_DOS)
162 #define RDATA_FLAGS ((win32 | win64) ? RDATA_FLAGS_WIN : RDATA_FLAGS_DOS)
164 #define SECT_DELTA 32
165 struct coff_Section **coff_sects;
166 static int sectlen;
167 int coff_nsects;
169 struct SAA *coff_syms;
170 uint32_t coff_nsyms;
172 static int32_t def_seg;
174 static int initsym;
176 static struct RAA *bsym, *symval;
178 struct SAA *coff_strs;
179 static uint32_t strslen;
181 static void coff_gen_init(void);
182 static void coff_sect_write(struct coff_Section *, const uint8_t *, uint32_t);
183 static void coff_write(void);
184 static void coff_section_header(char *, int32_t, int32_t, int32_t, int32_t, int32_t, int, int32_t);
185 static void coff_write_relocs(struct coff_Section *);
186 static void coff_write_symbols(void);
188 static void coff_win32_init(void)
190 win32 = true;
191 win64 = false;
192 coff_gen_init();
195 static void coff_win64_init(void)
197 win32 = false;
198 win64 = true;
199 coff_gen_init();
200 imagebase_sect = seg_alloc()+1;
201 backend_label(WRT_IMAGEBASE, imagebase_sect, 0);
204 static void coff_std_init(void)
206 win32 = win64 = false;
207 coff_gen_init();
210 static void coff_gen_init(void)
213 coff_sects = NULL;
214 coff_nsects = sectlen = 0;
215 coff_syms = saa_init(sizeof(struct coff_Symbol));
216 coff_nsyms = 0;
217 bsym = raa_init();
218 symval = raa_init();
219 coff_strs = saa_init(1);
220 strslen = 0;
221 def_seg = seg_alloc();
224 static void coff_cleanup(void)
226 struct coff_Reloc *r;
227 int i;
229 dfmt->cleanup();
231 coff_write();
232 for (i = 0; i < coff_nsects; i++) {
233 if (coff_sects[i]->data)
234 saa_free(coff_sects[i]->data);
235 while (coff_sects[i]->head) {
236 r = coff_sects[i]->head;
237 coff_sects[i]->head = coff_sects[i]->head->next;
238 nasm_free(r);
240 nasm_free(coff_sects[i]->name);
241 nasm_free(coff_sects[i]);
243 nasm_free(coff_sects);
244 saa_free(coff_syms);
245 raa_free(bsym);
246 raa_free(symval);
247 saa_free(coff_strs);
250 int coff_make_section(char *name, uint32_t flags)
252 struct coff_Section *s;
253 size_t namelen;
255 s = nasm_zalloc(sizeof(*s));
257 if (flags != BSS_FLAGS)
258 s->data = saa_init(1);
259 s->tail = &s->head;
260 if (!strcmp(name, ".text"))
261 s->index = def_seg;
262 else
263 s->index = seg_alloc();
264 s->namepos = -1;
265 namelen = strlen(name);
266 if (namelen > 8) {
267 if (win32 || win64) {
268 s->namepos = strslen + 4;
269 saa_wbytes(coff_strs, name, namelen + 1);
270 strslen += namelen + 1;
271 } else {
272 namelen = 8;
275 s->name = nasm_malloc(namelen + 1);
276 strncpy(s->name, name, namelen);
277 s->name[namelen] = '\0';
278 s->flags = flags;
280 if (coff_nsects >= sectlen) {
281 sectlen += SECT_DELTA;
282 coff_sects = nasm_realloc(coff_sects, sectlen * sizeof(*coff_sects));
284 coff_sects[coff_nsects++] = s;
286 return coff_nsects - 1;
289 static inline int32_t coff_sectalign_flags(unsigned int align)
291 return (ilog2_32(align) + 1) << 20;
294 static int32_t coff_section_names(char *name, int pass, int *bits)
296 char *p;
297 uint32_t flags, align_and = ~0L, align_or = 0L;
298 int i;
301 * Set default bits.
303 if (!name) {
304 if(win64)
305 *bits = 64;
306 else
307 *bits = 32;
309 return def_seg;
312 p = name;
313 while (*p && !nasm_isspace(*p))
314 p++;
315 if (*p)
316 *p++ = '\0';
317 if (strlen(name) > 8) {
318 if (!win32 && !win64) {
319 nasm_warn("COFF section names limited to 8 characters: truncating");
320 name[8] = '\0';
323 flags = 0;
325 while (*p && nasm_isspace(*p))
326 p++;
327 while (*p) {
328 char *q = p;
329 while (*p && !nasm_isspace(*p))
330 p++;
331 if (*p)
332 *p++ = '\0';
333 while (*p && nasm_isspace(*p))
334 p++;
336 if (!nasm_stricmp(q, "code") || !nasm_stricmp(q, "text")) {
337 flags = TEXT_FLAGS;
338 } else if (!nasm_stricmp(q, "data")) {
339 flags = DATA_FLAGS;
340 } else if (!nasm_stricmp(q, "rdata")) {
341 if (win32 | win64)
342 flags = RDATA_FLAGS;
343 else {
344 flags = DATA_FLAGS; /* gotta do something */
345 nasm_nonfatal("standard COFF does not support"
346 " read-only data sections");
348 } else if (!nasm_stricmp(q, "bss")) {
349 flags = BSS_FLAGS;
350 } else if (!nasm_stricmp(q, "info")) {
351 if (win32 | win64)
352 flags = INFO_FLAGS;
353 else {
354 flags = DATA_FLAGS; /* gotta do something */
355 nasm_nonfatal("standard COFF does not support"
356 " informational sections");
358 } else if (!nasm_strnicmp(q, "align=", 6)) {
359 if (!(win32 | win64))
360 nasm_nonfatal("standard COFF does not support"
361 " section alignment specification");
362 else {
363 if (q[6 + strspn(q + 6, "0123456789")])
364 nasm_nonfatal("argument to `align' is not numeric");
365 else {
366 unsigned int align = atoi(q + 6);
367 if (!align || ((align - 1) & align))
368 nasm_nonfatal("argument to `align' is not a"
369 " power of two");
370 else if (align > 64)
371 nasm_nonfatal("Win32 cannot align sections"
372 " to better than 64-byte boundaries");
373 else {
374 align_and = ~0x00F00000L;
375 align_or = coff_sectalign_flags(align);
382 for (i = 0; i < coff_nsects; i++)
383 if (!strcmp(name, coff_sects[i]->name))
384 break;
385 if (i == coff_nsects) {
386 if (!flags) {
387 if (!strcmp(name, ".data"))
388 flags = DATA_FLAGS;
389 else if (!strcmp(name, ".rdata"))
390 flags = RDATA_FLAGS;
391 else if (!strcmp(name, ".bss"))
392 flags = BSS_FLAGS;
393 else if (win64 && !strcmp(name, ".pdata"))
394 flags = PDATA_FLAGS;
395 else if (win64 && !strcmp(name, ".xdata"))
396 flags = XDATA_FLAGS;
397 else
398 flags = TEXT_FLAGS;
400 i = coff_make_section(name, flags);
401 if (flags)
402 coff_sects[i]->flags = flags;
403 coff_sects[i]->flags &= align_and;
404 coff_sects[i]->flags |= align_or;
405 } else if (pass == 1) {
406 /* Check if any flags are specified */
407 if (flags) {
408 unsigned int align_flags = flags & IMAGE_SCN_ALIGN_MASK;
410 /* Warn if non-alignment flags differ */
411 if ((flags ^ coff_sects[i]->flags) & ~IMAGE_SCN_ALIGN_MASK) {
412 nasm_warn("section attributes ignored on"
413 " redeclaration of section `%s'", name);
415 /* Check if alignment might be needed */
416 if (align_flags > IMAGE_SCN_ALIGN_1BYTES) {
417 unsigned int sect_align_flags = coff_sects[i]->flags & IMAGE_SCN_ALIGN_MASK;
419 /* Compute the actual alignment */
420 unsigned int align = 1u << ((align_flags - IMAGE_SCN_ALIGN_1BYTES) >> 20);
422 /* Update section header as needed */
423 if (align_flags > sect_align_flags) {
424 coff_sects[i]->flags = (coff_sects[i]->flags & ~IMAGE_SCN_ALIGN_MASK) | align_flags;
426 /* Check if not already aligned */
427 if (coff_sects[i]->len % align) {
428 unsigned int padding = (align - coff_sects[i]->len) % align;
429 /* We need to write at most 8095 bytes */
430 char buffer[8095];
431 if (coff_sects[i]->flags & IMAGE_SCN_CNT_CODE) {
432 /* Fill with INT 3 instructions */
433 memset(buffer, 0xCC, padding);
434 } else {
435 memset(buffer, 0x00, padding);
437 saa_wbytes(coff_sects[i]->data, buffer, padding);
438 coff_sects[i]->len += padding;
444 return coff_sects[i]->index;
447 static void coff_deflabel(char *name, int32_t segment, int64_t offset,
448 int is_global, char *special)
450 int pos = strslen + 4;
451 struct coff_Symbol *sym;
453 if (special)
454 nasm_nonfatal("COFF format does not support any"
455 " special symbol types");
457 if (name[0] == '.' && name[1] == '.' && name[2] != '@') {
458 if (strcmp(name,WRT_IMAGEBASE))
459 nasm_nonfatal("unrecognized special symbol `%s'", name);
460 return;
463 if (strlen(name) > 8) {
464 size_t nlen = strlen(name)+1;
465 saa_wbytes(coff_strs, name, nlen);
466 strslen += nlen;
467 } else
468 pos = -1;
470 sym = saa_wstruct(coff_syms);
472 sym->strpos = pos;
473 sym->namlen = strlen(name);
474 if (pos == -1)
475 strcpy(sym->name, name);
476 sym->is_global = !!is_global;
477 sym->type = 0; /* Default to T_NULL (no type) */
478 if (segment == NO_SEG)
479 sym->section = -1; /* absolute symbol */
480 else {
481 int i;
482 sym->section = 0;
483 for (i = 0; i < coff_nsects; i++)
484 if (segment == coff_sects[i]->index) {
485 sym->section = i + 1;
486 break;
488 if (!sym->section)
489 sym->is_global = true;
491 if (is_global == 2)
492 sym->value = offset;
493 else
494 sym->value = (sym->section == 0 ? 0 : offset);
497 * define the references from external-symbol segment numbers
498 * to these symbol records.
500 if (sym->section == 0)
501 bsym = raa_write(bsym, segment, coff_nsyms);
503 if (segment != NO_SEG)
504 symval = raa_write(symval, segment, sym->section ? 0 : sym->value);
506 coff_nsyms++;
509 static int32_t coff_add_reloc(struct coff_Section *sect, int32_t segment,
510 int16_t type)
512 struct coff_Reloc *r;
514 r = *sect->tail = nasm_malloc(sizeof(struct coff_Reloc));
515 sect->tail = &r->next;
516 r->next = NULL;
518 r->address = sect->len;
519 if (segment == NO_SEG) {
520 r->symbol = 0, r->symbase = ABS_SYMBOL;
521 } else {
522 int i;
523 r->symbase = REAL_SYMBOLS;
524 for (i = 0; i < coff_nsects; i++) {
525 if (segment == coff_sects[i]->index) {
526 r->symbol = i * 2;
527 r->symbase = SECT_SYMBOLS;
528 break;
531 if (r->symbase == REAL_SYMBOLS)
532 r->symbol = raa_read(bsym, segment);
534 r->type = type;
536 sect->nrelocs++;
539 * Return the fixup for standard COFF common variables.
541 if (r->symbase == REAL_SYMBOLS && !(win32 | win64))
542 return raa_read(symval, segment);
544 return 0;
547 static void coff_out(int32_t segto, const void *data,
548 enum out_type type, uint64_t size,
549 int32_t segment, int32_t wrt)
551 struct coff_Section *s;
552 uint8_t mydata[8], *p;
553 int i;
555 if (wrt != NO_SEG && !win64) {
556 wrt = NO_SEG; /* continue to do _something_ */
557 nasm_nonfatal("WRT not supported by COFF output formats");
560 s = NULL;
561 for (i = 0; i < coff_nsects; i++) {
562 if (segto == coff_sects[i]->index) {
563 s = coff_sects[i];
564 break;
567 if (!s) {
568 int tempint; /* ignored */
569 if (segto != coff_section_names(".text", 2, &tempint))
570 nasm_panic("strange segment conditions in COFF driver");
571 else
572 s = coff_sects[coff_nsects - 1];
575 /* magically default to 'wrt ..imagebase' in .pdata and .xdata */
576 if (win64 && wrt == NO_SEG) {
577 if (!strcmp(s->name,".pdata") || !strcmp(s->name,".xdata"))
578 wrt = imagebase_sect;
581 if (!s->data && type != OUT_RESERVE) {
582 nasm_warn("attempt to initialize memory in"
583 " BSS section `%s': ignored", s->name);
584 s->len += realsize(type, size);
585 return;
588 memset(mydata, 0, sizeof(mydata));
590 if (dfmt && dfmt->debug_output) {
591 struct coff_DebugInfo dinfo;
592 dinfo.segto = segto;
593 dinfo.seg = segment;
594 dinfo.section = s;
596 if (type == OUT_ADDRESS)
597 dinfo.size = abs((int)size);
598 else
599 dinfo.size = realsize(type, size);
601 dfmt->debug_output(type, &dinfo);
604 if (type == OUT_RESERVE) {
605 if (s->data) {
606 nasm_warn("uninitialised space declared in"
607 " non-BSS section `%s': zeroing", s->name);
608 coff_sect_write(s, NULL, size);
609 } else
610 s->len += size;
611 } else if (type == OUT_RAWDATA) {
612 coff_sect_write(s, data, size);
613 } else if (type == OUT_ADDRESS) {
614 int asize = abs((int)size);
615 if (!win64) {
616 if (asize != 4 && (segment != NO_SEG || wrt != NO_SEG)) {
617 nasm_nonfatal("COFF format does not support non-32-bit"
618 " relocations");
619 } else {
620 int32_t fix = 0;
621 if (segment != NO_SEG || wrt != NO_SEG) {
622 if (wrt != NO_SEG) {
623 nasm_nonfatal("COFF format does not support WRT types");
624 } else if (segment % 2) {
625 nasm_nonfatal("COFF format does not support"
626 " segment base references");
627 } else
628 fix = coff_add_reloc(s, segment, IMAGE_REL_I386_DIR32);
630 p = mydata;
631 WRITELONG(p, *(int64_t *)data + fix);
632 coff_sect_write(s, mydata, asize);
634 } else {
635 int32_t fix = 0;
636 p = mydata;
637 if (asize == 8) {
638 if (wrt == imagebase_sect) {
639 nasm_nonfatal("operand size mismatch: 'wrt "
640 WRT_IMAGEBASE "' is a 32-bit operand");
642 fix = coff_add_reloc(s, segment, IMAGE_REL_AMD64_ADDR64);
643 WRITEDLONG(p, *(int64_t *)data + fix);
644 coff_sect_write(s, mydata, asize);
645 } else {
646 fix = coff_add_reloc(s, segment,
647 wrt == imagebase_sect ? IMAGE_REL_AMD64_ADDR32NB:
648 IMAGE_REL_AMD64_ADDR32);
649 WRITELONG(p, *(int64_t *)data + fix);
650 coff_sect_write(s, mydata, asize);
653 } else if (type == OUT_REL2ADR) {
654 nasm_nonfatal("COFF format does not support 16-bit relocations");
655 } else if (type == OUT_REL4ADR) {
656 if (segment == segto && !(win64)) /* Acceptable for RIP-relative */
657 nasm_panic("intra-segment OUT_REL4ADR");
658 else if (segment == NO_SEG && win32)
659 nasm_nonfatal("Win32 COFF does not correctly support"
660 " relative references to absolute addresses");
661 else {
662 int32_t fix = 0;
663 if (segment != NO_SEG && segment % 2) {
664 nasm_nonfatal("COFF format does not support"
665 " segment base references");
666 } else
667 fix = coff_add_reloc(s, segment,
668 win64 ? IMAGE_REL_AMD64_REL32 : IMAGE_REL_I386_REL32);
669 p = mydata;
670 if (win32 | win64) {
671 WRITELONG(p, *(int64_t *)data + 4 - size + fix);
672 } else {
673 WRITELONG(p, *(int64_t *)data - (size + s->len) + fix);
675 coff_sect_write(s, mydata, 4L);
681 static void coff_sect_write(struct coff_Section *sect,
682 const uint8_t *data, uint32_t len)
684 saa_wbytes(sect->data, data, len);
685 sect->len += len;
688 typedef struct tagString {
689 struct tagString *next;
690 int len;
691 char *String;
692 } STRING;
694 #define EXPORT_SECTION_NAME ".drectve"
695 #define EXPORT_SECTION_FLAGS INFO_FLAGS
697 * #define EXPORT_SECTION_NAME ".text"
698 * #define EXPORT_SECTION_FLAGS TEXT_FLAGS
701 static STRING *Exports = NULL;
702 static struct coff_Section *directive_sec;
703 static void AddExport(char *name)
705 STRING *rvp = Exports, *newS;
707 newS = (STRING *) nasm_malloc(sizeof(STRING));
708 newS->len = strlen(name);
709 newS->next = NULL;
710 newS->String = (char *)nasm_malloc(newS->len + 1);
711 strcpy(newS->String, name);
712 if (rvp == NULL) {
713 int i;
715 for (i = 0; i < coff_nsects; i++) {
716 if (!strcmp(EXPORT_SECTION_NAME, coff_sects[i]->name))
717 break;
720 if (i == coff_nsects)
721 i = coff_make_section(EXPORT_SECTION_NAME, EXPORT_SECTION_FLAGS);
723 directive_sec = coff_sects[i];
724 Exports = newS;
725 } else {
726 while (rvp->next) {
727 if (!strcmp(rvp->String, name))
728 return;
729 rvp = rvp->next;
731 rvp->next = newS;
735 static void BuildExportTable(STRING **rvp)
737 STRING *p, *t;
739 if (!rvp || !*rvp)
740 return;
742 list_for_each_safe(p, t, *rvp) {
743 coff_sect_write(directive_sec, (uint8_t *)"-export:", 8);
744 coff_sect_write(directive_sec, (uint8_t *)p->String, p->len);
745 coff_sect_write(directive_sec, (uint8_t *)" ", 1);
746 nasm_free(p->String);
747 nasm_free(p);
750 *rvp = NULL;
753 static enum directive_result
754 coff_directives(enum directive directive, char *value, int pass)
756 switch (directive) {
757 case D_EXPORT:
759 char *q, *name;
761 if (pass == 2)
762 return DIRR_OK; /* ignore in pass two */
763 name = q = value;
764 while (*q && !nasm_isspace(*q))
765 q++;
766 if (nasm_isspace(*q)) {
767 *q++ = '\0';
768 while (*q && nasm_isspace(*q))
769 q++;
772 if (!*name) {
773 nasm_nonfatal("`export' directive requires export name");
774 return DIRR_ERROR;
776 if (*q) {
777 nasm_nonfatal("unrecognized export qualifier `%s'", q);
778 return DIRR_ERROR;
780 AddExport(name);
781 return DIRR_OK;
783 case D_SAFESEH:
785 static int sxseg=-1;
786 int i;
788 if (!win32) /* Only applicable for -f win32 */
789 return 0;
791 if (sxseg == -1) {
792 for (i = 0; i < coff_nsects; i++)
793 if (!strcmp(".sxdata",coff_sects[i]->name))
794 break;
795 if (i == coff_nsects)
796 sxseg = coff_make_section(".sxdata", IMAGE_SCN_LNK_INFO);
797 else
798 sxseg = i;
801 * pass0 == 2 is the only time when the full set of symbols are
802 * guaranteed to be present; it is the final output pass.
804 if (pass0 == 2) {
805 uint32_t n;
806 saa_rewind(coff_syms);
807 for (n = 0; n < coff_nsyms; n++) {
808 struct coff_Symbol *sym = saa_rstruct(coff_syms);
809 bool equals;
812 * sym->strpos is biased by 4, because symbol
813 * table is prefixed with table length
815 if (sym->strpos >=4) {
816 char *name = nasm_malloc(sym->namlen+1);
817 saa_fread(coff_strs, sym->strpos-4, name, sym->namlen);
818 name[sym->namlen] = '\0';
819 equals = !strcmp(value,name);
820 nasm_free(name);
821 } else {
822 equals = !strcmp(value,sym->name);
825 if (equals) {
827 * this value arithmetics effectively reflects
828 * initsym in coff_write(): 2 for file, 1 for
829 * .absolute and two per each section
831 unsigned char value[4],*p=value;
832 WRITELONG(p,n + 2 + 1 + coff_nsects*2);
833 coff_sect_write(coff_sects[sxseg],value,4);
834 sym->type = 0x20;
835 break;
838 if (n == coff_nsyms) {
839 nasm_nonfatal("`safeseh' directive requires valid symbol");
840 return DIRR_ERROR;
843 return DIRR_OK;
845 default:
846 return DIRR_UNKNOWN;
850 /* handle relocations storm, valid for win32/64 only */
851 static inline void coff_adjust_relocs(struct coff_Section *s)
853 if (s->nrelocs < IMAGE_SCN_MAX_RELOC)
854 return;
855 #ifdef OF_COFF
856 else
858 if (ofmt == &of_coff)
859 nasm_fatal("Too many relocations (%d) for section `%s'",
860 s->nrelocs, s->name);
862 #endif
864 s->flags |= IMAGE_SCN_LNK_NRELOC_OVFL;
865 s->nrelocs++;
868 static void coff_write(void)
870 int32_t pos, sympos, vsize;
871 int i;
873 /* fill in the .drectve section with -export's */
874 BuildExportTable(&Exports);
876 if (win32) {
877 /* add default value for @feat.00, this allows to 'link /safeseh' */
878 uint32_t n;
880 saa_rewind(coff_syms);
881 for (n = 0; n < coff_nsyms; n++) {
882 struct coff_Symbol *sym = saa_rstruct(coff_syms);
883 if (sym->strpos == -1 && !strcmp("@feat.00",sym->name))
884 break;
886 if (n == coff_nsyms)
887 coff_deflabel("@feat.00", NO_SEG, 1, 0, NULL);
891 * Work out how big the file will get.
892 * Calculate the start of the `real' symbols at the same time.
893 * Check for massive relocations.
895 pos = 0x14 + 0x28 * coff_nsects;
896 initsym = 3; /* two for the file, one absolute */
897 for (i = 0; i < coff_nsects; i++) {
898 if (coff_sects[i]->data) {
899 coff_adjust_relocs(coff_sects[i]);
900 coff_sects[i]->pos = pos;
901 pos += coff_sects[i]->len;
902 coff_sects[i]->relpos = pos;
903 pos += 10 * coff_sects[i]->nrelocs;
904 } else
905 coff_sects[i]->pos = coff_sects[i]->relpos = 0L;
906 initsym += 2; /* two for each section */
908 sympos = pos;
911 * Output the COFF header.
913 if (win64)
914 i = IMAGE_FILE_MACHINE_AMD64;
915 else
916 i = IMAGE_FILE_MACHINE_I386;
917 fwriteint16_t(i, ofile); /* machine type */
918 fwriteint16_t(coff_nsects, ofile); /* number of sections */
919 fwriteint32_t(time(NULL), ofile); /* time stamp */
920 fwriteint32_t(sympos, ofile);
921 fwriteint32_t(coff_nsyms + initsym, ofile);
922 fwriteint16_t(0, ofile); /* no optional header */
923 /* Flags: 32-bit, no line numbers. Win32 doesn't even bother with them. */
924 fwriteint16_t((win32 | win64) ? 0 : 0x104, ofile);
927 * Output the section headers.
929 vsize = 0L;
930 for (i = 0; i < coff_nsects; i++) {
931 coff_section_header(coff_sects[i]->name, coff_sects[i]->namepos, vsize, coff_sects[i]->len,
932 coff_sects[i]->pos, coff_sects[i]->relpos,
933 coff_sects[i]->nrelocs, coff_sects[i]->flags);
934 vsize += coff_sects[i]->len;
938 * Output the sections and their relocations.
940 for (i = 0; i < coff_nsects; i++)
941 if (coff_sects[i]->data) {
942 saa_fpwrite(coff_sects[i]->data, ofile);
943 coff_write_relocs(coff_sects[i]);
947 * Output the symbol and string tables.
949 coff_write_symbols();
950 fwriteint32_t(strslen + 4, ofile); /* length includes length count */
951 saa_fpwrite(coff_strs, ofile);
954 static void coff_section_header(char *name, int32_t namepos, int32_t vsize,
955 int32_t datalen, int32_t datapos,
956 int32_t relpos, int nrelocs, int32_t flags)
958 char padname[8];
960 (void)vsize;
962 if (namepos == -1) {
963 strncpy(padname, name, 8);
964 nasm_write(padname, 8, ofile);
965 } else {
967 * If name is longer than 8 bytes, write '/' followed
968 * by offset into the strings table represented as
969 * decimal number.
971 namepos = namepos % 100000000;
972 padname[0] = '/';
973 padname[1] = '0' + (namepos / 1000000);
974 namepos = namepos % 1000000;
975 padname[2] = '0' + (namepos / 100000);
976 namepos = namepos % 100000;
977 padname[3] = '0' + (namepos / 10000);
978 namepos = namepos % 10000;
979 padname[4] = '0' + (namepos / 1000);
980 namepos = namepos % 1000;
981 padname[5] = '0' + (namepos / 100);
982 namepos = namepos % 100;
983 padname[6] = '0' + (namepos / 10);
984 namepos = namepos % 10;
985 padname[7] = '0' + (namepos);
986 nasm_write(padname, 8, ofile);
989 fwriteint32_t(0, ofile); /* Virtual size field - set to 0 or vsize */
990 fwriteint32_t(0L, ofile); /* RVA/offset - we ignore */
991 fwriteint32_t(datalen, ofile);
992 fwriteint32_t(datapos, ofile);
993 fwriteint32_t(relpos, ofile);
994 fwriteint32_t(0L, ofile); /* no line numbers - we don't do 'em */
997 * a special case -- if there are too many relocs
998 * we have to put IMAGE_SCN_MAX_RELOC here and write
999 * the real relocs number into VirtualAddress of first
1000 * relocation
1002 if (flags & IMAGE_SCN_LNK_NRELOC_OVFL)
1003 fwriteint16_t(IMAGE_SCN_MAX_RELOC, ofile);
1004 else
1005 fwriteint16_t(nrelocs, ofile);
1007 fwriteint16_t(0, ofile); /* again, no line numbers */
1008 fwriteint32_t(flags, ofile);
1011 static void coff_write_relocs(struct coff_Section *s)
1013 struct coff_Reloc *r;
1015 /* a real number of relocations if needed */
1016 if (s->flags & IMAGE_SCN_LNK_NRELOC_OVFL) {
1017 fwriteint32_t(s->nrelocs, ofile);
1018 fwriteint32_t(0, ofile);
1019 fwriteint16_t(0, ofile);
1022 for (r = s->head; r; r = r->next) {
1023 fwriteint32_t(r->address, ofile);
1024 fwriteint32_t(r->symbol + (r->symbase == REAL_SYMBOLS ? initsym :
1025 r->symbase == ABS_SYMBOL ? initsym - 1 :
1026 r->symbase == SECT_SYMBOLS ? 2 : 0),
1027 ofile);
1028 fwriteint16_t(r->type, ofile);
1032 static void coff_symbol(char *name, int32_t strpos, int32_t value,
1033 int section, int type, int storageclass, int aux)
1035 char padname[8];
1037 if (name) {
1038 strncpy(padname, name, 8);
1039 nasm_write(padname, 8, ofile);
1040 } else {
1041 fwriteint32_t(0, ofile);
1042 fwriteint32_t(strpos, ofile);
1045 fwriteint32_t(value, ofile);
1046 fwriteint16_t(section, ofile);
1047 fwriteint16_t(type, ofile);
1049 fputc(storageclass, ofile);
1050 fputc(aux, ofile);
1053 static void coff_write_symbols(void)
1055 char filename[18];
1056 uint32_t i;
1059 * The `.file' record, and the file name auxiliary record.
1061 coff_symbol(".file", 0L, 0L, -2, 0, 0x67, 1);
1062 strncpy(filename, inname, 18);
1063 nasm_write(filename, 18, ofile);
1066 * The section records, with their auxiliaries.
1068 memset(filename, 0, 18); /* useful zeroed buffer */
1070 for (i = 0; i < (uint32_t) coff_nsects; i++) {
1071 coff_symbol(coff_sects[i]->name, 0L, 0L, i + 1, 0, 3, 1);
1072 fwriteint32_t(coff_sects[i]->len, ofile);
1073 fwriteint16_t(coff_sects[i]->nrelocs,ofile);
1074 nasm_write(filename, 12, ofile);
1078 * The absolute symbol, for relative-to-absolute relocations.
1080 coff_symbol(".absolut", 0L, 0L, -1, 0, 3, 0);
1083 * The real symbols.
1085 saa_rewind(coff_syms);
1086 for (i = 0; i < coff_nsyms; i++) {
1087 struct coff_Symbol *sym = saa_rstruct(coff_syms);
1088 coff_symbol(sym->strpos == -1 ? sym->name : NULL,
1089 sym->strpos, sym->value, sym->section,
1090 sym->type, sym->is_global ? 2 : 3, 0);
1094 static void coff_sectalign(int32_t seg, unsigned int value)
1096 struct coff_Section *s = NULL;
1097 uint32_t align;
1098 int i;
1100 for (i = 0; i < coff_nsects; i++) {
1101 if (coff_sects[i]->index == seg) {
1102 s = coff_sects[i];
1103 break;
1107 if (!s || !is_power2(value))
1108 return;
1110 /* DOS has limitation on 64 bytes */
1111 if (!(win32 | win64) && value > 64)
1112 return;
1114 align = (s->flags & IMAGE_SCN_ALIGN_MASK);
1115 value = coff_sectalign_flags(value);
1116 if (value > align)
1117 s->flags = (s->flags & ~IMAGE_SCN_ALIGN_MASK) | value;
1120 extern macros_t coff_stdmac[];
1122 #endif /* defined(OF_COFF) || defined(OF_WIN32) */
1124 #ifdef OF_COFF
1126 const struct ofmt of_coff = {
1127 "COFF (i386) object files (e.g. DJGPP for DOS)",
1128 "coff",
1129 ".o",
1132 null_debug_arr,
1133 &null_debug_form,
1134 coff_stdmac,
1135 coff_std_init,
1136 null_reset,
1137 nasm_do_legacy_output,
1138 coff_out,
1139 coff_deflabel,
1140 coff_section_names,
1141 NULL,
1142 coff_sectalign,
1143 null_segbase,
1144 coff_directives,
1145 coff_cleanup,
1146 NULL /* pragma list */
1149 #endif
1151 extern const struct dfmt df_cv8;
1153 #ifdef OF_WIN32
1155 static const struct dfmt * const win32_debug_arr[2] = { &df_cv8, NULL };
1157 const struct ofmt of_win32 = {
1158 "Microsoft Win32 (i386) object files",
1159 "win32",
1160 ".obj",
1163 win32_debug_arr,
1164 &df_cv8,
1165 coff_stdmac,
1166 coff_win32_init,
1167 null_reset,
1168 nasm_do_legacy_output,
1169 coff_out,
1170 coff_deflabel,
1171 coff_section_names,
1172 NULL,
1173 coff_sectalign,
1174 null_segbase,
1175 coff_directives,
1176 coff_cleanup,
1177 NULL /* pragma list */
1180 #endif
1182 #ifdef OF_WIN64
1184 static const struct dfmt * const win64_debug_arr[2] = { &df_cv8, NULL };
1186 const struct ofmt of_win64 = {
1187 "Microsoft Win64 (x86-64) object files",
1188 "win64",
1189 ".obj",
1192 win64_debug_arr,
1193 &df_cv8,
1194 coff_stdmac,
1195 coff_win64_init,
1196 null_reset,
1197 nasm_do_legacy_output,
1198 coff_out,
1199 coff_deflabel,
1200 coff_section_names,
1201 NULL,
1202 coff_sectalign,
1203 null_segbase,
1204 coff_directives,
1205 coff_cleanup,
1206 NULL /* pragma list */
1209 #endif