1/* ----------------------------------------------------------------------- *
2 *
3 * Copyright 1996-2017 The NASM Authors - All Rights Reserved
4 * See the file AUTHORS included with the NASM distribution for
5 * the specific copyright holders.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following
9 * conditions are met:
10 *
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.
17 *
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.
31 *
32 * ----------------------------------------------------------------------- */
33
34/*
35 * outcoff.c output routines for the Netwide Assembler to produce
36 * COFF object files (for DJGPP and Win32)
37 */
38
39#include "compiler.h"
40
41#include <stdio.h>
42#include <stdlib.h>
43#include <string.h>
44#include <ctype.h>
45#include <time.h>
46
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"
57
58#if defined(OF_COFF) || defined(OF_WIN32) || defined(OF_WIN64)
59
60/*
61 * Notes on COFF:
62 *
63 * (0) When I say `standard COFF' below, I mean `COFF as output and
64 * used by DJGPP'. I assume DJGPP gets it right.
65 *
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.
74 *
75 * (2) Win32 doesn't bother putting any flags in the header flags
76 * field (at offset 0x12 into the file).
77 *
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.
83 *
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.
92 *
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.
95 *
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.
101 */
102
103/* Flag which version of COFF we are currently outputting. */
104bool win32, win64;
105
106static int32_t imagebase_sect;
107#define WRT_IMAGEBASE "..imagebase"
108
109/*
110 * Some common section flags by default
111 */
112#define TEXT_FLAGS_WIN \
113 (IMAGE_SCN_CNT_CODE | \
114 IMAGE_SCN_ALIGN_16BYTES | \
115 IMAGE_SCN_MEM_EXECUTE | \
116 IMAGE_SCN_MEM_READ)
117#define TEXT_FLAGS_DOS \
118 (IMAGE_SCN_CNT_CODE)
119
120#define DATA_FLAGS_WIN \
121 (IMAGE_SCN_CNT_INITIALIZED_DATA | \
122 IMAGE_SCN_ALIGN_4BYTES | \
123 IMAGE_SCN_MEM_READ | \
124 IMAGE_SCN_MEM_WRITE)
125#define DATA_FLAGS_DOS \
126 (IMAGE_SCN_CNT_INITIALIZED_DATA)
127
128#define BSS_FLAGS_WIN \
129 (IMAGE_SCN_CNT_UNINITIALIZED_DATA | \
130 IMAGE_SCN_ALIGN_4BYTES | \
131 IMAGE_SCN_MEM_READ | \
132 IMAGE_SCN_MEM_WRITE)
133#define BSS_FLAGS_DOS \
134 (IMAGE_SCN_CNT_UNINITIALIZED_DATA)
135
136#define RDATA_FLAGS_WIN \
137 (IMAGE_SCN_CNT_INITIALIZED_DATA | \
138 IMAGE_SCN_ALIGN_8BYTES | \
139 IMAGE_SCN_MEM_READ)
140
141#define RDATA_FLAGS_DOS \
142 (IMAGE_SCN_CNT_INITIALIZED_DATA)
143
144#define PDATA_FLAGS \
145 (IMAGE_SCN_CNT_INITIALIZED_DATA | \
146 IMAGE_SCN_ALIGN_4BYTES | \
147 IMAGE_SCN_MEM_READ)
148
149#define XDATA_FLAGS \
150 (IMAGE_SCN_CNT_INITIALIZED_DATA | \
151 IMAGE_SCN_ALIGN_8BYTES | \
152 IMAGE_SCN_MEM_READ)
153
154#define INFO_FLAGS \
155 (IMAGE_SCN_ALIGN_1BYTES | \
156 IMAGE_SCN_LNK_INFO | \
157 IMAGE_SCN_LNK_REMOVE)
158
159#define TEXT_FLAGS ((win32 | win64) ? TEXT_FLAGS_WIN : TEXT_FLAGS_DOS)
160#define DATA_FLAGS ((win32 | win64) ? DATA_FLAGS_WIN : DATA_FLAGS_DOS)
161#define BSS_FLAGS ((win32 | win64) ? BSS_FLAGS_WIN : BSS_FLAGS_DOS)
162#define RDATA_FLAGS ((win32 | win64) ? RDATA_FLAGS_WIN : RDATA_FLAGS_DOS)
163
164#define SECT_DELTA 32
165struct coff_Section **coff_sects;
166static int sectlen;
167int coff_nsects;
168
169struct SAA *coff_syms;
170uint32_t coff_nsyms;
171
172static int32_t def_seg;
173
174static int initsym;
175
176static struct RAA *bsym, *symval;
177
178struct SAA *coff_strs;
179static uint32_t strslen;
180
181static void coff_gen_init(void);
182static void coff_sect_write(struct coff_Section *, const uint8_t *, uint32_t);
183static void coff_write(void);
184static void coff_section_header(char *, int32_t, int32_t, int32_t, int32_t, int32_t, int, int32_t);
185static void coff_write_relocs(struct coff_Section *);
186static void coff_write_symbols(void);
187
188static void coff_win32_init(void)
189{
190 win32 = true;
191 win64 = false;
192 coff_gen_init();
193}
194
195static void coff_win64_init(void)
196{
197 win32 = false;
198 win64 = true;
199 coff_gen_init();
200 imagebase_sect = seg_alloc()+1;
201 backend_label(WRT_IMAGEBASE, imagebase_sect, 0);
202}
203
204static void coff_std_init(void)
205{
206 win32 = win64 = false;
207 coff_gen_init();
208}
209
210static void coff_gen_init(void)
211{
212
213 coff_sects = NULL;
214 coff_nsects = sectlen = 0;
215 coff_syms = saa_init(sizeof(struct coff_Symbol));
216 coff_nsyms = 0;
217 bsym = raa_init();
218 symval = raa_init();
219 coff_strs = saa_init(1);
220 strslen = 0;
221 def_seg = seg_alloc();
222}
223
224static void coff_cleanup(void)
225{
226 struct coff_Reloc *r;
227 int i;
228
229 dfmt->cleanup();
230
231 coff_write();
232 for (i = 0; i < coff_nsects; i++) {
233 if (coff_sects[i]->data)
234 saa_free(coff_sects[i]->data);
235 while (coff_sects[i]->head) {
236 r = coff_sects[i]->head;
237 coff_sects[i]->head = coff_sects[i]->head->next;
238 nasm_free(r);
239 }
240 nasm_free(coff_sects[i]->name);
241 nasm_free(coff_sects[i]);
242 }
243 nasm_free(coff_sects);
244 saa_free(coff_syms);
245 raa_free(bsym);
246 raa_free(symval);
247 saa_free(coff_strs);
248}
249
250int coff_make_section(char *name, uint32_t flags)
251{
252 struct coff_Section *s;
253 size_t namelen;
254
255 s = nasm_zalloc(sizeof(*s));
256
257 if (flags != BSS_FLAGS)
258 s->data = saa_init(1);
259 s->tail = &s->head;
260 if (!strcmp(name, ".text"))
261 s->index = def_seg;
262 else
263 s->index = seg_alloc();
264 s->namepos = -1;
265 namelen = strlen(name);
266 if (namelen > 8) {
267 if (win32 || win64) {
268 s->namepos = strslen + 4;
269 saa_wbytes(coff_strs, name, namelen + 1);
270 strslen += namelen + 1;
271 } else {
272 namelen = 8;
273 }
274 }
275 s->name = nasm_malloc(namelen + 1);
276 strncpy(s->name, name, namelen);
277 s->name[namelen] = '\0';
278 s->flags = flags;
279
280 if (coff_nsects >= sectlen) {
281 sectlen += SECT_DELTA;
282 coff_sects = nasm_realloc(coff_sects, sectlen * sizeof(*coff_sects));
283 }
284 coff_sects[coff_nsects++] = s;
285
286 return coff_nsects - 1;
287}
288
289static inline int32_t coff_sectalign_flags(unsigned int align)
290{
291 return (ilog2_32(align) + 1) << 20;
292}
293
294static int32_t coff_section_names(char *name, int pass, int *bits)
295{
296 char *p;
297 uint32_t flags, align_and = ~0L, align_or = 0L;
298 int i;
299
300 /*
301 * Set default bits.
302 */
303 if (!name) {
304 if(win64)
305 *bits = 64;
306 else
307 *bits = 32;
308
309 return def_seg;
310 }
311
312 p = name;
313 while (*p && !nasm_isspace(*p))
314 p++;
315 if (*p)
316 *p++ = '\0';
317 if (strlen(name) > 8) {
318 if (!win32 && !win64) {
319 nasm_error(ERR_WARNING,
320 "COFF section names limited to 8 characters: truncating");
321 name[8] = '\0';
322 }
323 }
324 flags = 0;
325
326 while (*p && nasm_isspace(*p))
327 p++;
328 while (*p) {
329 char *q = p;
330 while (*p && !nasm_isspace(*p))
331 p++;
332 if (*p)
333 *p++ = '\0';
334 while (*p && nasm_isspace(*p))
335 p++;
336
337 if (!nasm_stricmp(q, "code") || !nasm_stricmp(q, "text")) {
338 flags = TEXT_FLAGS;
339 } else if (!nasm_stricmp(q, "data")) {
340 flags = DATA_FLAGS;
341 } else if (!nasm_stricmp(q, "rdata")) {
342 if (win32 | win64)
343 flags = RDATA_FLAGS;
344 else {
345 flags = DATA_FLAGS; /* gotta do something */
346 nasm_error(ERR_NONFATAL, "standard COFF does not support"
347 " read-only data sections");
348 }
349 } else if (!nasm_stricmp(q, "bss")) {
350 flags = BSS_FLAGS;
351 } else if (!nasm_stricmp(q, "info")) {
352 if (win32 | win64)
353 flags = INFO_FLAGS;
354 else {
355 flags = DATA_FLAGS; /* gotta do something */
356 nasm_error(ERR_NONFATAL, "standard COFF does not support"
357 " informational sections");
358 }
359 } else if (!nasm_strnicmp(q, "align=", 6)) {
360 if (!(win32 | win64))
361 nasm_error(ERR_NONFATAL, "standard COFF does not support"
362 " section alignment specification");
363 else {
364 if (q[6 + strspn(q + 6, "0123456789")])
365 nasm_error(ERR_NONFATAL,
366 "argument to `align' is not numeric");
367 else {
368 unsigned int align = atoi(q + 6);
369 if (!align || ((align - 1) & align))
370 nasm_error(ERR_NONFATAL, "argument to `align' is not a"
371 " power of two");
372 else if (align > 64)
373 nasm_error(ERR_NONFATAL, "Win32 cannot align sections"
374 " to better than 64-byte boundaries");
375 else {
376 align_and = ~0x00F00000L;
377 align_or = coff_sectalign_flags(align);
378 }
379 }
380 }
381 }
382 }
383
384 for (i = 0; i < coff_nsects; i++)
385 if (!strcmp(name, coff_sects[i]->name))
386 break;
387 if (i == coff_nsects) {
388 if (!flags) {
389 if (!strcmp(name, ".data"))
390 flags = DATA_FLAGS;
391 else if (!strcmp(name, ".rdata"))
392 flags = RDATA_FLAGS;
393 else if (!strcmp(name, ".bss"))
394 flags = BSS_FLAGS;
395 else if (win64 && !strcmp(name, ".pdata"))
396 flags = PDATA_FLAGS;
397 else if (win64 && !strcmp(name, ".xdata"))
398 flags = XDATA_FLAGS;
399 else
400 flags = TEXT_FLAGS;
401 }
402 i = coff_make_section(name, flags);
403 if (flags)
404 coff_sects[i]->flags = flags;
405 coff_sects[i]->flags &= align_and;
406 coff_sects[i]->flags |= align_or;
407 } else if (pass == 1) {
408 /* Check if any flags are specified */
409 if (flags) {
410 unsigned int align_flags = flags & IMAGE_SCN_ALIGN_MASK;
411
412 /* Warn if non-alignment flags differ */
413 if ((flags ^ coff_sects[i]->flags) & ~IMAGE_SCN_ALIGN_MASK) {
414 nasm_error(ERR_WARNING, "section attributes ignored on"
415 " redeclaration of section `%s'", name);
416 }
417 /* Check if alignment might be needed */
418 if (align_flags > IMAGE_SCN_ALIGN_1BYTES) {
419 unsigned int sect_align_flags = coff_sects[i]->flags & IMAGE_SCN_ALIGN_MASK;
420
421 /* Compute the actual alignment */
422 unsigned int align = 1u << ((align_flags - IMAGE_SCN_ALIGN_1BYTES) >> 20);
423
424 /* Update section header as needed */
425 if (align_flags > sect_align_flags) {
426 coff_sects[i]->flags = (coff_sects[i]->flags & ~IMAGE_SCN_ALIGN_MASK) | align_flags;
427 }
428 /* Check if not already aligned */
429 if (coff_sects[i]->len % align) {
430 unsigned int padding = (align - coff_sects[i]->len) % align;
431 /* We need to write at most 8095 bytes */
432 char buffer[8095];
433 if (coff_sects[i]->flags & IMAGE_SCN_CNT_CODE) {
434 /* Fill with INT 3 instructions */
435 memset(buffer, 0xCC, padding);
436 } else {
437 memset(buffer, 0x00, padding);
438 }
439 saa_wbytes(coff_sects[i]->data, buffer, padding);
440 coff_sects[i]->len += padding;
441 }
442 }
443 }
444 }
445
446 return coff_sects[i]->index;
447}
448
449static void coff_deflabel(char *name, int32_t segment, int64_t offset,
450 int is_global, char *special)
451{
452 int pos = strslen + 4;
453 struct coff_Symbol *sym;
454
455 if (special)
456 nasm_error(ERR_NONFATAL, "COFF format does not support any"
457 " special symbol types");
458
459 if (name[0] == '.' && name[1] == '.' && name[2] != '@') {
460 if (strcmp(name,WRT_IMAGEBASE))
461 nasm_error(ERR_NONFATAL, "unrecognized special symbol `%s'", name);
462 return;
463 }
464
465 if (strlen(name) > 8) {
466 size_t nlen = strlen(name)+1;
467 saa_wbytes(coff_strs, name, nlen);
468 strslen += nlen;
469 } else
470 pos = -1;
471
472 sym = saa_wstruct(coff_syms);
473
474 sym->strpos = pos;
475 sym->namlen = strlen(name);
476 if (pos == -1)
477 strcpy(sym->name, name);
478 sym->is_global = !!is_global;
479 sym->type = 0; /* Default to T_NULL (no type) */
480 if (segment == NO_SEG)
481 sym->section = -1; /* absolute symbol */
482 else {
483 int i;
484 sym->section = 0;
485 for (i = 0; i < coff_nsects; i++)
486 if (segment == coff_sects[i]->index) {
487 sym->section = i + 1;
488 break;
489 }
490 if (!sym->section)
491 sym->is_global = true;
492 }
493 if (is_global == 2)
494 sym->value = offset;
495 else
496 sym->value = (sym->section == 0 ? 0 : offset);
497
498 /*
499 * define the references from external-symbol segment numbers
500 * to these symbol records.
501 */
502 if (sym->section == 0)
503 bsym = raa_write(bsym, segment, coff_nsyms);
504
505 if (segment != NO_SEG)
506 symval = raa_write(symval, segment, sym->section ? 0 : sym->value);
507
508 coff_nsyms++;
509}
510
511static int32_t coff_add_reloc(struct coff_Section *sect, int32_t segment,
512 int16_t type)
513{
514 struct coff_Reloc *r;
515
516 r = *sect->tail = nasm_malloc(sizeof(struct coff_Reloc));
517 sect->tail = &r->next;
518 r->next = NULL;
519
520 r->address = sect->len;
521 if (segment == NO_SEG) {
522 r->symbol = 0, r->symbase = ABS_SYMBOL;
523 } else {
524 int i;
525 r->symbase = REAL_SYMBOLS;
526 for (i = 0; i < coff_nsects; i++) {
527 if (segment == coff_sects[i]->index) {
528 r->symbol = i * 2;
529 r->symbase = SECT_SYMBOLS;
530 break;
531 }
532 }
533 if (r->symbase == REAL_SYMBOLS)
534 r->symbol = raa_read(bsym, segment);
535 }
536 r->type = type;
537
538 sect->nrelocs++;
539
540 /*
541 * Return the fixup for standard COFF common variables.
542 */
543 if (r->symbase == REAL_SYMBOLS && !(win32 | win64))
544 return raa_read(symval, segment);
545
546 return 0;
547}
548
549static void coff_out(int32_t segto, const void *data,
550 enum out_type type, uint64_t size,
551 int32_t segment, int32_t wrt)
552{
553 struct coff_Section *s;
554 uint8_t mydata[8], *p;
555 int i;
556
557 if (wrt != NO_SEG && !win64) {
558 wrt = NO_SEG; /* continue to do _something_ */
559 nasm_error(ERR_NONFATAL, "WRT not supported by COFF output formats");
560 }
561
562 /*
563 * handle absolute-assembly (structure definitions)
564 */
565 if (segto == NO_SEG) {
566 if (type != OUT_RESERVE)
567 nasm_error(ERR_NONFATAL, "attempt to assemble code in [ABSOLUTE]"
568 " space");
569 return;
570 }
571
572 s = NULL;
573 for (i = 0; i < coff_nsects; i++) {
574 if (segto == coff_sects[i]->index) {
575 s = coff_sects[i];
576 break;
577 }
578 }
579 if (!s) {
580 int tempint; /* ignored */
581 if (segto != coff_section_names(".text", 2, &tempint))
582 nasm_panic(0, "strange segment conditions in COFF driver");
583 else
584 s = coff_sects[coff_nsects - 1];
585 }
586
587 /* magically default to 'wrt ..imagebase' in .pdata and .xdata */
588 if (win64 && wrt == NO_SEG) {
589 if (!strcmp(s->name,".pdata") || !strcmp(s->name,".xdata"))
590 wrt = imagebase_sect;
591 }
592
593 if (!s->data && type != OUT_RESERVE) {
594 nasm_error(ERR_WARNING, "attempt to initialize memory in"
595 " BSS section `%s': ignored", s->name);
596 s->len += realsize(type, size);
597 return;
598 }
599
600 memset(mydata, 0, sizeof(mydata));
601
602 if (dfmt && dfmt->debug_output) {
603 struct coff_DebugInfo dinfo;
604 dinfo.segto = segto;
605 dinfo.seg = segment;
606 dinfo.section = s;
607
608 if (type == OUT_ADDRESS)
609 dinfo.size = abs((int)size);
610 else
611 dinfo.size = realsize(type, size);
612
613 dfmt->debug_output(type, &dinfo);
614 }
615
616 if (type == OUT_RESERVE) {
617 if (s->data) {
618 nasm_error(ERR_WARNING, "uninitialised space declared in"
619 " non-BSS section `%s': zeroing", s->name);
620 coff_sect_write(s, NULL, size);
621 } else
622 s->len += size;
623 } else if (type == OUT_RAWDATA) {
624 if (segment != NO_SEG)
625 nasm_panic(0, "OUT_RAWDATA with other than NO_SEG");
626 coff_sect_write(s, data, size);
627 } else if (type == OUT_ADDRESS) {
628 int asize = abs((int)size);
629 if (!win64) {
630 if (asize != 4 && (segment != NO_SEG || wrt != NO_SEG)) {
631 nasm_error(ERR_NONFATAL, "COFF format does not support non-32-bit"
632 " relocations");
633 } else {
634 int32_t fix = 0;
635 if (segment != NO_SEG || wrt != NO_SEG) {
636 if (wrt != NO_SEG) {
637 nasm_error(ERR_NONFATAL, "COFF format does not support"
638 " WRT types");
639 } else if (segment % 2) {
640 nasm_error(ERR_NONFATAL, "COFF format does not support"
641 " segment base references");
642 } else
643 fix = coff_add_reloc(s, segment, IMAGE_REL_I386_DIR32);
644 }
645 p = mydata;
646 WRITELONG(p, *(int64_t *)data + fix);
647 coff_sect_write(s, mydata, asize);
648 }
649 } else {
650 int32_t fix = 0;
651 p = mydata;
652 if (asize == 8) {
653 if (wrt == imagebase_sect) {
654 nasm_error(ERR_NONFATAL, "operand size mismatch: 'wrt "
655 WRT_IMAGEBASE "' is a 32-bit operand");
656 }
657 fix = coff_add_reloc(s, segment, IMAGE_REL_AMD64_ADDR64);
658 WRITEDLONG(p, *(int64_t *)data + fix);
659 coff_sect_write(s, mydata, asize);
660 } else {
661 fix = coff_add_reloc(s, segment,
662 wrt == imagebase_sect ? IMAGE_REL_AMD64_ADDR32NB:
663 IMAGE_REL_AMD64_ADDR32);
664 WRITELONG(p, *(int64_t *)data + fix);
665 coff_sect_write(s, mydata, asize);
666 }
667 }
668 } else if (type == OUT_REL2ADR) {
669 nasm_error(ERR_NONFATAL, "COFF format does not support 16-bit"
670 " relocations");
671 } else if (type == OUT_REL4ADR) {
672 if (segment == segto && !(win64)) /* Acceptable for RIP-relative */
673 nasm_panic(0, "intra-segment OUT_REL4ADR");
674 else if (segment == NO_SEG && win32)
675 nasm_error(ERR_NONFATAL, "Win32 COFF does not correctly support"
676 " relative references to absolute addresses");
677 else {
678 int32_t fix = 0;
679 if (segment != NO_SEG && segment % 2) {
680 nasm_error(ERR_NONFATAL, "COFF format does not support"
681 " segment base references");
682 } else
683 fix = coff_add_reloc(s, segment,
684 win64 ? IMAGE_REL_AMD64_REL32 : IMAGE_REL_I386_REL32);
685 p = mydata;
686 if (win32 | win64) {
687 WRITELONG(p, *(int64_t *)data + 4 - size + fix);
688 } else {
689 WRITELONG(p, *(int64_t *)data - (size + s->len) + fix);
690 }
691 coff_sect_write(s, mydata, 4L);
692 }
693
694 }
695}
696
697static void coff_sect_write(struct coff_Section *sect,
698 const uint8_t *data, uint32_t len)
699{
700 saa_wbytes(sect->data, data, len);
701 sect->len += len;
702}
703
704typedef struct tagString {
705 struct tagString *next;
706 int len;
707 char *String;
708} STRING;
709
710#define EXPORT_SECTION_NAME ".drectve"
711#define EXPORT_SECTION_FLAGS INFO_FLAGS
712/*
713 * #define EXPORT_SECTION_NAME ".text"
714 * #define EXPORT_SECTION_FLAGS TEXT_FLAGS
715 */
716
717static STRING *Exports = NULL;
718static struct coff_Section *directive_sec;
719static void AddExport(char *name)
720{
721 STRING *rvp = Exports, *newS;
722
723 newS = (STRING *) nasm_malloc(sizeof(STRING));
724 newS->len = strlen(name);
725 newS->next = NULL;
726 newS->String = (char *)nasm_malloc(newS->len + 1);
727 strcpy(newS->String, name);
728 if (rvp == NULL) {
729 int i;
730
731 for (i = 0; i < coff_nsects; i++) {
732 if (!strcmp(EXPORT_SECTION_NAME, coff_sects[i]->name))
733 break;
734 }
735
736 if (i == coff_nsects)
737 i = coff_make_section(EXPORT_SECTION_NAME, EXPORT_SECTION_FLAGS);
738
739 directive_sec = coff_sects[i];
740 Exports = newS;
741 } else {
742 while (rvp->next) {
743 if (!strcmp(rvp->String, name))
744 return;
745 rvp = rvp->next;
746 }
747 rvp->next = newS;
748 }
749}
750
751static void BuildExportTable(STRING **rvp)
752{
753 STRING *p, *t;
754
755 if (!rvp || !*rvp)
756 return;
757
758 list_for_each_safe(p, t, *rvp) {
759 coff_sect_write(directive_sec, (uint8_t *)"-export:", 8);
760 coff_sect_write(directive_sec, (uint8_t *)p->String, p->len);
761 coff_sect_write(directive_sec, (uint8_t *)" ", 1);
762 nasm_free(p->String);
763 nasm_free(p);
764 }
765
766 *rvp = NULL;
767}
768
769static enum directive_result
770coff_directives(enum directive directive, char *value, int pass)
771{
772 switch (directive) {
773 case D_EXPORT:
774 {
775 char *q, *name;
776
777 if (pass == 2)
778 return DIRR_OK; /* ignore in pass two */
779 name = q = value;
780 while (*q && !nasm_isspace(*q))
781 q++;
782 if (nasm_isspace(*q)) {
783 *q++ = '\0';
784 while (*q && nasm_isspace(*q))
785 q++;
786 }
787
788 if (!*name) {
789 nasm_error(ERR_NONFATAL, "`export' directive requires export name");
790 return DIRR_ERROR;
791 }
792 if (*q) {
793 nasm_error(ERR_NONFATAL, "unrecognized export qualifier `%s'", q);
794 return DIRR_ERROR;
795 }
796 AddExport(name);
797 return DIRR_OK;
798 }
799 case D_SAFESEH:
800 {
801 static int sxseg=-1;
802 int i;
803
804 if (!win32) /* Only applicable for -f win32 */
805 return 0;
806
807 if (sxseg == -1) {
808 for (i = 0; i < coff_nsects; i++)
809 if (!strcmp(".sxdata",coff_sects[i]->name))
810 break;
811 if (i == coff_nsects)
812 sxseg = coff_make_section(".sxdata", IMAGE_SCN_LNK_INFO);
813 else
814 sxseg = i;
815 }
816 /*
817 * pass0 == 2 is the only time when the full set of symbols are
818 * guaranteed to be present; it is the final output pass.
819 */
820 if (pass0 == 2) {
821 uint32_t n;
822 saa_rewind(coff_syms);
823 for (n = 0; n < coff_nsyms; n++) {
824 struct coff_Symbol *sym = saa_rstruct(coff_syms);
825 bool equals;
826
827 /*
828 * sym->strpos is biased by 4, because symbol
829 * table is prefixed with table length
830 */
831 if (sym->strpos >=4) {
832 char *name = nasm_malloc(sym->namlen+1);
833 saa_fread(coff_strs, sym->strpos-4, name, sym->namlen);
834 name[sym->namlen] = '\0';
835 equals = !strcmp(value,name);
836 nasm_free(name);
837 } else {
838 equals = !strcmp(value,sym->name);
839 }
840
841 if (equals) {
842 /*
843 * this value arithmetics effectively reflects
844 * initsym in coff_write(): 2 for file, 1 for
845 * .absolute and two per each section
846 */
847 unsigned char value[4],*p=value;
848 WRITELONG(p,n + 2 + 1 + coff_nsects*2);
849 coff_sect_write(coff_sects[sxseg],value,4);
850 sym->type = 0x20;
851 break;
852 }
853 }
854 if (n == coff_nsyms) {
855 nasm_error(ERR_NONFATAL,
856 "`safeseh' directive requires valid symbol");
857 return DIRR_ERROR;
858 }
859 }
860 return DIRR_OK;
861 }
862 default:
863 return DIRR_UNKNOWN;
864 }
865}
866
867/* handle relocations storm, valid for win32/64 only */
868static inline void coff_adjust_relocs(struct coff_Section *s)
869{
870 if (s->nrelocs < IMAGE_SCN_MAX_RELOC)
871 return;
872#ifdef OF_COFF
873 else
874 {
875 if (ofmt == &of_coff)
876 nasm_fatal(0,
877 "Too many relocations (%d) for section `%s'",
878 s->nrelocs, s->name);
879 }
880#endif
881
882 s->flags |= IMAGE_SCN_LNK_NRELOC_OVFL;
883 s->nrelocs++;
884}
885
886static void coff_write(void)
887{
888 int32_t pos, sympos, vsize;
889 int i;
890
891 /* fill in the .drectve section with -export's */
892 BuildExportTable(&Exports);
893
894 if (win32) {
895 /* add default value for @feat.00, this allows to 'link /safeseh' */
896 uint32_t n;
897
898 saa_rewind(coff_syms);
899 for (n = 0; n < coff_nsyms; n++) {
900 struct coff_Symbol *sym = saa_rstruct(coff_syms);
901 if (sym->strpos == -1 && !strcmp("@feat.00",sym->name))
902 break;
903 }
904 if (n == coff_nsyms)
905 coff_deflabel("@feat.00", NO_SEG, 1, 0, NULL);
906 }
907
908 /*
909 * Work out how big the file will get.
910 * Calculate the start of the `real' symbols at the same time.
911 * Check for massive relocations.
912 */
913 pos = 0x14 + 0x28 * coff_nsects;
914 initsym = 3; /* two for the file, one absolute */
915 for (i = 0; i < coff_nsects; i++) {
916 if (coff_sects[i]->data) {
917 coff_adjust_relocs(coff_sects[i]);
918 coff_sects[i]->pos = pos;
919 pos += coff_sects[i]->len;
920 coff_sects[i]->relpos = pos;
921 pos += 10 * coff_sects[i]->nrelocs;
922 } else
923 coff_sects[i]->pos = coff_sects[i]->relpos = 0L;
924 initsym += 2; /* two for each section */
925 }
926 sympos = pos;
927
928 /*
929 * Output the COFF header.
930 */
931 if (win64)
932 i = IMAGE_FILE_MACHINE_AMD64;
933 else
934 i = IMAGE_FILE_MACHINE_I386;
935 fwriteint16_t(i, ofile); /* machine type */
936 fwriteint16_t(coff_nsects, ofile); /* number of sections */
937 fwriteint32_t(time(NULL), ofile); /* time stamp */
938 fwriteint32_t(sympos, ofile);
939 fwriteint32_t(coff_nsyms + initsym, ofile);
940 fwriteint16_t(0, ofile); /* no optional header */
941 /* Flags: 32-bit, no line numbers. Win32 doesn't even bother with them. */
942 fwriteint16_t((win32 | win64) ? 0 : 0x104, ofile);
943
944 /*
945 * Output the section headers.
946 */
947 vsize = 0L;
948 for (i = 0; i < coff_nsects; i++) {
949 coff_section_header(coff_sects[i]->name, coff_sects[i]->namepos, vsize, coff_sects[i]->len,
950 coff_sects[i]->pos, coff_sects[i]->relpos,
951 coff_sects[i]->nrelocs, coff_sects[i]->flags);
952 vsize += coff_sects[i]->len;
953 }
954
955 /*
956 * Output the sections and their relocations.
957 */
958 for (i = 0; i < coff_nsects; i++)
959 if (coff_sects[i]->data) {
960 saa_fpwrite(coff_sects[i]->data, ofile);
961 coff_write_relocs(coff_sects[i]);
962 }
963
964 /*
965 * Output the symbol and string tables.
966 */
967 coff_write_symbols();
968 fwriteint32_t(strslen + 4, ofile); /* length includes length count */
969 saa_fpwrite(coff_strs, ofile);
970}
971
972static void coff_section_header(char *name, int32_t namepos, int32_t vsize,
973 int32_t datalen, int32_t datapos,
974 int32_t relpos, int nrelocs, int32_t flags)
975{
976 char padname[8];
977
978 (void)vsize;
979
980 if (namepos == -1) {
981 strncpy(padname, name, 8);
982 nasm_write(padname, 8, ofile);
983 } else {
984 /*
985 * If name is longer than 8 bytes, write '/' followed
986 * by offset into the strings table represented as
987 * decimal number.
988 */
989 namepos = namepos % 100000000;
990 padname[0] = '/';
991 padname[1] = '0' + (namepos / 1000000);
992 namepos = namepos % 1000000;
993 padname[2] = '0' + (namepos / 100000);
994 namepos = namepos % 100000;
995 padname[3] = '0' + (namepos / 10000);
996 namepos = namepos % 10000;
997 padname[4] = '0' + (namepos / 1000);
998 namepos = namepos % 1000;
999 padname[5] = '0' + (namepos / 100);
1000 namepos = namepos % 100;
1001 padname[6] = '0' + (namepos / 10);
1002 namepos = namepos % 10;
1003 padname[7] = '0' + (namepos);
1004 nasm_write(padname, 8, ofile);
1005 }
1006
1007 fwriteint32_t(0, ofile); /* Virtual size field - set to 0 or vsize */
1008 fwriteint32_t(0L, ofile); /* RVA/offset - we ignore */
1009 fwriteint32_t(datalen, ofile);
1010 fwriteint32_t(datapos, ofile);
1011 fwriteint32_t(relpos, ofile);
1012 fwriteint32_t(0L, ofile); /* no line numbers - we don't do 'em */
1013
1014 /*
1015 * a special case -- if there are too many relocs
1016 * we have to put IMAGE_SCN_MAX_RELOC here and write
1017 * the real relocs number into VirtualAddress of first
1018 * relocation
1019 */
1020 if (flags & IMAGE_SCN_LNK_NRELOC_OVFL)
1021 fwriteint16_t(IMAGE_SCN_MAX_RELOC, ofile);
1022 else
1023 fwriteint16_t(nrelocs, ofile);
1024
1025 fwriteint16_t(0, ofile); /* again, no line numbers */
1026 fwriteint32_t(flags, ofile);
1027}
1028
1029static void coff_write_relocs(struct coff_Section *s)
1030{
1031 struct coff_Reloc *r;
1032
1033 /* a real number of relocations if needed */
1034 if (s->flags & IMAGE_SCN_LNK_NRELOC_OVFL) {
1035 fwriteint32_t(s->nrelocs, ofile);
1036 fwriteint32_t(0, ofile);
1037 fwriteint16_t(0, ofile);
1038 }
1039
1040 for (r = s->head; r; r = r->next) {
1041 fwriteint32_t(r->address, ofile);
1042 fwriteint32_t(r->symbol + (r->symbase == REAL_SYMBOLS ? initsym :
1043 r->symbase == ABS_SYMBOL ? initsym - 1 :
1044 r->symbase == SECT_SYMBOLS ? 2 : 0),
1045 ofile);
1046 fwriteint16_t(r->type, ofile);
1047 }
1048}
1049
1050static void coff_symbol(char *name, int32_t strpos, int32_t value,
1051 int section, int type, int storageclass, int aux)
1052{
1053 char padname[8];
1054
1055 if (name) {
1056 strncpy(padname, name, 8);
1057 nasm_write(padname, 8, ofile);
1058 } else {
1059 fwriteint32_t(0, ofile);
1060 fwriteint32_t(strpos, ofile);
1061 }
1062
1063 fwriteint32_t(value, ofile);
1064 fwriteint16_t(section, ofile);
1065 fwriteint16_t(type, ofile);
1066
1067 fputc(storageclass, ofile);
1068 fputc(aux, ofile);
1069}
1070
1071static void coff_write_symbols(void)
1072{
1073 char filename[18];
1074 uint32_t i;
1075
1076 /*
1077 * The `.file' record, and the file name auxiliary record.
1078 */
1079 coff_symbol(".file", 0L, 0L, -2, 0, 0x67, 1);
1080 strncpy(filename, inname, 18);
1081 nasm_write(filename, 18, ofile);
1082
1083 /*
1084 * The section records, with their auxiliaries.
1085 */
1086 memset(filename, 0, 18); /* useful zeroed buffer */
1087
1088 for (i = 0; i < (uint32_t) coff_nsects; i++) {
1089 coff_symbol(coff_sects[i]->name, 0L, 0L, i + 1, 0, 3, 1);
1090 fwriteint32_t(coff_sects[i]->len, ofile);
1091 fwriteint16_t(coff_sects[i]->nrelocs,ofile);
1092 nasm_write(filename, 12, ofile);
1093 }
1094
1095 /*
1096 * The absolute symbol, for relative-to-absolute relocations.
1097 */
1098 coff_symbol(".absolut", 0L, 0L, -1, 0, 3, 0);
1099
1100 /*
1101 * The real symbols.
1102 */
1103 saa_rewind(coff_syms);
1104 for (i = 0; i < coff_nsyms; i++) {
1105 struct coff_Symbol *sym = saa_rstruct(coff_syms);
1106 coff_symbol(sym->strpos == -1 ? sym->name : NULL,
1107 sym->strpos, sym->value, sym->section,
1108 sym->type, sym->is_global ? 2 : 3, 0);
1109 }
1110}
1111
1112static void coff_sectalign(int32_t seg, unsigned int value)
1113{
1114 struct coff_Section *s = NULL;
1115 uint32_t align;
1116 int i;
1117
1118 for (i = 0; i < coff_nsects; i++) {
1119 if (coff_sects[i]->index == seg) {
1120 s = coff_sects[i];
1121 break;
1122 }
1123 }
1124
1125 if (!s || !is_power2(value))
1126 return;
1127
1128 /* DOS has limitation on 64 bytes */
1129 if (!(win32 | win64) && value > 64)
1130 return;
1131
1132 align = (s->flags & IMAGE_SCN_ALIGN_MASK);
1133 value = coff_sectalign_flags(value);
1134 if (value > align)
1135 s->flags = (s->flags & ~IMAGE_SCN_ALIGN_MASK) | value;
1136}
1137
1138static int32_t coff_segbase(int32_t segment)
1139{
1140 return segment;
1141}
1142
1143extern macros_t coff_stdmac[];
1144
1145#endif /* defined(OF_COFF) || defined(OF_WIN32) */
1146
1147#ifdef OF_COFF
1148
1149const struct ofmt of_coff = {
1150 "COFF (i386) object files (e.g. DJGPP for DOS)",
1151 "coff",
1152 ".o",
1153 0,
1154 32,
1155 null_debug_arr,
1156 &null_debug_form,
1157 coff_stdmac,
1158 coff_std_init,
1159 null_reset,
1160 nasm_do_legacy_output,
1161 coff_out,
1162 coff_deflabel,
1163 coff_section_names,
1164 NULL,
1165 coff_sectalign,
1166 coff_segbase,
1167 coff_directives,
1168 coff_cleanup,
1169 NULL /* pragma list */
1170};
1171
1172#endif
1173
1174extern const struct dfmt df_cv8;
1175
1176#ifdef OF_WIN32
1177
1178static const struct dfmt * const win32_debug_arr[2] = { &df_cv8, NULL };
1179
1180const struct ofmt of_win32 = {
1181 "Microsoft Win32 (i386) object files",
1182 "win32",
1183 ".obj",
1184 0,
1185 32,
1186 win32_debug_arr,
1187 &df_cv8,
1188 coff_stdmac,
1189 coff_win32_init,
1190 null_reset,
1191 nasm_do_legacy_output,
1192 coff_out,
1193 coff_deflabel,
1194 coff_section_names,
1195 NULL,
1196 coff_sectalign,
1197 coff_segbase,
1198 coff_directives,
1199 coff_cleanup,
1200 NULL /* pragma list */
1201};
1202
1203#endif
1204
1205#ifdef OF_WIN64
1206
1207static const struct dfmt * const win64_debug_arr[2] = { &df_cv8, NULL };
1208
1209const struct ofmt of_win64 = {
1210 "Microsoft Win64 (x86-64) object files",
1211 "win64",
1212 ".obj",
1213 0,
1214 64,
1215 win64_debug_arr,
1216 &df_cv8,
1217 coff_stdmac,
1218 coff_win64_init,
1219 null_reset,
1220 nasm_do_legacy_output,
1221 coff_out,
1222 coff_deflabel,
1223 coff_section_names,
1224 NULL,
1225 coff_sectalign,
1226 coff_segbase,
1227 coff_directives,
1228 coff_cleanup,
1229 NULL /* pragma list */
1230};
1231
1232#endif
1233