changes.src: update for a 2.12.03 release
[nasm.git] / output / outcoff.c
blob56d76674ad5796f8e18e7cdd3ca05295e87d4c0e
1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2014 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 bool win32, win64;
105 static int32_t imagebase_sect;
106 #define WRT_IMAGEBASE "..imagebase"
108 char coff_infile[FILENAME_MAX];
109 char coff_outfile[FILENAME_MAX];
112 * Some common section flags by default
114 #define TEXT_FLAGS_WIN \
115 (IMAGE_SCN_CNT_CODE | \
116 IMAGE_SCN_ALIGN_16BYTES | \
117 IMAGE_SCN_MEM_EXECUTE | \
118 IMAGE_SCN_MEM_READ)
119 #define TEXT_FLAGS_DOS \
120 (IMAGE_SCN_CNT_CODE)
122 #define DATA_FLAGS_WIN \
123 (IMAGE_SCN_CNT_INITIALIZED_DATA | \
124 IMAGE_SCN_ALIGN_4BYTES | \
125 IMAGE_SCN_MEM_READ | \
126 IMAGE_SCN_MEM_WRITE)
127 #define DATA_FLAGS_DOS \
128 (IMAGE_SCN_CNT_INITIALIZED_DATA)
130 #define BSS_FLAGS_WIN \
131 (IMAGE_SCN_CNT_UNINITIALIZED_DATA | \
132 IMAGE_SCN_ALIGN_4BYTES | \
133 IMAGE_SCN_MEM_READ | \
134 IMAGE_SCN_MEM_WRITE)
135 #define BSS_FLAGS_DOS \
136 (IMAGE_SCN_CNT_UNINITIALIZED_DATA)
138 #define RDATA_FLAGS_WIN \
139 (IMAGE_SCN_CNT_INITIALIZED_DATA | \
140 IMAGE_SCN_ALIGN_8BYTES | \
141 IMAGE_SCN_MEM_READ)
143 #define RDATA_FLAGS_DOS \
144 (IMAGE_SCN_CNT_INITIALIZED_DATA)
146 #define PDATA_FLAGS \
147 (IMAGE_SCN_CNT_INITIALIZED_DATA | \
148 IMAGE_SCN_ALIGN_4BYTES | \
149 IMAGE_SCN_MEM_READ)
151 #define XDATA_FLAGS \
152 (IMAGE_SCN_CNT_INITIALIZED_DATA | \
153 IMAGE_SCN_ALIGN_8BYTES | \
154 IMAGE_SCN_MEM_READ)
156 #define INFO_FLAGS \
157 (IMAGE_SCN_ALIGN_1BYTES | \
158 IMAGE_SCN_LNK_INFO | \
159 IMAGE_SCN_LNK_REMOVE)
161 #define TEXT_FLAGS ((win32 | win64) ? TEXT_FLAGS_WIN : TEXT_FLAGS_DOS)
162 #define DATA_FLAGS ((win32 | win64) ? DATA_FLAGS_WIN : DATA_FLAGS_DOS)
163 #define BSS_FLAGS ((win32 | win64) ? BSS_FLAGS_WIN : BSS_FLAGS_DOS)
164 #define RDATA_FLAGS ((win32 | win64) ? RDATA_FLAGS_WIN : RDATA_FLAGS_DOS)
166 #define SECT_DELTA 32
167 struct coff_Section **coff_sects;
168 static int sectlen;
169 int coff_nsects;
171 struct SAA *coff_syms;
172 uint32_t coff_nsyms;
174 static int32_t def_seg;
176 static int initsym;
178 static struct RAA *bsym, *symval;
180 struct SAA *coff_strs;
181 static uint32_t strslen;
183 static void coff_gen_init(void);
184 static void coff_sect_write(struct coff_Section *, const uint8_t *, uint32_t);
185 static void coff_write(void);
186 static void coff_section_header(char *, int32_t, int32_t, int32_t, int32_t, int32_t, int, int32_t);
187 static void coff_write_relocs(struct coff_Section *);
188 static void coff_write_symbols(void);
190 static void coff_win32_init(void)
192 win32 = true;
193 win64 = false;
194 coff_gen_init();
197 static void coff_win64_init(void)
199 win32 = false;
200 win64 = true;
201 coff_gen_init();
202 imagebase_sect = seg_alloc()+1;
203 define_label(WRT_IMAGEBASE, imagebase_sect, 0, NULL, false, false);
206 static void coff_std_init(void)
208 win32 = win64 = false;
209 coff_gen_init();
212 static void coff_gen_init(void)
215 coff_sects = NULL;
216 coff_nsects = sectlen = 0;
217 coff_syms = saa_init(sizeof(struct coff_Symbol));
218 coff_nsyms = 0;
219 bsym = raa_init();
220 symval = raa_init();
221 coff_strs = saa_init(1);
222 strslen = 0;
223 def_seg = seg_alloc();
226 static void coff_cleanup(void)
228 struct coff_Reloc *r;
229 int i;
231 dfmt->cleanup();
233 coff_write();
234 for (i = 0; i < coff_nsects; i++) {
235 if (coff_sects[i]->data)
236 saa_free(coff_sects[i]->data);
237 while (coff_sects[i]->head) {
238 r = coff_sects[i]->head;
239 coff_sects[i]->head = coff_sects[i]->head->next;
240 nasm_free(r);
242 nasm_free(coff_sects[i]->name);
243 nasm_free(coff_sects[i]);
245 nasm_free(coff_sects);
246 saa_free(coff_syms);
247 raa_free(bsym);
248 raa_free(symval);
249 saa_free(coff_strs);
252 int coff_make_section(char *name, uint32_t flags)
254 struct coff_Section *s;
255 size_t namelen;
257 s = nasm_zalloc(sizeof(*s));
259 if (flags != BSS_FLAGS)
260 s->data = saa_init(1);
261 s->tail = &s->head;
262 if (!strcmp(name, ".text"))
263 s->index = def_seg;
264 else
265 s->index = seg_alloc();
266 s->namepos = -1;
267 namelen = strlen(name);
268 if (namelen > 8) {
269 if (win32 || win64) {
270 s->namepos = strslen + 4;
271 saa_wbytes(coff_strs, name, namelen + 1);
272 strslen += namelen + 1;
273 } else {
274 namelen = 8;
277 s->name = nasm_malloc(namelen + 1);
278 strncpy(s->name, name, namelen);
279 s->name[namelen] = '\0';
280 s->flags = flags;
282 if (coff_nsects >= sectlen) {
283 sectlen += SECT_DELTA;
284 coff_sects = nasm_realloc(coff_sects, sectlen * sizeof(*coff_sects));
286 coff_sects[coff_nsects++] = s;
288 return coff_nsects - 1;
291 static inline int32_t coff_sectalign_flags(unsigned int align)
293 return (ilog2_32(align) + 1) << 20;
296 static int32_t coff_section_names(char *name, int pass, int *bits)
298 char *p;
299 uint32_t flags, align_and = ~0L, align_or = 0L;
300 int i;
303 * Set default bits.
305 if (!name) {
306 if(win64)
307 *bits = 64;
308 else
309 *bits = 32;
312 if (!name)
313 return def_seg;
315 p = name;
316 while (*p && !nasm_isspace(*p))
317 p++;
318 if (*p)
319 *p++ = '\0';
320 if (strlen(name) > 8) {
321 if (!win32 && !win64) {
322 nasm_error(ERR_WARNING,
323 "COFF section names limited to 8 characters: truncating");
324 name[8] = '\0';
327 flags = 0;
329 while (*p && nasm_isspace(*p))
330 p++;
331 while (*p) {
332 char *q = p;
333 while (*p && !nasm_isspace(*p))
334 p++;
335 if (*p)
336 *p++ = '\0';
337 while (*p && nasm_isspace(*p))
338 p++;
340 if (!nasm_stricmp(q, "code") || !nasm_stricmp(q, "text")) {
341 flags = TEXT_FLAGS;
342 } else if (!nasm_stricmp(q, "data")) {
343 flags = DATA_FLAGS;
344 } else if (!nasm_stricmp(q, "rdata")) {
345 if (win32 | win64)
346 flags = RDATA_FLAGS;
347 else {
348 flags = DATA_FLAGS; /* gotta do something */
349 nasm_error(ERR_NONFATAL, "standard COFF does not support"
350 " read-only data sections");
352 } else if (!nasm_stricmp(q, "bss")) {
353 flags = BSS_FLAGS;
354 } else if (!nasm_stricmp(q, "info")) {
355 if (win32 | win64)
356 flags = INFO_FLAGS;
357 else {
358 flags = DATA_FLAGS; /* gotta do something */
359 nasm_error(ERR_NONFATAL, "standard COFF does not support"
360 " informational sections");
362 } else if (!nasm_strnicmp(q, "align=", 6)) {
363 if (!(win32 | win64))
364 nasm_error(ERR_NONFATAL, "standard COFF does not support"
365 " section alignment specification");
366 else {
367 if (q[6 + strspn(q + 6, "0123456789")])
368 nasm_error(ERR_NONFATAL,
369 "argument to `align' is not numeric");
370 else {
371 unsigned int align = atoi(q + 6);
372 if (!align || ((align - 1) & align))
373 nasm_error(ERR_NONFATAL, "argument to `align' is not a"
374 " power of two");
375 else if (align > 64)
376 nasm_error(ERR_NONFATAL, "Win32 cannot align sections"
377 " to better than 64-byte boundaries");
378 else {
379 align_and = ~0x00F00000L;
380 align_or = coff_sectalign_flags(align);
387 for (i = 0; i < coff_nsects; i++)
388 if (!strcmp(name, coff_sects[i]->name))
389 break;
390 if (i == coff_nsects) {
391 if (!flags) {
392 if (!strcmp(name, ".data"))
393 flags = DATA_FLAGS;
394 else if (!strcmp(name, ".rdata"))
395 flags = RDATA_FLAGS;
396 else if (!strcmp(name, ".bss"))
397 flags = BSS_FLAGS;
398 else if (win64 && !strcmp(name, ".pdata"))
399 flags = PDATA_FLAGS;
400 else if (win64 && !strcmp(name, ".xdata"))
401 flags = XDATA_FLAGS;
402 else
403 flags = TEXT_FLAGS;
405 i = coff_make_section(name, flags);
406 if (flags)
407 coff_sects[i]->flags = flags;
408 coff_sects[i]->flags &= align_and;
409 coff_sects[i]->flags |= align_or;
410 } else if (pass == 1) {
411 /* Check if any flags are specified */
412 if (flags) {
413 unsigned int align_flags = flags & IMAGE_SCN_ALIGN_MASK;
415 /* Warn if non-alignment flags differ */
416 if ((flags ^ coff_sects[i]->flags) & ~IMAGE_SCN_ALIGN_MASK) {
417 nasm_error(ERR_WARNING, "section attributes ignored on"
418 " redeclaration of section `%s'", name);
420 /* Check if alignment might be needed */
421 if (align_flags > IMAGE_SCN_ALIGN_1BYTES) {
422 unsigned int sect_align_flags = coff_sects[i]->flags & IMAGE_SCN_ALIGN_MASK;
424 /* Compute the actual alignment */
425 unsigned int align = 1u << ((align_flags - IMAGE_SCN_ALIGN_1BYTES) >> 20);
427 /* Update section header as needed */
428 if (align_flags > sect_align_flags) {
429 coff_sects[i]->flags = (coff_sects[i]->flags & ~IMAGE_SCN_ALIGN_MASK) | align_flags;
431 /* Check if not already aligned */
432 if (coff_sects[i]->len % align) {
433 unsigned int padding = (align - coff_sects[i]->len) % align;
434 /* We need to write at most 8095 bytes */
435 char buffer[8095];
436 if (coff_sects[i]->flags & IMAGE_SCN_CNT_CODE) {
437 /* Fill with INT 3 instructions */
438 memset(buffer, 0xCC, padding);
439 } else {
440 memset(buffer, 0x00, padding);
442 saa_wbytes(coff_sects[i]->data, buffer, padding);
443 coff_sects[i]->len += padding;
449 return coff_sects[i]->index;
452 static void coff_deflabel(char *name, int32_t segment, int64_t offset,
453 int is_global, char *special)
455 int pos = strslen + 4;
456 struct coff_Symbol *sym;
458 if (special)
459 nasm_error(ERR_NONFATAL, "COFF format does not support any"
460 " special symbol types");
462 if (name[0] == '.' && name[1] == '.' && name[2] != '@') {
463 if (strcmp(name,WRT_IMAGEBASE))
464 nasm_error(ERR_NONFATAL, "unrecognized special symbol `%s'", name);
465 return;
468 if (strlen(name) > 8) {
469 size_t nlen = strlen(name)+1;
470 saa_wbytes(coff_strs, name, nlen);
471 strslen += nlen;
472 } else
473 pos = -1;
475 sym = saa_wstruct(coff_syms);
477 sym->strpos = pos;
478 sym->namlen = strlen(name);
479 if (pos == -1)
480 strcpy(sym->name, name);
481 sym->is_global = !!is_global;
482 sym->type = 0; /* Default to T_NULL (no type) */
483 if (segment == NO_SEG)
484 sym->section = -1; /* absolute symbol */
485 else {
486 int i;
487 sym->section = 0;
488 for (i = 0; i < coff_nsects; i++)
489 if (segment == coff_sects[i]->index) {
490 sym->section = i + 1;
491 break;
493 if (!sym->section)
494 sym->is_global = true;
496 if (is_global == 2)
497 sym->value = offset;
498 else
499 sym->value = (sym->section == 0 ? 0 : offset);
502 * define the references from external-symbol segment numbers
503 * to these symbol records.
505 if (sym->section == 0)
506 bsym = raa_write(bsym, segment, coff_nsyms);
508 if (segment != NO_SEG)
509 symval = raa_write(symval, segment, sym->section ? 0 : sym->value);
511 coff_nsyms++;
514 static int32_t coff_add_reloc(struct coff_Section *sect, int32_t segment,
515 int16_t type)
517 struct coff_Reloc *r;
519 r = *sect->tail = nasm_malloc(sizeof(struct coff_Reloc));
520 sect->tail = &r->next;
521 r->next = NULL;
523 r->address = sect->len;
524 if (segment == NO_SEG) {
525 r->symbol = 0, r->symbase = ABS_SYMBOL;
526 } else {
527 int i;
528 r->symbase = REAL_SYMBOLS;
529 for (i = 0; i < coff_nsects; i++) {
530 if (segment == coff_sects[i]->index) {
531 r->symbol = i * 2;
532 r->symbase = SECT_SYMBOLS;
533 break;
536 if (r->symbase == REAL_SYMBOLS)
537 r->symbol = raa_read(bsym, segment);
539 r->type = type;
541 sect->nrelocs++;
544 * Return the fixup for standard COFF common variables.
546 if (r->symbase == REAL_SYMBOLS && !(win32 | win64))
547 return raa_read(symval, segment);
549 return 0;
552 static void coff_out(int32_t segto, const void *data,
553 enum out_type type, uint64_t size,
554 int32_t segment, int32_t wrt)
556 struct coff_Section *s;
557 uint8_t mydata[8], *p;
558 int i;
560 if (wrt != NO_SEG && !win64) {
561 wrt = NO_SEG; /* continue to do _something_ */
562 nasm_error(ERR_NONFATAL, "WRT not supported by COFF output formats");
566 * handle absolute-assembly (structure definitions)
568 if (segto == NO_SEG) {
569 if (type != OUT_RESERVE)
570 nasm_error(ERR_NONFATAL, "attempt to assemble code in [ABSOLUTE]"
571 " space");
572 return;
575 s = NULL;
576 for (i = 0; i < coff_nsects; i++) {
577 if (segto == coff_sects[i]->index) {
578 s = coff_sects[i];
579 break;
582 if (!s) {
583 int tempint; /* ignored */
584 if (segto != coff_section_names(".text", 2, &tempint))
585 nasm_panic(0, "strange segment conditions in COFF driver");
586 else
587 s = coff_sects[coff_nsects - 1];
590 /* magically default to 'wrt ..imagebase' in .pdata and .xdata */
591 if (win64 && wrt == NO_SEG) {
592 if (!strcmp(s->name,".pdata") || !strcmp(s->name,".xdata"))
593 wrt = imagebase_sect;
596 if (!s->data && type != OUT_RESERVE) {
597 nasm_error(ERR_WARNING, "attempt to initialize memory in"
598 " BSS section `%s': ignored", s->name);
599 s->len += realsize(type, size);
600 return;
603 memset(mydata, 0, sizeof(mydata));
605 if (dfmt && dfmt->debug_output) {
606 struct coff_DebugInfo dinfo;
607 dinfo.segto = segto;
608 dinfo.seg = segment;
609 dinfo.section = s;
611 if (type == OUT_ADDRESS)
612 dinfo.size = abs((int)size);
613 else
614 dinfo.size = realsize(type, size);
616 dfmt->debug_output(type, &dinfo);
619 if (type == OUT_RESERVE) {
620 if (s->data) {
621 nasm_error(ERR_WARNING, "uninitialised space declared in"
622 " non-BSS section `%s': zeroing", s->name);
623 coff_sect_write(s, NULL, size);
624 } else
625 s->len += size;
626 } else if (type == OUT_RAWDATA) {
627 if (segment != NO_SEG)
628 nasm_panic(0, "OUT_RAWDATA with other than NO_SEG");
629 coff_sect_write(s, data, size);
630 } else if (type == OUT_ADDRESS) {
631 int asize = abs((int)size);
632 if (!win64) {
633 if (asize != 4 && (segment != NO_SEG || wrt != NO_SEG)) {
634 nasm_error(ERR_NONFATAL, "COFF format does not support non-32-bit"
635 " relocations");
636 } else {
637 int32_t fix = 0;
638 if (segment != NO_SEG || wrt != NO_SEG) {
639 if (wrt != NO_SEG) {
640 nasm_error(ERR_NONFATAL, "COFF format does not support"
641 " WRT types");
642 } else if (segment % 2) {
643 nasm_error(ERR_NONFATAL, "COFF format does not support"
644 " segment base references");
645 } else
646 fix = coff_add_reloc(s, segment, IMAGE_REL_I386_DIR32);
648 p = mydata;
649 WRITELONG(p, *(int64_t *)data + fix);
650 coff_sect_write(s, mydata, asize);
652 } else {
653 int32_t fix = 0;
654 p = mydata;
655 if (asize == 8) {
656 if (wrt == imagebase_sect) {
657 nasm_error(ERR_NONFATAL, "operand size mismatch: 'wrt "
658 WRT_IMAGEBASE "' is a 32-bit operand");
660 fix = coff_add_reloc(s, segment, IMAGE_REL_AMD64_ADDR64);
661 WRITEDLONG(p, *(int64_t *)data + fix);
662 coff_sect_write(s, mydata, asize);
663 } else {
664 fix = coff_add_reloc(s, segment,
665 wrt == imagebase_sect ? IMAGE_REL_AMD64_ADDR32NB:
666 IMAGE_REL_AMD64_ADDR32);
667 WRITELONG(p, *(int64_t *)data + fix);
668 coff_sect_write(s, mydata, asize);
671 } else if (type == OUT_REL2ADR) {
672 nasm_error(ERR_NONFATAL, "COFF format does not support 16-bit"
673 " relocations");
674 } else if (type == OUT_REL4ADR) {
675 if (segment == segto && !(win64)) /* Acceptable for RIP-relative */
676 nasm_panic(0, "intra-segment OUT_REL4ADR");
677 else if (segment == NO_SEG && win32)
678 nasm_error(ERR_NONFATAL, "Win32 COFF does not correctly support"
679 " relative references to absolute addresses");
680 else {
681 int32_t fix = 0;
682 if (segment != NO_SEG && segment % 2) {
683 nasm_error(ERR_NONFATAL, "COFF format does not support"
684 " segment base references");
685 } else
686 fix = coff_add_reloc(s, segment,
687 win64 ? IMAGE_REL_AMD64_REL32 : IMAGE_REL_I386_REL32);
688 p = mydata;
689 if (win32 | win64) {
690 WRITELONG(p, *(int64_t *)data + 4 - size + fix);
691 } else {
692 WRITELONG(p, *(int64_t *)data - (size + s->len) + fix);
694 coff_sect_write(s, mydata, 4L);
700 static void coff_sect_write(struct coff_Section *sect,
701 const uint8_t *data, uint32_t len)
703 saa_wbytes(sect->data, data, len);
704 sect->len += len;
707 typedef struct tagString {
708 struct tagString *next;
709 int len;
710 char *String;
711 } STRING;
713 #define EXPORT_SECTION_NAME ".drectve"
714 #define EXPORT_SECTION_FLAGS INFO_FLAGS
716 * #define EXPORT_SECTION_NAME ".text"
717 * #define EXPORT_SECTION_FLAGS TEXT_FLAGS
720 static STRING *Exports = NULL;
721 static struct coff_Section *directive_sec;
722 static void AddExport(char *name)
724 STRING *rvp = Exports, *newS;
726 newS = (STRING *) nasm_malloc(sizeof(STRING));
727 newS->len = strlen(name);
728 newS->next = NULL;
729 newS->String = (char *)nasm_malloc(newS->len + 1);
730 strcpy(newS->String, name);
731 if (rvp == NULL) {
732 int i;
734 for (i = 0; i < coff_nsects; i++) {
735 if (!strcmp(EXPORT_SECTION_NAME, coff_sects[i]->name))
736 break;
739 if (i == coff_nsects)
740 i = coff_make_section(EXPORT_SECTION_NAME, EXPORT_SECTION_FLAGS);
742 directive_sec = coff_sects[i];
743 Exports = newS;
744 } else {
745 while (rvp->next) {
746 if (!strcmp(rvp->String, name))
747 return;
748 rvp = rvp->next;
750 rvp->next = newS;
754 static void BuildExportTable(STRING **rvp)
756 STRING *p, *t;
758 if (!rvp || !*rvp)
759 return;
761 list_for_each_safe(p, t, *rvp) {
762 coff_sect_write(directive_sec, (uint8_t *)"-export:", 8);
763 coff_sect_write(directive_sec, (uint8_t *)p->String, p->len);
764 coff_sect_write(directive_sec, (uint8_t *)" ", 1);
765 nasm_free(p->String);
766 nasm_free(p);
769 *rvp = NULL;
772 static int coff_directives(enum directives directive, char *value, int pass)
774 switch (directive) {
775 case D_EXPORT:
777 char *q, *name;
779 if (pass == 2)
780 return 1; /* ignore in pass two */
781 name = q = value;
782 while (*q && !nasm_isspace(*q))
783 q++;
784 if (nasm_isspace(*q)) {
785 *q++ = '\0';
786 while (*q && nasm_isspace(*q))
787 q++;
790 if (!*name) {
791 nasm_error(ERR_NONFATAL, "`export' directive requires export name");
792 return 1;
794 if (*q) {
795 nasm_error(ERR_NONFATAL, "unrecognized export qualifier `%s'", q);
796 return 1;
798 AddExport(name);
799 return 1;
801 case D_SAFESEH:
803 static int sxseg=-1;
804 int i;
806 if (!win32) /* Only applicable for -f win32 */
807 return 0;
809 if (sxseg == -1) {
810 for (i = 0; i < coff_nsects; i++)
811 if (!strcmp(".sxdata",coff_sects[i]->name))
812 break;
813 if (i == coff_nsects)
814 sxseg = coff_make_section(".sxdata", IMAGE_SCN_LNK_INFO);
815 else
816 sxseg = i;
819 * pass0 == 2 is the only time when the full set of symbols are
820 * guaranteed to be present; it is the final output pass.
822 if (pass0 == 2) {
823 uint32_t n;
824 saa_rewind(coff_syms);
825 for (n = 0; n < coff_nsyms; n++) {
826 struct coff_Symbol *sym = saa_rstruct(coff_syms);
827 bool equals;
830 * sym->strpos is biased by 4, because symbol
831 * table is prefixed with table length
833 if (sym->strpos >=4) {
834 char *name = nasm_malloc(sym->namlen+1);
835 saa_fread(coff_strs, sym->strpos-4, name, sym->namlen);
836 name[sym->namlen] = '\0';
837 equals = !strcmp(value,name);
838 nasm_free(name);
839 } else {
840 equals = !strcmp(value,sym->name);
843 if (equals) {
845 * this value arithmetics effectively reflects
846 * initsym in coff_write(): 2 for file, 1 for
847 * .absolute and two per each section
849 unsigned char value[4],*p=value;
850 WRITELONG(p,n + 2 + 1 + coff_nsects*2);
851 coff_sect_write(coff_sects[sxseg],value,4);
852 sym->type = 0x20;
853 break;
856 if (n == coff_nsyms) {
857 nasm_error(ERR_NONFATAL,
858 "`safeseh' directive requires valid symbol");
861 return 1;
863 default:
864 return 0;
868 /* handle relocations storm, valid for win32/64 only */
869 static inline void coff_adjust_relocs(struct coff_Section *s)
871 if (s->nrelocs < IMAGE_SCN_MAX_RELOC)
872 return;
873 #ifdef OF_COFF
874 else
876 if (ofmt == &of_coff)
877 nasm_fatal(0,
878 "Too many relocations (%d) for section `%s'",
879 s->nrelocs, s->name);
881 #endif
883 s->flags |= IMAGE_SCN_LNK_NRELOC_OVFL;
884 s->nrelocs++;
887 static void coff_write(void)
889 int32_t pos, sympos, vsize;
890 int i;
892 /* fill in the .drectve section with -export's */
893 BuildExportTable(&Exports);
895 if (win32) {
896 /* add default value for @feat.00, this allows to 'link /safeseh' */
897 uint32_t n;
899 saa_rewind(coff_syms);
900 for (n = 0; n < coff_nsyms; n++) {
901 struct coff_Symbol *sym = saa_rstruct(coff_syms);
902 if (sym->strpos == -1 && !strcmp("@feat.00",sym->name))
903 break;
905 if (n == coff_nsyms)
906 coff_deflabel("@feat.00", NO_SEG, 1, 0, NULL);
910 * Work out how big the file will get.
911 * Calculate the start of the `real' symbols at the same time.
912 * Check for massive relocations.
914 pos = 0x14 + 0x28 * coff_nsects;
915 initsym = 3; /* two for the file, one absolute */
916 for (i = 0; i < coff_nsects; i++) {
917 if (coff_sects[i]->data) {
918 coff_adjust_relocs(coff_sects[i]);
919 coff_sects[i]->pos = pos;
920 pos += coff_sects[i]->len;
921 coff_sects[i]->relpos = pos;
922 pos += 10 * coff_sects[i]->nrelocs;
923 } else
924 coff_sects[i]->pos = coff_sects[i]->relpos = 0L;
925 initsym += 2; /* two for each section */
927 sympos = pos;
930 * Output the COFF header.
932 if (win64)
933 i = IMAGE_FILE_MACHINE_AMD64;
934 else
935 i = IMAGE_FILE_MACHINE_I386;
936 fwriteint16_t(i, ofile); /* machine type */
937 fwriteint16_t(coff_nsects, ofile); /* number of sections */
938 fwriteint32_t(time(NULL), ofile); /* time stamp */
939 fwriteint32_t(sympos, ofile);
940 fwriteint32_t(coff_nsyms + initsym, ofile);
941 fwriteint16_t(0, ofile); /* no optional header */
942 /* Flags: 32-bit, no line numbers. Win32 doesn't even bother with them. */
943 fwriteint16_t((win32 | win64) ? 0 : 0x104, ofile);
946 * Output the section headers.
948 vsize = 0L;
949 for (i = 0; i < coff_nsects; i++) {
950 coff_section_header(coff_sects[i]->name, coff_sects[i]->namepos, vsize, coff_sects[i]->len,
951 coff_sects[i]->pos, coff_sects[i]->relpos,
952 coff_sects[i]->nrelocs, coff_sects[i]->flags);
953 vsize += coff_sects[i]->len;
957 * Output the sections and their relocations.
959 for (i = 0; i < coff_nsects; i++)
960 if (coff_sects[i]->data) {
961 saa_fpwrite(coff_sects[i]->data, ofile);
962 coff_write_relocs(coff_sects[i]);
966 * Output the symbol and string tables.
968 coff_write_symbols();
969 fwriteint32_t(strslen + 4, ofile); /* length includes length count */
970 saa_fpwrite(coff_strs, ofile);
973 static void coff_section_header(char *name, int32_t namepos, int32_t vsize,
974 int32_t datalen, int32_t datapos,
975 int32_t relpos, int nrelocs, int32_t flags)
977 char padname[8];
979 (void)vsize;
981 if (namepos == -1) {
982 strncpy(padname, name, 8);
983 nasm_write(padname, 8, ofile);
984 } else {
986 * If name is longer than 8 bytes, write '/' followed
987 * by offset into the strings table represented as
988 * decimal number.
990 namepos = namepos % 100000000;
991 padname[0] = '/';
992 padname[1] = '0' + (namepos / 1000000);
993 namepos = namepos % 1000000;
994 padname[2] = '0' + (namepos / 100000);
995 namepos = namepos % 100000;
996 padname[3] = '0' + (namepos / 10000);
997 namepos = namepos % 10000;
998 padname[4] = '0' + (namepos / 1000);
999 namepos = namepos % 1000;
1000 padname[5] = '0' + (namepos / 100);
1001 namepos = namepos % 100;
1002 padname[6] = '0' + (namepos / 10);
1003 namepos = namepos % 10;
1004 padname[7] = '0' + (namepos);
1005 nasm_write(padname, 8, ofile);
1008 fwriteint32_t(0, ofile); /* Virtual size field - set to 0 or vsize */
1009 fwriteint32_t(0L, ofile); /* RVA/offset - we ignore */
1010 fwriteint32_t(datalen, ofile);
1011 fwriteint32_t(datapos, ofile);
1012 fwriteint32_t(relpos, ofile);
1013 fwriteint32_t(0L, ofile); /* no line numbers - we don't do 'em */
1016 * a special case -- if there are too many relocs
1017 * we have to put IMAGE_SCN_MAX_RELOC here and write
1018 * the real relocs number into VirtualAddress of first
1019 * relocation
1021 if (flags & IMAGE_SCN_LNK_NRELOC_OVFL)
1022 fwriteint16_t(IMAGE_SCN_MAX_RELOC, ofile);
1023 else
1024 fwriteint16_t(nrelocs, ofile);
1026 fwriteint16_t(0, ofile); /* again, no line numbers */
1027 fwriteint32_t(flags, ofile);
1030 static void coff_write_relocs(struct coff_Section *s)
1032 struct coff_Reloc *r;
1034 /* a real number of relocations if needed */
1035 if (s->flags & IMAGE_SCN_LNK_NRELOC_OVFL) {
1036 fwriteint32_t(s->nrelocs, ofile);
1037 fwriteint32_t(0, ofile);
1038 fwriteint16_t(0, ofile);
1041 for (r = s->head; r; r = r->next) {
1042 fwriteint32_t(r->address, ofile);
1043 fwriteint32_t(r->symbol + (r->symbase == REAL_SYMBOLS ? initsym :
1044 r->symbase == ABS_SYMBOL ? initsym - 1 :
1045 r->symbase == SECT_SYMBOLS ? 2 : 0),
1046 ofile);
1047 fwriteint16_t(r->type, ofile);
1051 static void coff_symbol(char *name, int32_t strpos, int32_t value,
1052 int section, int type, int storageclass, int aux)
1054 char padname[8];
1056 if (name) {
1057 strncpy(padname, name, 8);
1058 nasm_write(padname, 8, ofile);
1059 } else {
1060 fwriteint32_t(0, ofile);
1061 fwriteint32_t(strpos, ofile);
1064 fwriteint32_t(value, ofile);
1065 fwriteint16_t(section, ofile);
1066 fwriteint16_t(type, ofile);
1068 fputc(storageclass, ofile);
1069 fputc(aux, ofile);
1072 static void coff_write_symbols(void)
1074 char filename[18];
1075 uint32_t i;
1078 * The `.file' record, and the file name auxiliary record.
1080 coff_symbol(".file", 0L, 0L, -2, 0, 0x67, 1);
1081 strncpy(filename, coff_infile, 18);
1082 nasm_write(filename, 18, ofile);
1085 * The section records, with their auxiliaries.
1087 memset(filename, 0, 18); /* useful zeroed buffer */
1089 for (i = 0; i < (uint32_t) coff_nsects; i++) {
1090 coff_symbol(coff_sects[i]->name, 0L, 0L, i + 1, 0, 3, 1);
1091 fwriteint32_t(coff_sects[i]->len, ofile);
1092 fwriteint16_t(coff_sects[i]->nrelocs,ofile);
1093 nasm_write(filename, 12, ofile);
1097 * The absolute symbol, for relative-to-absolute relocations.
1099 coff_symbol(".absolut", 0L, 0L, -1, 0, 3, 0);
1102 * The real symbols.
1104 saa_rewind(coff_syms);
1105 for (i = 0; i < coff_nsyms; i++) {
1106 struct coff_Symbol *sym = saa_rstruct(coff_syms);
1107 coff_symbol(sym->strpos == -1 ? sym->name : NULL,
1108 sym->strpos, sym->value, sym->section,
1109 sym->type, sym->is_global ? 2 : 3, 0);
1113 static void coff_sectalign(int32_t seg, unsigned int value)
1115 struct coff_Section *s = NULL;
1116 uint32_t align;
1117 int i;
1119 for (i = 0; i < coff_nsects; i++) {
1120 if (coff_sects[i]->index == seg) {
1121 s = coff_sects[i];
1122 break;
1126 if (!s || !is_power2(value))
1127 return;
1129 /* DOS has limitation on 64 bytes */
1130 if (!(win32 | win64) && value > 64)
1131 return;
1133 align = (s->flags & IMAGE_SCN_ALIGN_MASK);
1134 value = coff_sectalign_flags(value);
1135 if (value > align)
1136 s->flags = (s->flags & ~IMAGE_SCN_ALIGN_MASK) | value;
1139 static int32_t coff_segbase(int32_t segment)
1141 return segment;
1144 static void coff_std_filename(char *inname, char *outname)
1146 strcpy(coff_infile, inname);
1147 standard_extension(inname, outname, ".o");
1148 strcpy(coff_outfile, outname);
1151 static void coff_win32_filename(char *inname, char *outname)
1153 strcpy(coff_infile, inname);
1154 standard_extension(inname, outname, ".obj");
1155 strcpy(coff_outfile, outname);
1158 extern macros_t coff_stdmac[];
1160 static int coff_set_info(enum geninfo type, char **val)
1162 (void)type;
1163 (void)val;
1164 return 0;
1166 #endif /* defined(OF_COFF) || defined(OF_WIN32) */
1168 #ifdef OF_COFF
1170 struct ofmt of_coff = {
1171 "COFF (i386) object files (e.g. DJGPP for DOS)",
1172 "coff",
1175 null_debug_arr,
1176 &null_debug_form,
1177 coff_stdmac,
1178 coff_std_init,
1179 coff_set_info,
1180 coff_out,
1181 coff_deflabel,
1182 coff_section_names,
1183 coff_sectalign,
1184 coff_segbase,
1185 coff_directives,
1186 coff_std_filename,
1187 coff_cleanup
1190 #endif
1192 extern struct dfmt df_cv8;
1194 #ifdef OF_WIN32
1196 struct dfmt *win32_debug_arr[2] = { &df_cv8, NULL };
1198 struct ofmt of_win32 = {
1199 "Microsoft Win32 (i386) object files",
1200 "win32",
1203 win32_debug_arr,
1204 &df_cv8,
1205 coff_stdmac,
1206 coff_win32_init,
1207 coff_set_info,
1208 coff_out,
1209 coff_deflabel,
1210 coff_section_names,
1211 coff_sectalign,
1212 coff_segbase,
1213 coff_directives,
1214 coff_win32_filename,
1215 coff_cleanup
1218 #endif
1220 #ifdef OF_WIN64
1222 struct dfmt *win64_debug_arr[2] = { &df_cv8, NULL };
1224 struct ofmt of_win64 = {
1225 "Microsoft Win64 (x86-64) object files",
1226 "win64",
1229 win64_debug_arr,
1230 &df_cv8,
1231 coff_stdmac,
1232 coff_win64_init,
1233 coff_set_info,
1234 coff_out,
1235 coff_deflabel,
1236 coff_section_names,
1237 coff_sectalign,
1238 coff_segbase,
1239 coff_directives,
1240 coff_win32_filename,
1241 coff_cleanup
1244 #endif