coff: Better handling of section redefinition
[nasm.git] / output / outcoff.c
blobd0fcb775184cd8200f2ea3623a841fe98acf048c
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;
141 int32_t namepos; /* Offset of name into the strings table */
142 int32_t pos, relpos;
146 * Some common section flags by default
148 #define TEXT_FLAGS_WIN \
149 (IMAGE_SCN_CNT_CODE | \
150 IMAGE_SCN_ALIGN_16BYTES | \
151 IMAGE_SCN_MEM_EXECUTE | \
152 IMAGE_SCN_MEM_READ)
153 #define TEXT_FLAGS_DOS \
154 (IMAGE_SCN_CNT_CODE)
156 #define DATA_FLAGS_WIN \
157 (IMAGE_SCN_CNT_INITIALIZED_DATA | \
158 IMAGE_SCN_ALIGN_4BYTES | \
159 IMAGE_SCN_MEM_READ | \
160 IMAGE_SCN_MEM_WRITE)
161 #define DATA_FLAGS_DOS \
162 (IMAGE_SCN_CNT_INITIALIZED_DATA)
164 #define BSS_FLAGS_WIN \
165 (IMAGE_SCN_CNT_UNINITIALIZED_DATA | \
166 IMAGE_SCN_ALIGN_4BYTES | \
167 IMAGE_SCN_MEM_READ | \
168 IMAGE_SCN_MEM_WRITE)
169 #define BSS_FLAGS_DOS \
170 (IMAGE_SCN_CNT_UNINITIALIZED_DATA)
172 #define RDATA_FLAGS_WIN \
173 (IMAGE_SCN_CNT_INITIALIZED_DATA | \
174 IMAGE_SCN_ALIGN_8BYTES | \
175 IMAGE_SCN_MEM_READ)
177 #define RDATA_FLAGS_DOS \
178 (IMAGE_SCN_CNT_INITIALIZED_DATA)
180 #define PDATA_FLAGS \
181 (IMAGE_SCN_CNT_INITIALIZED_DATA | \
182 IMAGE_SCN_ALIGN_4BYTES | \
183 IMAGE_SCN_MEM_READ)
185 #define XDATA_FLAGS \
186 (IMAGE_SCN_CNT_INITIALIZED_DATA | \
187 IMAGE_SCN_ALIGN_8BYTES | \
188 IMAGE_SCN_MEM_READ)
190 #define INFO_FLAGS \
191 (IMAGE_SCN_ALIGN_1BYTES | \
192 IMAGE_SCN_LNK_INFO | \
193 IMAGE_SCN_LNK_REMOVE)
195 #define TEXT_FLAGS ((win32 | win64) ? TEXT_FLAGS_WIN : TEXT_FLAGS_DOS)
196 #define DATA_FLAGS ((win32 | win64) ? DATA_FLAGS_WIN : DATA_FLAGS_DOS)
197 #define BSS_FLAGS ((win32 | win64) ? BSS_FLAGS_WIN : BSS_FLAGS_DOS)
198 #define RDATA_FLAGS ((win32 | win64) ? RDATA_FLAGS_WIN : RDATA_FLAGS_DOS)
200 #define SECT_DELTA 32
201 static struct Section **sects;
202 static int nsects, sectlen;
204 static struct SAA *syms;
205 static uint32_t nsyms;
207 static int32_t def_seg;
209 static int initsym;
211 static struct RAA *bsym, *symval;
213 static struct SAA *strs;
214 static uint32_t strslen;
216 static void coff_gen_init(void);
217 static void coff_sect_write(struct Section *, const uint8_t *, uint32_t);
218 static void coff_write(void);
219 static void coff_section_header(char *, int32_t, int32_t, int32_t, int32_t, int32_t, int, int32_t);
220 static void coff_write_relocs(struct Section *);
221 static void coff_write_symbols(void);
223 static void coff_win32_init(void)
225 win32 = true;
226 win64 = false;
227 coff_gen_init();
230 static void coff_win64_init(void)
232 maxbits = 64;
233 win32 = false;
234 win64 = true;
235 coff_gen_init();
236 imagebase_sect = seg_alloc()+1;
237 define_label(WRT_IMAGEBASE, imagebase_sect, 0, NULL, false, false);
240 static void coff_std_init(void)
242 win32 = win64 = false;
243 coff_gen_init();
246 static void coff_gen_init(void)
249 sects = NULL;
250 nsects = sectlen = 0;
251 syms = saa_init(sizeof(struct Symbol));
252 nsyms = 0;
253 bsym = raa_init();
254 symval = raa_init();
255 strs = saa_init(1);
256 strslen = 0;
257 def_seg = seg_alloc();
260 static void coff_cleanup(int debuginfo)
262 struct Reloc *r;
263 int i;
265 (void)debuginfo;
267 coff_write();
268 for (i = 0; i < nsects; i++) {
269 if (sects[i]->data)
270 saa_free(sects[i]->data);
271 while (sects[i]->head) {
272 r = sects[i]->head;
273 sects[i]->head = sects[i]->head->next;
274 nasm_free(r);
276 nasm_free(sects[i]->name);
277 nasm_free(sects[i]);
279 nasm_free(sects);
280 saa_free(syms);
281 raa_free(bsym);
282 raa_free(symval);
283 saa_free(strs);
286 static int coff_make_section(char *name, uint32_t flags)
288 struct Section *s;
289 size_t namelen;
291 s = nasm_zalloc(sizeof(*s));
293 if (flags != BSS_FLAGS)
294 s->data = saa_init(1);
295 s->tail = &s->head;
296 if (!strcmp(name, ".text"))
297 s->index = def_seg;
298 else
299 s->index = seg_alloc();
300 s->namepos = -1;
301 namelen = strlen(name);
302 if (namelen > 8) {
303 if (win32 || win64) {
304 s->namepos = strslen + 4;
305 saa_wbytes(strs, name, namelen + 1);
306 strslen += namelen + 1;
307 } else {
308 namelen = 8;
311 s->name = nasm_malloc(namelen + 1);
312 strncpy(s->name, name, namelen);
313 s->name[namelen] = '\0';
314 s->flags = flags;
316 if (nsects >= sectlen) {
317 sectlen += SECT_DELTA;
318 sects = nasm_realloc(sects, sectlen * sizeof(*sects));
320 sects[nsects++] = s;
322 return nsects - 1;
325 static inline int32_t coff_sectalign_flags(unsigned int align)
327 return (ilog2_32(align) + 1) << 20;
330 static int32_t coff_section_names(char *name, int pass, int *bits)
332 char *p;
333 uint32_t flags, align_and = ~0L, align_or = 0L;
334 int i;
337 * Set default bits.
339 if (!name) {
340 if(win64)
341 *bits = 64;
342 else
343 *bits = 32;
346 if (!name)
347 return def_seg;
349 p = name;
350 while (*p && !nasm_isspace(*p))
351 p++;
352 if (*p)
353 *p++ = '\0';
354 if (strlen(name) > 8) {
355 if (!win32 && !win64) {
356 nasm_error(ERR_WARNING,
357 "COFF section names limited to 8 characters: truncating");
358 name[8] = '\0';
361 flags = 0;
363 while (*p && nasm_isspace(*p))
364 p++;
365 while (*p) {
366 char *q = p;
367 while (*p && !nasm_isspace(*p))
368 p++;
369 if (*p)
370 *p++ = '\0';
371 while (*p && nasm_isspace(*p))
372 p++;
374 if (!nasm_stricmp(q, "code") || !nasm_stricmp(q, "text")) {
375 flags = TEXT_FLAGS;
376 } else if (!nasm_stricmp(q, "data")) {
377 flags = DATA_FLAGS;
378 } else if (!nasm_stricmp(q, "rdata")) {
379 if (win32 | win64)
380 flags = RDATA_FLAGS;
381 else {
382 flags = DATA_FLAGS; /* gotta do something */
383 nasm_error(ERR_NONFATAL, "standard COFF does not support"
384 " read-only data sections");
386 } else if (!nasm_stricmp(q, "bss")) {
387 flags = BSS_FLAGS;
388 } else if (!nasm_stricmp(q, "info")) {
389 if (win32 | win64)
390 flags = INFO_FLAGS;
391 else {
392 flags = DATA_FLAGS; /* gotta do something */
393 nasm_error(ERR_NONFATAL, "standard COFF does not support"
394 " informational sections");
396 } else if (!nasm_strnicmp(q, "align=", 6)) {
397 if (!(win32 | win64))
398 nasm_error(ERR_NONFATAL, "standard COFF does not support"
399 " section alignment specification");
400 else {
401 if (q[6 + strspn(q + 6, "0123456789")])
402 nasm_error(ERR_NONFATAL,
403 "argument to `align' is not numeric");
404 else {
405 unsigned int align = atoi(q + 6);
406 if (!align || ((align - 1) & align))
407 nasm_error(ERR_NONFATAL, "argument to `align' is not a"
408 " power of two");
409 else if (align > 64)
410 nasm_error(ERR_NONFATAL, "Win32 cannot align sections"
411 " to better than 64-byte boundaries");
412 else {
413 align_and = ~0x00F00000L;
414 align_or = coff_sectalign_flags(align);
421 for (i = 0; i < nsects; i++)
422 if (!strcmp(name, sects[i]->name))
423 break;
424 if (i == nsects) {
425 if (!flags) {
426 if (!strcmp(name, ".data"))
427 flags = DATA_FLAGS;
428 else if (!strcmp(name, ".rdata"))
429 flags = RDATA_FLAGS;
430 else if (!strcmp(name, ".bss"))
431 flags = BSS_FLAGS;
432 else if (win64 && !strcmp(name, ".pdata"))
433 flags = PDATA_FLAGS;
434 else if (win64 && !strcmp(name, ".xdata"))
435 flags = XDATA_FLAGS;
436 else
437 flags = TEXT_FLAGS;
439 i = coff_make_section(name, flags);
440 if (flags)
441 sects[i]->flags = flags;
442 sects[i]->flags &= align_and;
443 sects[i]->flags |= align_or;
444 } else if (pass == 1) {
445 /* Check if any flags are specified */
446 if (flags) {
447 unsigned int align_flags = flags & IMAGE_SCN_ALIGN_MASK;
449 /* Warn if non-alignment flags differ */
450 if ((flags ^ sects[i]->flags) & ~IMAGE_SCN_ALIGN_MASK) {
451 nasm_error(ERR_WARNING, "section attributes ignored on"
452 " redeclaration of section `%s'", name);
454 /* Check if alignment might be needed */
455 if (align_flags > IMAGE_SCN_ALIGN_1BYTES) {
456 unsigned int sect_align_flags = sects[i]->flags & IMAGE_SCN_ALIGN_MASK;
458 /* Compute the actual alignment */
459 unsigned int align = 1u << ((align_flags - IMAGE_SCN_ALIGN_1BYTES) >> 20);
461 /* Update section header as needed */
462 if (align_flags > sect_align_flags) {
463 sects[i]->flags = (sects[i]->flags & ~IMAGE_SCN_ALIGN_MASK) | align_flags;
465 /* Check if not already aligned */
466 if (sects[i]->len % align) {
467 unsigned int padding = (align - sects[i]->len) % align;
468 /* We need to write at most 8095 bytes */
469 char buffer[8095];
470 if (sects[i]->flags & IMAGE_SCN_CNT_CODE) {
471 /* Fill with INT 3 instructions */
472 memset(buffer, 0xCC, padding);
473 } else {
474 memset(buffer, 0x00, padding);
476 saa_wbytes(sects[i]->data, buffer, padding);
477 sects[i]->len += padding;
483 return sects[i]->index;
486 static void coff_deflabel(char *name, int32_t segment, int64_t offset,
487 int is_global, char *special)
489 int pos = strslen + 4;
490 struct Symbol *sym;
492 if (special)
493 nasm_error(ERR_NONFATAL, "COFF format does not support any"
494 " special symbol types");
496 if (name[0] == '.' && name[1] == '.' && name[2] != '@') {
497 if (strcmp(name,WRT_IMAGEBASE))
498 nasm_error(ERR_NONFATAL, "unrecognized special symbol `%s'", name);
499 return;
502 if (strlen(name) > 8) {
503 size_t nlen = strlen(name)+1;
504 saa_wbytes(strs, name, nlen);
505 strslen += nlen;
506 } else
507 pos = -1;
509 sym = saa_wstruct(syms);
511 sym->strpos = pos;
512 sym->namlen = strlen(name);
513 if (pos == -1)
514 strcpy(sym->name, name);
515 sym->is_global = !!is_global;
516 sym->type = 0; /* Default to T_NULL (no type) */
517 if (segment == NO_SEG)
518 sym->section = -1; /* absolute symbol */
519 else {
520 int i;
521 sym->section = 0;
522 for (i = 0; i < nsects; i++)
523 if (segment == sects[i]->index) {
524 sym->section = i + 1;
525 break;
527 if (!sym->section)
528 sym->is_global = true;
530 if (is_global == 2)
531 sym->value = offset;
532 else
533 sym->value = (sym->section == 0 ? 0 : offset);
536 * define the references from external-symbol segment numbers
537 * to these symbol records.
539 if (sym->section == 0)
540 bsym = raa_write(bsym, segment, nsyms);
542 if (segment != NO_SEG)
543 symval = raa_write(symval, segment, sym->section ? 0 : sym->value);
545 nsyms++;
548 static int32_t coff_add_reloc(struct Section *sect, int32_t segment,
549 int16_t type)
551 struct Reloc *r;
553 r = *sect->tail = nasm_malloc(sizeof(struct Reloc));
554 sect->tail = &r->next;
555 r->next = NULL;
557 r->address = sect->len;
558 if (segment == NO_SEG) {
559 r->symbol = 0, r->symbase = ABS_SYMBOL;
560 } else {
561 int i;
562 r->symbase = REAL_SYMBOLS;
563 for (i = 0; i < nsects; i++) {
564 if (segment == sects[i]->index) {
565 r->symbol = i * 2;
566 r->symbase = SECT_SYMBOLS;
567 break;
570 if (r->symbase == REAL_SYMBOLS)
571 r->symbol = raa_read(bsym, segment);
573 r->type = type;
575 sect->nrelocs++;
578 * Return the fixup for standard COFF common variables.
580 if (r->symbase == REAL_SYMBOLS && !(win32 | win64))
581 return raa_read(symval, segment);
583 return 0;
586 static void coff_out(int32_t segto, const void *data,
587 enum out_type type, uint64_t size,
588 int32_t segment, int32_t wrt)
590 struct Section *s;
591 uint8_t mydata[8], *p;
592 int i;
594 if (wrt != NO_SEG && !win64) {
595 wrt = NO_SEG; /* continue to do _something_ */
596 nasm_error(ERR_NONFATAL, "WRT not supported by COFF output formats");
600 * handle absolute-assembly (structure definitions)
602 if (segto == NO_SEG) {
603 if (type != OUT_RESERVE)
604 nasm_error(ERR_NONFATAL, "attempt to assemble code in [ABSOLUTE]"
605 " space");
606 return;
609 s = NULL;
610 for (i = 0; i < nsects; i++) {
611 if (segto == sects[i]->index) {
612 s = sects[i];
613 break;
616 if (!s) {
617 int tempint; /* ignored */
618 if (segto != coff_section_names(".text", 2, &tempint))
619 nasm_error(ERR_PANIC, "strange segment conditions in COFF driver");
620 else
621 s = sects[nsects - 1];
624 /* magically default to 'wrt ..imagebase' in .pdata and .xdata */
625 if (win64 && wrt == NO_SEG) {
626 if (!strcmp(s->name,".pdata") || !strcmp(s->name,".xdata"))
627 wrt = imagebase_sect;
630 if (!s->data && type != OUT_RESERVE) {
631 nasm_error(ERR_WARNING, "attempt to initialize memory in"
632 " BSS section `%s': ignored", s->name);
633 s->len += realsize(type, size);
634 return;
637 if (type == OUT_RESERVE) {
638 if (s->data) {
639 nasm_error(ERR_WARNING, "uninitialised space declared in"
640 " non-BSS section `%s': zeroing", s->name);
641 coff_sect_write(s, NULL, size);
642 } else
643 s->len += size;
644 } else if (type == OUT_RAWDATA) {
645 if (segment != NO_SEG)
646 nasm_error(ERR_PANIC, "OUT_RAWDATA with other than NO_SEG");
647 coff_sect_write(s, data, size);
648 } else if (type == OUT_ADDRESS) {
649 if (!(win64)) {
650 if (size != 4 && (segment != NO_SEG || wrt != NO_SEG)) {
651 nasm_error(ERR_NONFATAL, "COFF format does not support non-32-bit"
652 " relocations");
653 } else {
654 int32_t fix = 0;
655 if (segment != NO_SEG || wrt != NO_SEG) {
656 if (wrt != NO_SEG) {
657 nasm_error(ERR_NONFATAL, "COFF format does not support"
658 " WRT types");
659 } else if (segment % 2) {
660 nasm_error(ERR_NONFATAL, "COFF format does not support"
661 " segment base references");
662 } else
663 fix = coff_add_reloc(s, segment, IMAGE_REL_I386_DIR32);
665 p = mydata;
666 WRITELONG(p, *(int64_t *)data + fix);
667 coff_sect_write(s, mydata, size);
669 } else {
670 int32_t fix = 0;
671 p = mydata;
672 if (size == 8) {
673 if (wrt == imagebase_sect) {
674 nasm_error(ERR_NONFATAL, "operand size mismatch: 'wrt "
675 WRT_IMAGEBASE "' is a 32-bit operand");
677 fix = coff_add_reloc(s, segment, IMAGE_REL_AMD64_ADDR64);
678 WRITEDLONG(p, *(int64_t *)data + fix);
679 coff_sect_write(s, mydata, size);
680 } else {
681 fix = coff_add_reloc(s, segment,
682 wrt == imagebase_sect ? IMAGE_REL_AMD64_ADDR32NB:
683 IMAGE_REL_AMD64_ADDR32);
684 WRITELONG(p, *(int64_t *)data + fix);
685 coff_sect_write(s, mydata, size);
688 } else if (type == OUT_REL2ADR) {
689 nasm_error(ERR_NONFATAL, "COFF format does not support 16-bit"
690 " relocations");
691 } else if (type == OUT_REL4ADR) {
692 if (segment == segto && !(win64)) /* Acceptable for RIP-relative */
693 nasm_error(ERR_PANIC, "intra-segment OUT_REL4ADR");
694 else if (segment == NO_SEG && win32)
695 nasm_error(ERR_NONFATAL, "Win32 COFF does not correctly support"
696 " relative references to absolute addresses");
697 else {
698 int32_t fix = 0;
699 if (segment != NO_SEG && segment % 2) {
700 nasm_error(ERR_NONFATAL, "COFF format does not support"
701 " segment base references");
702 } else
703 fix = coff_add_reloc(s, segment,
704 win64 ? IMAGE_REL_AMD64_REL32 : IMAGE_REL_I386_REL32);
705 p = mydata;
706 if (win32 | win64) {
707 WRITELONG(p, *(int64_t *)data + 4 - size + fix);
708 } else {
709 WRITELONG(p, *(int64_t *)data - (size + s->len) + fix);
711 coff_sect_write(s, mydata, 4L);
717 static void coff_sect_write(struct Section *sect,
718 const uint8_t *data, uint32_t len)
720 saa_wbytes(sect->data, data, len);
721 sect->len += len;
724 typedef struct tagString {
725 struct tagString *next;
726 int len;
727 char *String;
728 } STRING;
730 #define EXPORT_SECTION_NAME ".drectve"
731 #define EXPORT_SECTION_FLAGS INFO_FLAGS
733 * #define EXPORT_SECTION_NAME ".text"
734 * #define EXPORT_SECTION_FLAGS TEXT_FLAGS
737 static STRING *Exports = NULL;
738 static struct Section *directive_sec;
739 void AddExport(char *name)
741 STRING *rvp = Exports, *newS;
743 newS = (STRING *) nasm_malloc(sizeof(STRING));
744 newS->len = strlen(name);
745 newS->next = NULL;
746 newS->String = (char *)nasm_malloc(newS->len + 1);
747 strcpy(newS->String, name);
748 if (rvp == NULL) {
749 int i;
751 for (i = 0; i < nsects; i++) {
752 if (!strcmp(EXPORT_SECTION_NAME, sects[i]->name))
753 break;
756 if (i == nsects)
757 i = coff_make_section(EXPORT_SECTION_NAME, EXPORT_SECTION_FLAGS);
759 directive_sec = sects[i];
760 Exports = newS;
761 } else {
762 while (rvp->next) {
763 if (!strcmp(rvp->String, name))
764 return;
765 rvp = rvp->next;
767 rvp->next = newS;
771 static void BuildExportTable(STRING **rvp)
773 STRING *p, *t;
775 if (!rvp || !*rvp)
776 return;
778 list_for_each_safe(p, t, *rvp) {
779 coff_sect_write(directive_sec, (uint8_t *)"-export:", 8);
780 coff_sect_write(directive_sec, (uint8_t *)p->String, p->len);
781 coff_sect_write(directive_sec, (uint8_t *)" ", 1);
782 nasm_free(p->String);
783 nasm_free(p);
786 *rvp = NULL;
789 static int coff_directives(enum directives directive, char *value, int pass)
791 switch (directive) {
792 case D_EXPORT:
794 char *q, *name;
796 if (pass == 2)
797 return 1; /* ignore in pass two */
798 name = q = value;
799 while (*q && !nasm_isspace(*q))
800 q++;
801 if (nasm_isspace(*q)) {
802 *q++ = '\0';
803 while (*q && nasm_isspace(*q))
804 q++;
807 if (!*name) {
808 nasm_error(ERR_NONFATAL, "`export' directive requires export name");
809 return 1;
811 if (*q) {
812 nasm_error(ERR_NONFATAL, "unrecognized export qualifier `%s'", q);
813 return 1;
815 AddExport(name);
816 return 1;
818 case D_SAFESEH:
820 static int sxseg=-1;
821 int i;
823 if (!win32) /* Only applicable for -f win32 */
824 return 0;
826 if (sxseg == -1) {
827 for (i = 0; i < nsects; i++)
828 if (!strcmp(".sxdata",sects[i]->name))
829 break;
830 if (i == nsects)
831 sxseg = coff_make_section(".sxdata", IMAGE_SCN_LNK_INFO);
832 else
833 sxseg = i;
836 * pass0 == 2 is the only time when the full set of symbols are
837 * guaranteed to be present; it is the final output pass.
839 if (pass0 == 2) {
840 uint32_t n;
841 saa_rewind(syms);
842 for (n = 0; n < nsyms; n++) {
843 struct Symbol *sym = saa_rstruct(syms);
844 bool equals;
847 * sym->strpos is biased by 4, because symbol
848 * table is prefixed with table length
850 if (sym->strpos >=4) {
851 char *name = nasm_malloc(sym->namlen+1);
852 saa_fread(strs, sym->strpos-4, name, sym->namlen);
853 name[sym->namlen] = '\0';
854 equals = !strcmp(value,name);
855 nasm_free(name);
856 } else {
857 equals = !strcmp(value,sym->name);
860 if (equals) {
862 * this value arithmetics effectively reflects
863 * initsym in coff_write(): 2 for file, 1 for
864 * .absolute and two per each section
866 unsigned char value[4],*p=value;
867 WRITELONG(p,n + 2 + 1 + nsects*2);
868 coff_sect_write(sects[sxseg],value,4);
869 sym->type = 0x20;
870 break;
873 if (n == nsyms) {
874 nasm_error(ERR_NONFATAL,
875 "`safeseh' directive requires valid symbol");
878 return 1;
880 default:
881 return 0;
885 /* handle relocations storm, valid for win32/64 only */
886 static inline void coff_adjust_relocs(struct Section *s)
888 if (s->nrelocs < IMAGE_SCN_MAX_RELOC)
889 return;
890 #ifdef OF_COFF
891 else
893 if (ofmt == &of_coff)
894 nasm_error(ERR_FATAL,
895 "Too many relocations (%d) for section `%s'",
896 s->nrelocs, s->name);
898 #endif
900 s->flags |= IMAGE_SCN_LNK_NRELOC_OVFL;
901 s->nrelocs++;
904 static void coff_write(void)
906 int32_t pos, sympos, vsize;
907 int i;
909 /* fill in the .drectve section with -export's */
910 BuildExportTable(&Exports);
912 if (win32) {
913 /* add default value for @feat.00, this allows to 'link /safeseh' */
914 uint32_t n;
916 saa_rewind(syms);
917 for (n = 0; n < nsyms; n++) {
918 struct Symbol *sym = saa_rstruct(syms);
919 if (sym->strpos == -1 && !strcmp("@feat.00",sym->name))
920 break;
922 if (n == nsyms)
923 coff_deflabel("@feat.00", NO_SEG, 1, 0, NULL);
927 * Work out how big the file will get.
928 * Calculate the start of the `real' symbols at the same time.
929 * Check for massive relocations.
931 pos = 0x14 + 0x28 * nsects;
932 initsym = 3; /* two for the file, one absolute */
933 for (i = 0; i < nsects; i++) {
934 if (sects[i]->data) {
935 coff_adjust_relocs(sects[i]);
936 sects[i]->pos = pos;
937 pos += sects[i]->len;
938 sects[i]->relpos = pos;
939 pos += 10 * sects[i]->nrelocs;
940 } else
941 sects[i]->pos = sects[i]->relpos = 0L;
942 initsym += 2; /* two for each section */
944 sympos = pos;
947 * Output the COFF header.
949 if (win64)
950 i = IMAGE_FILE_MACHINE_AMD64;
951 else
952 i = IMAGE_FILE_MACHINE_I386;
953 fwriteint16_t(i, ofile); /* machine type */
954 fwriteint16_t(nsects, ofile); /* number of sections */
955 fwriteint32_t(time(NULL), ofile); /* time stamp */
956 fwriteint32_t(sympos, ofile);
957 fwriteint32_t(nsyms + initsym, ofile);
958 fwriteint16_t(0, ofile); /* no optional header */
959 /* Flags: 32-bit, no line numbers. Win32 doesn't even bother with them. */
960 fwriteint16_t((win32 | win64) ? 0 : 0x104, ofile);
963 * Output the section headers.
965 vsize = 0L;
966 for (i = 0; i < nsects; i++) {
967 coff_section_header(sects[i]->name, sects[i]->namepos, vsize, sects[i]->len,
968 sects[i]->pos, sects[i]->relpos,
969 sects[i]->nrelocs, sects[i]->flags);
970 vsize += sects[i]->len;
974 * Output the sections and their relocations.
976 for (i = 0; i < nsects; i++)
977 if (sects[i]->data) {
978 saa_fpwrite(sects[i]->data, ofile);
979 coff_write_relocs(sects[i]);
983 * Output the symbol and string tables.
985 coff_write_symbols();
986 fwriteint32_t(strslen + 4, ofile); /* length includes length count */
987 saa_fpwrite(strs, ofile);
990 static void coff_section_header(char *name, int32_t namepos, int32_t vsize,
991 int32_t datalen, int32_t datapos,
992 int32_t relpos, int nrelocs, int32_t flags)
994 char padname[8];
996 (void)vsize;
998 if (namepos == -1) {
999 strncpy(padname, name, 8);
1000 fwrite(padname, 8, 1, ofile);
1001 } else {
1003 * If name is longer than 8 bytes, write '/' followed
1004 * by offset into the strings table represented as
1005 * decimal number.
1007 namepos = namepos % 100000000;
1008 padname[0] = '/';
1009 padname[1] = '0' + (namepos / 1000000);
1010 namepos = namepos % 1000000;
1011 padname[2] = '0' + (namepos / 100000);
1012 namepos = namepos % 100000;
1013 padname[3] = '0' + (namepos / 10000);
1014 namepos = namepos % 10000;
1015 padname[4] = '0' + (namepos / 1000);
1016 namepos = namepos % 1000;
1017 padname[5] = '0' + (namepos / 100);
1018 namepos = namepos % 100;
1019 padname[6] = '0' + (namepos / 10);
1020 namepos = namepos % 10;
1021 padname[7] = '0' + (namepos);
1022 fwrite(padname, 8, 1, ofile);
1025 fwriteint32_t(0, ofile); /* Virtual size field - set to 0 or vsize */
1026 fwriteint32_t(0L, ofile); /* RVA/offset - we ignore */
1027 fwriteint32_t(datalen, ofile);
1028 fwriteint32_t(datapos, ofile);
1029 fwriteint32_t(relpos, ofile);
1030 fwriteint32_t(0L, ofile); /* no line numbers - we don't do 'em */
1033 * a special case -- if there are too many relocs
1034 * we have to put IMAGE_SCN_MAX_RELOC here and write
1035 * the real relocs number into VirtualAddress of first
1036 * relocation
1038 if (flags & IMAGE_SCN_LNK_NRELOC_OVFL)
1039 fwriteint16_t(IMAGE_SCN_MAX_RELOC, ofile);
1040 else
1041 fwriteint16_t(nrelocs, ofile);
1043 fwriteint16_t(0, ofile); /* again, no line numbers */
1044 fwriteint32_t(flags, ofile);
1047 static void coff_write_relocs(struct Section *s)
1049 struct Reloc *r;
1051 /* a real number of relocations if needed */
1052 if (s->flags & IMAGE_SCN_LNK_NRELOC_OVFL) {
1053 fwriteint32_t(s->nrelocs, ofile);
1054 fwriteint32_t(0, ofile);
1055 fwriteint16_t(0, ofile);
1058 for (r = s->head; r; r = r->next) {
1059 fwriteint32_t(r->address, ofile);
1060 fwriteint32_t(r->symbol + (r->symbase == REAL_SYMBOLS ? initsym :
1061 r->symbase == ABS_SYMBOL ? initsym - 1 :
1062 r->symbase == SECT_SYMBOLS ? 2 : 0),
1063 ofile);
1064 fwriteint16_t(r->type, ofile);
1068 static void coff_symbol(char *name, int32_t strpos, int32_t value,
1069 int section, int type, int storageclass, int aux)
1071 char padname[8];
1073 if (name) {
1074 strncpy(padname, name, 8);
1075 fwrite(padname, 8, 1, ofile);
1076 } else {
1077 fwriteint32_t(0, ofile);
1078 fwriteint32_t(strpos, ofile);
1081 fwriteint32_t(value, ofile);
1082 fwriteint16_t(section, ofile);
1083 fwriteint16_t(type, ofile);
1085 fputc(storageclass, ofile);
1086 fputc(aux, ofile);
1089 static void coff_write_symbols(void)
1091 char filename[18];
1092 uint32_t i;
1095 * The `.file' record, and the file name auxiliary record.
1097 coff_symbol(".file", 0L, 0L, -2, 0, 0x67, 1);
1098 strncpy(filename, coff_infile, 18);
1099 fwrite(filename, 18, 1, ofile);
1102 * The section records, with their auxiliaries.
1104 memset(filename, 0, 18); /* useful zeroed buffer */
1106 for (i = 0; i < (uint32_t) nsects; i++) {
1107 coff_symbol(sects[i]->name, 0L, 0L, i + 1, 0, 3, 1);
1108 fwriteint32_t(sects[i]->len, ofile);
1109 fwriteint16_t(sects[i]->nrelocs,ofile);
1110 fwrite(filename, 12, 1, ofile);
1114 * The absolute symbol, for relative-to-absolute relocations.
1116 coff_symbol(".absolut", 0L, 0L, -1, 0, 3, 0);
1119 * The real symbols.
1121 saa_rewind(syms);
1122 for (i = 0; i < nsyms; i++) {
1123 struct Symbol *sym = saa_rstruct(syms);
1124 coff_symbol(sym->strpos == -1 ? sym->name : NULL,
1125 sym->strpos, sym->value, sym->section,
1126 sym->type, sym->is_global ? 2 : 3, 0);
1130 static void coff_sectalign(int32_t seg, unsigned int value)
1132 struct Section *s = NULL;
1133 uint32_t align;
1134 int i;
1136 for (i = 0; i < nsects; i++) {
1137 if (sects[i]->index == seg) {
1138 s = sects[i];
1139 break;
1143 if (!s || !is_power2(value))
1144 return;
1146 /* DOS has limitation on 64 bytes */
1147 if (!(win32 | win64) && value > 64)
1148 return;
1150 align = (s->flags & IMAGE_SCN_ALIGN_MASK);
1151 value = coff_sectalign_flags(value);
1152 if (value > align)
1153 s->flags = (s->flags & ~IMAGE_SCN_ALIGN_MASK) | value;
1156 static int32_t coff_segbase(int32_t segment)
1158 return segment;
1161 static void coff_std_filename(char *inname, char *outname)
1163 strcpy(coff_infile, inname);
1164 standard_extension(inname, outname, ".o");
1167 static void coff_win32_filename(char *inname, char *outname)
1169 strcpy(coff_infile, inname);
1170 standard_extension(inname, outname, ".obj");
1173 extern macros_t coff_stdmac[];
1175 static int coff_set_info(enum geninfo type, char **val)
1177 (void)type;
1178 (void)val;
1179 return 0;
1181 #endif /* defined(OF_COFF) || defined(OF_WIN32) */
1183 #ifdef OF_COFF
1185 struct ofmt of_coff = {
1186 "COFF (i386) object files (e.g. DJGPP for DOS)",
1187 "coff",
1189 null_debug_arr,
1190 &null_debug_form,
1191 coff_stdmac,
1192 coff_std_init,
1193 coff_set_info,
1194 coff_out,
1195 coff_deflabel,
1196 coff_section_names,
1197 coff_sectalign,
1198 coff_segbase,
1199 coff_directives,
1200 coff_std_filename,
1201 coff_cleanup
1204 #endif
1206 #ifdef OF_WIN32
1208 struct ofmt of_win32 = {
1209 "Microsoft Win32 (i386) object files",
1210 "win32",
1212 null_debug_arr,
1213 &null_debug_form,
1214 coff_stdmac,
1215 coff_win32_init,
1216 coff_set_info,
1217 coff_out,
1218 coff_deflabel,
1219 coff_section_names,
1220 coff_sectalign,
1221 coff_segbase,
1222 coff_directives,
1223 coff_win32_filename,
1224 coff_cleanup
1227 #endif
1229 #ifdef OF_WIN64
1231 struct ofmt of_win64 = {
1232 "Microsoft Win64 (x86-64) object files",
1233 "win64",
1235 null_debug_arr,
1236 &null_debug_form,
1237 coff_stdmac,
1238 coff_win64_init,
1239 coff_set_info,
1240 coff_out,
1241 coff_deflabel,
1242 coff_section_names,
1243 coff_sectalign,
1244 coff_segbase,
1245 coff_directives,
1246 coff_win32_filename,
1247 coff_cleanup
1250 #endif