ilog2(): inline functions if practical
[nasm/externdefs2.git] / output / outcoff.c
blobd3a1b22cc29411dc020b0d252c648fc148c12147
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>
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"
109 char coff_infile[FILENAME_MAX];
110 char coff_outfile[FILENAME_MAX];
113 * Some common section flags by default
115 #define TEXT_FLAGS_WIN \
116 (IMAGE_SCN_CNT_CODE | \
117 IMAGE_SCN_ALIGN_16BYTES | \
118 IMAGE_SCN_MEM_EXECUTE | \
119 IMAGE_SCN_MEM_READ)
120 #define TEXT_FLAGS_DOS \
121 (IMAGE_SCN_CNT_CODE)
123 #define DATA_FLAGS_WIN \
124 (IMAGE_SCN_CNT_INITIALIZED_DATA | \
125 IMAGE_SCN_ALIGN_4BYTES | \
126 IMAGE_SCN_MEM_READ | \
127 IMAGE_SCN_MEM_WRITE)
128 #define DATA_FLAGS_DOS \
129 (IMAGE_SCN_CNT_INITIALIZED_DATA)
131 #define BSS_FLAGS_WIN \
132 (IMAGE_SCN_CNT_UNINITIALIZED_DATA | \
133 IMAGE_SCN_ALIGN_4BYTES | \
134 IMAGE_SCN_MEM_READ | \
135 IMAGE_SCN_MEM_WRITE)
136 #define BSS_FLAGS_DOS \
137 (IMAGE_SCN_CNT_UNINITIALIZED_DATA)
139 #define RDATA_FLAGS_WIN \
140 (IMAGE_SCN_CNT_INITIALIZED_DATA | \
141 IMAGE_SCN_ALIGN_8BYTES | \
142 IMAGE_SCN_MEM_READ)
144 #define RDATA_FLAGS_DOS \
145 (IMAGE_SCN_CNT_INITIALIZED_DATA)
147 #define PDATA_FLAGS \
148 (IMAGE_SCN_CNT_INITIALIZED_DATA | \
149 IMAGE_SCN_ALIGN_4BYTES | \
150 IMAGE_SCN_MEM_READ)
152 #define XDATA_FLAGS \
153 (IMAGE_SCN_CNT_INITIALIZED_DATA | \
154 IMAGE_SCN_ALIGN_8BYTES | \
155 IMAGE_SCN_MEM_READ)
157 #define INFO_FLAGS \
158 (IMAGE_SCN_ALIGN_1BYTES | \
159 IMAGE_SCN_LNK_INFO | \
160 IMAGE_SCN_LNK_REMOVE)
162 #define TEXT_FLAGS ((win32 | win64) ? TEXT_FLAGS_WIN : TEXT_FLAGS_DOS)
163 #define DATA_FLAGS ((win32 | win64) ? DATA_FLAGS_WIN : DATA_FLAGS_DOS)
164 #define BSS_FLAGS ((win32 | win64) ? BSS_FLAGS_WIN : BSS_FLAGS_DOS)
165 #define RDATA_FLAGS ((win32 | win64) ? RDATA_FLAGS_WIN : RDATA_FLAGS_DOS)
167 #define SECT_DELTA 32
168 struct coff_Section **coff_sects;
169 static int sectlen;
170 int coff_nsects;
172 struct SAA *coff_syms;
173 uint32_t coff_nsyms;
175 static int32_t def_seg;
177 static int initsym;
179 static struct RAA *bsym, *symval;
181 struct SAA *coff_strs;
182 static uint32_t strslen;
184 static void coff_gen_init(void);
185 static void coff_sect_write(struct coff_Section *, const uint8_t *, uint32_t);
186 static void coff_write(void);
187 static void coff_section_header(char *, int32_t, int32_t, int32_t, int32_t, int32_t, int, int32_t);
188 static void coff_write_relocs(struct coff_Section *);
189 static void coff_write_symbols(void);
191 static void coff_win32_init(void)
193 win32 = true;
194 win64 = false;
195 coff_gen_init();
198 static void coff_win64_init(void)
200 win32 = false;
201 win64 = true;
202 coff_gen_init();
203 imagebase_sect = seg_alloc()+1;
204 define_label(WRT_IMAGEBASE, imagebase_sect, 0, NULL, false, false);
207 static void coff_std_init(void)
209 win32 = win64 = false;
210 coff_gen_init();
213 static void coff_gen_init(void)
216 coff_sects = NULL;
217 coff_nsects = sectlen = 0;
218 coff_syms = saa_init(sizeof(struct coff_Symbol));
219 coff_nsyms = 0;
220 bsym = raa_init();
221 symval = raa_init();
222 coff_strs = saa_init(1);
223 strslen = 0;
224 def_seg = seg_alloc();
227 static void coff_cleanup(void)
229 struct coff_Reloc *r;
230 int i;
232 dfmt->cleanup();
234 coff_write();
235 for (i = 0; i < coff_nsects; i++) {
236 if (coff_sects[i]->data)
237 saa_free(coff_sects[i]->data);
238 while (coff_sects[i]->head) {
239 r = coff_sects[i]->head;
240 coff_sects[i]->head = coff_sects[i]->head->next;
241 nasm_free(r);
243 nasm_free(coff_sects[i]->name);
244 nasm_free(coff_sects[i]);
246 nasm_free(coff_sects);
247 saa_free(coff_syms);
248 raa_free(bsym);
249 raa_free(symval);
250 saa_free(coff_strs);
253 int coff_make_section(char *name, uint32_t flags)
255 struct coff_Section *s;
256 size_t namelen;
258 s = nasm_zalloc(sizeof(*s));
260 if (flags != BSS_FLAGS)
261 s->data = saa_init(1);
262 s->tail = &s->head;
263 if (!strcmp(name, ".text"))
264 s->index = def_seg;
265 else
266 s->index = seg_alloc();
267 s->namepos = -1;
268 namelen = strlen(name);
269 if (namelen > 8) {
270 if (win32 || win64) {
271 s->namepos = strslen + 4;
272 saa_wbytes(coff_strs, name, namelen + 1);
273 strslen += namelen + 1;
274 } else {
275 namelen = 8;
278 s->name = nasm_malloc(namelen + 1);
279 strncpy(s->name, name, namelen);
280 s->name[namelen] = '\0';
281 s->flags = flags;
283 if (coff_nsects >= sectlen) {
284 sectlen += SECT_DELTA;
285 coff_sects = nasm_realloc(coff_sects, sectlen * sizeof(*coff_sects));
287 coff_sects[coff_nsects++] = s;
289 return coff_nsects - 1;
292 static inline int32_t coff_sectalign_flags(unsigned int align)
294 return (ilog2_32(align) + 1) << 20;
297 static int32_t coff_section_names(char *name, int pass, int *bits)
299 char *p;
300 uint32_t flags, align_and = ~0L, align_or = 0L;
301 int i;
304 * Set default bits.
306 if (!name) {
307 if(win64)
308 *bits = 64;
309 else
310 *bits = 32;
312 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 enum directive_result
773 coff_directives(enum directive directive, char *value, int pass)
775 switch (directive) {
776 case D_EXPORT:
778 char *q, *name;
780 if (pass == 2)
781 return DIRR_OK; /* ignore in pass two */
782 name = q = value;
783 while (*q && !nasm_isspace(*q))
784 q++;
785 if (nasm_isspace(*q)) {
786 *q++ = '\0';
787 while (*q && nasm_isspace(*q))
788 q++;
791 if (!*name) {
792 nasm_error(ERR_NONFATAL, "`export' directive requires export name");
793 return DIRR_ERROR;
795 if (*q) {
796 nasm_error(ERR_NONFATAL, "unrecognized export qualifier `%s'", q);
797 return DIRR_ERROR;
799 AddExport(name);
800 return DIRR_OK;
802 case D_SAFESEH:
804 static int sxseg=-1;
805 int i;
807 if (!win32) /* Only applicable for -f win32 */
808 return 0;
810 if (sxseg == -1) {
811 for (i = 0; i < coff_nsects; i++)
812 if (!strcmp(".sxdata",coff_sects[i]->name))
813 break;
814 if (i == coff_nsects)
815 sxseg = coff_make_section(".sxdata", IMAGE_SCN_LNK_INFO);
816 else
817 sxseg = i;
820 * pass0 == 2 is the only time when the full set of symbols are
821 * guaranteed to be present; it is the final output pass.
823 if (pass0 == 2) {
824 uint32_t n;
825 saa_rewind(coff_syms);
826 for (n = 0; n < coff_nsyms; n++) {
827 struct coff_Symbol *sym = saa_rstruct(coff_syms);
828 bool equals;
831 * sym->strpos is biased by 4, because symbol
832 * table is prefixed with table length
834 if (sym->strpos >=4) {
835 char *name = nasm_malloc(sym->namlen+1);
836 saa_fread(coff_strs, sym->strpos-4, name, sym->namlen);
837 name[sym->namlen] = '\0';
838 equals = !strcmp(value,name);
839 nasm_free(name);
840 } else {
841 equals = !strcmp(value,sym->name);
844 if (equals) {
846 * this value arithmetics effectively reflects
847 * initsym in coff_write(): 2 for file, 1 for
848 * .absolute and two per each section
850 unsigned char value[4],*p=value;
851 WRITELONG(p,n + 2 + 1 + coff_nsects*2);
852 coff_sect_write(coff_sects[sxseg],value,4);
853 sym->type = 0x20;
854 break;
857 if (n == coff_nsyms) {
858 nasm_error(ERR_NONFATAL,
859 "`safeseh' directive requires valid symbol");
860 return DIRR_ERROR;
863 return DIRR_OK;
865 default:
866 return DIRR_UNKNOWN;
870 /* handle relocations storm, valid for win32/64 only */
871 static inline void coff_adjust_relocs(struct coff_Section *s)
873 if (s->nrelocs < IMAGE_SCN_MAX_RELOC)
874 return;
875 #ifdef OF_COFF
876 else
878 if (ofmt == &of_coff)
879 nasm_fatal(0,
880 "Too many relocations (%d) for section `%s'",
881 s->nrelocs, s->name);
883 #endif
885 s->flags |= IMAGE_SCN_LNK_NRELOC_OVFL;
886 s->nrelocs++;
889 static void coff_write(void)
891 int32_t pos, sympos, vsize;
892 int i;
894 /* fill in the .drectve section with -export's */
895 BuildExportTable(&Exports);
897 if (win32) {
898 /* add default value for @feat.00, this allows to 'link /safeseh' */
899 uint32_t n;
901 saa_rewind(coff_syms);
902 for (n = 0; n < coff_nsyms; n++) {
903 struct coff_Symbol *sym = saa_rstruct(coff_syms);
904 if (sym->strpos == -1 && !strcmp("@feat.00",sym->name))
905 break;
907 if (n == coff_nsyms)
908 coff_deflabel("@feat.00", NO_SEG, 1, 0, NULL);
912 * Work out how big the file will get.
913 * Calculate the start of the `real' symbols at the same time.
914 * Check for massive relocations.
916 pos = 0x14 + 0x28 * coff_nsects;
917 initsym = 3; /* two for the file, one absolute */
918 for (i = 0; i < coff_nsects; i++) {
919 if (coff_sects[i]->data) {
920 coff_adjust_relocs(coff_sects[i]);
921 coff_sects[i]->pos = pos;
922 pos += coff_sects[i]->len;
923 coff_sects[i]->relpos = pos;
924 pos += 10 * coff_sects[i]->nrelocs;
925 } else
926 coff_sects[i]->pos = coff_sects[i]->relpos = 0L;
927 initsym += 2; /* two for each section */
929 sympos = pos;
932 * Output the COFF header.
934 if (win64)
935 i = IMAGE_FILE_MACHINE_AMD64;
936 else
937 i = IMAGE_FILE_MACHINE_I386;
938 fwriteint16_t(i, ofile); /* machine type */
939 fwriteint16_t(coff_nsects, ofile); /* number of sections */
940 fwriteint32_t(time(NULL), ofile); /* time stamp */
941 fwriteint32_t(sympos, ofile);
942 fwriteint32_t(coff_nsyms + initsym, ofile);
943 fwriteint16_t(0, ofile); /* no optional header */
944 /* Flags: 32-bit, no line numbers. Win32 doesn't even bother with them. */
945 fwriteint16_t((win32 | win64) ? 0 : 0x104, ofile);
948 * Output the section headers.
950 vsize = 0L;
951 for (i = 0; i < coff_nsects; i++) {
952 coff_section_header(coff_sects[i]->name, coff_sects[i]->namepos, vsize, coff_sects[i]->len,
953 coff_sects[i]->pos, coff_sects[i]->relpos,
954 coff_sects[i]->nrelocs, coff_sects[i]->flags);
955 vsize += coff_sects[i]->len;
959 * Output the sections and their relocations.
961 for (i = 0; i < coff_nsects; i++)
962 if (coff_sects[i]->data) {
963 saa_fpwrite(coff_sects[i]->data, ofile);
964 coff_write_relocs(coff_sects[i]);
968 * Output the symbol and string tables.
970 coff_write_symbols();
971 fwriteint32_t(strslen + 4, ofile); /* length includes length count */
972 saa_fpwrite(coff_strs, ofile);
975 static void coff_section_header(char *name, int32_t namepos, int32_t vsize,
976 int32_t datalen, int32_t datapos,
977 int32_t relpos, int nrelocs, int32_t flags)
979 char padname[8];
981 (void)vsize;
983 if (namepos == -1) {
984 strncpy(padname, name, 8);
985 nasm_write(padname, 8, ofile);
986 } else {
988 * If name is longer than 8 bytes, write '/' followed
989 * by offset into the strings table represented as
990 * decimal number.
992 namepos = namepos % 100000000;
993 padname[0] = '/';
994 padname[1] = '0' + (namepos / 1000000);
995 namepos = namepos % 1000000;
996 padname[2] = '0' + (namepos / 100000);
997 namepos = namepos % 100000;
998 padname[3] = '0' + (namepos / 10000);
999 namepos = namepos % 10000;
1000 padname[4] = '0' + (namepos / 1000);
1001 namepos = namepos % 1000;
1002 padname[5] = '0' + (namepos / 100);
1003 namepos = namepos % 100;
1004 padname[6] = '0' + (namepos / 10);
1005 namepos = namepos % 10;
1006 padname[7] = '0' + (namepos);
1007 nasm_write(padname, 8, ofile);
1010 fwriteint32_t(0, ofile); /* Virtual size field - set to 0 or vsize */
1011 fwriteint32_t(0L, ofile); /* RVA/offset - we ignore */
1012 fwriteint32_t(datalen, ofile);
1013 fwriteint32_t(datapos, ofile);
1014 fwriteint32_t(relpos, ofile);
1015 fwriteint32_t(0L, ofile); /* no line numbers - we don't do 'em */
1018 * a special case -- if there are too many relocs
1019 * we have to put IMAGE_SCN_MAX_RELOC here and write
1020 * the real relocs number into VirtualAddress of first
1021 * relocation
1023 if (flags & IMAGE_SCN_LNK_NRELOC_OVFL)
1024 fwriteint16_t(IMAGE_SCN_MAX_RELOC, ofile);
1025 else
1026 fwriteint16_t(nrelocs, ofile);
1028 fwriteint16_t(0, ofile); /* again, no line numbers */
1029 fwriteint32_t(flags, ofile);
1032 static void coff_write_relocs(struct coff_Section *s)
1034 struct coff_Reloc *r;
1036 /* a real number of relocations if needed */
1037 if (s->flags & IMAGE_SCN_LNK_NRELOC_OVFL) {
1038 fwriteint32_t(s->nrelocs, ofile);
1039 fwriteint32_t(0, ofile);
1040 fwriteint16_t(0, ofile);
1043 for (r = s->head; r; r = r->next) {
1044 fwriteint32_t(r->address, ofile);
1045 fwriteint32_t(r->symbol + (r->symbase == REAL_SYMBOLS ? initsym :
1046 r->symbase == ABS_SYMBOL ? initsym - 1 :
1047 r->symbase == SECT_SYMBOLS ? 2 : 0),
1048 ofile);
1049 fwriteint16_t(r->type, ofile);
1053 static void coff_symbol(char *name, int32_t strpos, int32_t value,
1054 int section, int type, int storageclass, int aux)
1056 char padname[8];
1058 if (name) {
1059 strncpy(padname, name, 8);
1060 nasm_write(padname, 8, ofile);
1061 } else {
1062 fwriteint32_t(0, ofile);
1063 fwriteint32_t(strpos, ofile);
1066 fwriteint32_t(value, ofile);
1067 fwriteint16_t(section, ofile);
1068 fwriteint16_t(type, ofile);
1070 fputc(storageclass, ofile);
1071 fputc(aux, ofile);
1074 static void coff_write_symbols(void)
1076 char filename[18];
1077 uint32_t i;
1080 * The `.file' record, and the file name auxiliary record.
1082 coff_symbol(".file", 0L, 0L, -2, 0, 0x67, 1);
1083 strncpy(filename, coff_infile, 18);
1084 nasm_write(filename, 18, ofile);
1087 * The section records, with their auxiliaries.
1089 memset(filename, 0, 18); /* useful zeroed buffer */
1091 for (i = 0; i < (uint32_t) coff_nsects; i++) {
1092 coff_symbol(coff_sects[i]->name, 0L, 0L, i + 1, 0, 3, 1);
1093 fwriteint32_t(coff_sects[i]->len, ofile);
1094 fwriteint16_t(coff_sects[i]->nrelocs,ofile);
1095 nasm_write(filename, 12, ofile);
1099 * The absolute symbol, for relative-to-absolute relocations.
1101 coff_symbol(".absolut", 0L, 0L, -1, 0, 3, 0);
1104 * The real symbols.
1106 saa_rewind(coff_syms);
1107 for (i = 0; i < coff_nsyms; i++) {
1108 struct coff_Symbol *sym = saa_rstruct(coff_syms);
1109 coff_symbol(sym->strpos == -1 ? sym->name : NULL,
1110 sym->strpos, sym->value, sym->section,
1111 sym->type, sym->is_global ? 2 : 3, 0);
1115 static void coff_sectalign(int32_t seg, unsigned int value)
1117 struct coff_Section *s = NULL;
1118 uint32_t align;
1119 int i;
1121 for (i = 0; i < coff_nsects; i++) {
1122 if (coff_sects[i]->index == seg) {
1123 s = coff_sects[i];
1124 break;
1128 if (!s || !is_power2(value))
1129 return;
1131 /* DOS has limitation on 64 bytes */
1132 if (!(win32 | win64) && value > 64)
1133 return;
1135 align = (s->flags & IMAGE_SCN_ALIGN_MASK);
1136 value = coff_sectalign_flags(value);
1137 if (value > align)
1138 s->flags = (s->flags & ~IMAGE_SCN_ALIGN_MASK) | value;
1141 static int32_t coff_segbase(int32_t segment)
1143 return segment;
1146 static void coff_std_filename(char *inname, char *outname)
1148 strcpy(coff_infile, inname);
1149 standard_extension(inname, outname, ".o");
1150 strcpy(coff_outfile, outname);
1153 static void coff_win32_filename(char *inname, char *outname)
1155 strcpy(coff_infile, inname);
1156 standard_extension(inname, outname, ".obj");
1157 strcpy(coff_outfile, outname);
1160 extern macros_t coff_stdmac[];
1162 #endif /* defined(OF_COFF) || defined(OF_WIN32) */
1164 #ifdef OF_COFF
1166 const struct ofmt of_coff = {
1167 "COFF (i386) object files (e.g. DJGPP for DOS)",
1168 "coff",
1171 null_debug_arr,
1172 &null_debug_form,
1173 coff_stdmac,
1174 coff_std_init,
1175 nasm_do_legacy_output,
1176 coff_out,
1177 coff_deflabel,
1178 coff_section_names,
1179 coff_sectalign,
1180 coff_segbase,
1181 coff_directives,
1182 coff_std_filename,
1183 coff_cleanup,
1184 NULL /* pragma list */
1187 #endif
1189 extern const struct dfmt df_cv8;
1191 #ifdef OF_WIN32
1193 static const struct dfmt * const win32_debug_arr[2] = { &df_cv8, NULL };
1195 const struct ofmt of_win32 = {
1196 "Microsoft Win32 (i386) object files",
1197 "win32",
1200 win32_debug_arr,
1201 &df_cv8,
1202 coff_stdmac,
1203 coff_win32_init,
1204 nasm_do_legacy_output,
1205 coff_out,
1206 coff_deflabel,
1207 coff_section_names,
1208 coff_sectalign,
1209 coff_segbase,
1210 coff_directives,
1211 coff_win32_filename,
1212 coff_cleanup,
1213 NULL /* pragma list */
1216 #endif
1218 #ifdef OF_WIN64
1220 static const struct dfmt * const win64_debug_arr[2] = { &df_cv8, NULL };
1222 const struct ofmt of_win64 = {
1223 "Microsoft Win64 (x86-64) object files",
1224 "win64",
1227 win64_debug_arr,
1228 &df_cv8,
1229 coff_stdmac,
1230 coff_win64_init,
1231 nasm_do_legacy_output,
1232 coff_out,
1233 coff_deflabel,
1234 coff_section_names,
1235 coff_sectalign,
1236 coff_segbase,
1237 coff_directives,
1238 coff_win32_filename,
1239 coff_cleanup,
1240 NULL /* pragma list */
1243 #endif