Debian Codegraph @

output/outcoff.c

raw
1 /* SPDX-License-Identifier: BSD-2-Clause */
2 /* Copyright 1996-2020 The NASM Authors - All Rights Reserved */
3
4 /*
5 * outcoff.c output routines for the Netwide Assembler to produce
6 * COFF object files (for DJGPP and Win32)
7 */
8
9 #include "compiler.h"
10
11 #include "nctype.h"
12 #include <time.h>
13 #include "ver.h"
14
15 #include "nasm.h"
16 #include "nasmlib.h"
17 #include "ilog2.h"
18 #include "error.h"
19 #include "saa.h"
20 #include "raa.h"
21 #include "eval.h"
22 #include "outform.h"
23 #include "outlib.h"
24 #include "pecoff.h"
25
26 #if defined(OF_COFF) || defined(OF_WIN32) || defined(OF_WIN64)
27
28 /*
29 * Notes on COFF:
30 *
31 * (0) When I say `standard COFF' below, I mean `COFF as output and
32 * used by DJGPP'. I assume DJGPP gets it right.
33 *
34 * (1) Win32 appears to interpret the term `relative relocation'
35 * differently from standard COFF. Standard COFF understands a
36 * relative relocation to mean that during relocation you add the
37 * address of the symbol you're referencing, and subtract the base
38 * address of the section you're in. Win32 COFF, by contrast, seems
39 * to add the address of the symbol and then subtract the address
40 * of THE BYTE AFTER THE RELOCATED DWORD. Hence the two formats are
41 * subtly incompatible.
42 *
43 * (2) Win32 doesn't bother putting any flags in the header flags
44 * field (at offset 0x12 into the file).
45 *
46 * (3) Win32/64 uses some extra flags into the section header table:
47 * it defines flags 0x80000000 (writable), 0x40000000 (readable)
48 * and 0x20000000 (executable), and uses them in the expected
49 * combinations. It also defines 0x00100000 through 0x00f00000 for
50 * section alignments of 1 through 8192 bytes.
51 *
52 * (4) Both standard COFF and Win32 COFF seem to use the DWORD
53 * field directly after the section name in the section header
54 * table for something strange: they store what the address of the
55 * section start point _would_ be, if you laid all the sections end
56 * to end starting at zero. Dunno why. Microsoft's documentation
57 * lists this field as "Virtual Size of Section", which doesn't
58 * seem to fit at all. In fact, Win32 even includes non-linked
59 * sections such as .drectve in this calculation.
60 *
61 * Newer versions of MASM seem to have changed this to be zero, and
62 * that apparently matches the COFF spec, so go with that.
63 *
64 * (5) Standard COFF does something very strange to common
65 * variables: the relocation point for a common variable is as far
66 * _before_ the variable as its size stretches out _after_ it. So
67 * we must fix up common variable references. Win32 seems to be
68 * sensible on this one.
69 */
70
71 /* Flag which version of COFF we are currently outputting. */
72 bool win32, win64;
73
74 static int32_t imagebase_sect;
75 #define WRT_IMAGEBASE "..imagebase"
76
77 /*
78 * Some common section flags by default
79 */
80 #define TEXT_FLAGS_WIN \
81 (IMAGE_SCN_CNT_CODE | \
82 IMAGE_SCN_ALIGN_16BYTES | \
83 IMAGE_SCN_MEM_EXECUTE | \
84 IMAGE_SCN_MEM_READ)
85 #define TEXT_FLAGS_DOS \
86 (IMAGE_SCN_CNT_CODE)
87
88 #define DATA_FLAGS_WIN \
89 (IMAGE_SCN_CNT_INITIALIZED_DATA | \
90 IMAGE_SCN_ALIGN_4BYTES | \
91 IMAGE_SCN_MEM_READ | \
92 IMAGE_SCN_MEM_WRITE)
93 #define DATA_FLAGS_DOS \
94 (IMAGE_SCN_CNT_INITIALIZED_DATA)
95
96 #define BSS_FLAGS_WIN \
97 (IMAGE_SCN_CNT_UNINITIALIZED_DATA | \
98 IMAGE_SCN_ALIGN_4BYTES | \
99 IMAGE_SCN_MEM_READ | \
100 IMAGE_SCN_MEM_WRITE)
101 #define BSS_FLAGS_DOS \
102 (IMAGE_SCN_CNT_UNINITIALIZED_DATA)
103
104 #define RDATA_FLAGS_WIN \
105 (IMAGE_SCN_CNT_INITIALIZED_DATA | \
106 IMAGE_SCN_ALIGN_8BYTES | \
107 IMAGE_SCN_MEM_READ)
108
109 #define RDATA_FLAGS_DOS \
110 (IMAGE_SCN_CNT_INITIALIZED_DATA)
111
112 #define PDATA_FLAGS \
113 (IMAGE_SCN_CNT_INITIALIZED_DATA | \
114 IMAGE_SCN_ALIGN_4BYTES | \
115 IMAGE_SCN_MEM_READ)
116
117 #define XDATA_FLAGS \
118 (IMAGE_SCN_CNT_INITIALIZED_DATA | \
119 IMAGE_SCN_ALIGN_8BYTES | \
120 IMAGE_SCN_MEM_READ)
121
122 #define INFO_FLAGS \
123 (IMAGE_SCN_ALIGN_1BYTES | \
124 IMAGE_SCN_LNK_INFO | \
125 IMAGE_SCN_LNK_REMOVE)
126
127 #define TEXT_FLAGS ((win32 | win64) ? TEXT_FLAGS_WIN : TEXT_FLAGS_DOS)
128 #define DATA_FLAGS ((win32 | win64) ? DATA_FLAGS_WIN : DATA_FLAGS_DOS)
129 #define BSS_FLAGS ((win32 | win64) ? BSS_FLAGS_WIN : BSS_FLAGS_DOS)
130 #define RDATA_FLAGS ((win32 | win64) ? RDATA_FLAGS_WIN : RDATA_FLAGS_DOS)
131
132 #define COFF_MAX_ALIGNMENT 8192
133
134 #define SECT_DELTA 32
135 struct coff_Section **coff_sects;
136 static int sectlen;
137 int coff_nsects;
138
139 struct SAA *coff_syms;
140 uint32_t coff_nsyms;
141
142 static int32_t def_seg;
143
144 static int initsym;
145
146 static struct RAA *bsym, *symval;
147
148 struct SAA *coff_strs;
149 static uint32_t strslen;
150
151 static void coff_gen_init(void);
152 static void coff_sect_write(struct coff_Section *, const uint8_t *, uint32_t);
153 static void coff_write(void);
154 static void coff_section_header(char *, int32_t, int32_t, int32_t, int32_t, int32_t, int, int32_t);
155 static void coff_write_relocs(struct coff_Section *);
156 static void coff_write_symbols(void);
157 static void coff_defcomdatname(char *name, int32_t segment);
158
159 #define COMDAT_PLACEHOLDER_NAME ".tmpcmdt"
160
161 static void coff_win32_init(void)
162 {
163 win32 = true;
164 win64 = false;
165 coff_gen_init();
166 }
167
168 static void coff_win64_init(void)
169 {
170 win32 = false;
171 win64 = true;
172 coff_gen_init();
173 imagebase_sect = seg_alloc()+1;
174 backend_label(WRT_IMAGEBASE, imagebase_sect, 0);
175 }
176
177 static void coff_std_init(void)
178 {
179 win32 = win64 = false;
180 coff_gen_init();
181 }
182
183 static void coff_gen_init(void)
184 {
185
186 coff_sects = NULL;
187 coff_nsects = sectlen = 0;
188 coff_syms = saa_init(sizeof(struct coff_Symbol));
189 coff_nsyms = 0;
190 bsym = raa_init();
191 symval = raa_init();
192 coff_strs = saa_init(1);
193 strslen = 0;
194 def_seg = seg_alloc();
195 }
196
197 static void coff_cleanup(void)
198 {
199 struct coff_Reloc *r;
200 int i;
201
202 dfmt->cleanup();
203
204 coff_write();
205 for (i = 0; i < coff_nsects; i++) {
206 if (coff_sects[i]->data)
207 saa_free(coff_sects[i]->data);
208 while (coff_sects[i]->head) {
209 r = coff_sects[i]->head;
210 coff_sects[i]->head = coff_sects[i]->head->next;
211 nasm_free(r);
212 }
213 nasm_free(coff_sects[i]->name);
214 nasm_free(coff_sects[i]->comdat_name);
215 nasm_free(coff_sects[i]);
216 }
217 nasm_free(coff_sects);
218 saa_free(coff_syms);
219 raa_free(bsym);
220 raa_free(symval);
221 saa_free(coff_strs);
222 }
223
224 int coff_make_section(char *name, uint32_t flags)
225 {
226 struct coff_Section *s;
227 size_t namelen;
228
229 s = nasm_zalloc(sizeof(*s));
230
231 if (flags != BSS_FLAGS)
232 s->data = saa_init(1);
233 s->tail = &s->head;
234 if (!strcmp(name, ".text"))
235 s->index = def_seg;
236 else
237 s->index = seg_alloc();
238 s->namepos = -1;
239 namelen = strlen(name);
240 if (namelen > 8) {
241 if (win32 || win64) {
242 s->namepos = strslen + 4;
243 saa_wbytes(coff_strs, name, namelen + 1);
244 strslen += namelen + 1;
245 } else {
246 namelen = 8;
247 }
248 }
249 s->name = nasm_malloc(namelen + 1);
250 strncpy(s->name, name, namelen);
251 s->name[namelen] = '\0';
252 s->flags = flags;
253
254 if (coff_nsects >= sectlen) {
255 sectlen += SECT_DELTA;
256 coff_sects = nasm_realloc(coff_sects, sectlen * sizeof(*coff_sects));
257 }
258 coff_sects[coff_nsects++] = s;
259
260 return coff_nsects - 1;
261 }
262
263 /*
264 * Update the name and flags of an existing section
265 */
266 static void coff_update_section(int section, char *name, uint32_t flags)
267 {
268 struct coff_Section *s = coff_sects[section];
269 size_t namelen = strlen(name);
270
271 if (namelen > 8) {
272 if (win32 || win64) {
273 s->namepos = strslen + 4;
274 saa_wbytes(coff_strs, name, namelen + 1);
275 strslen += namelen + 1;
276 } else {
277 namelen = 8;
278 }
279 }
280
281 nasm_free(s->name);
282 s->name = nasm_malloc(namelen + 1);
283 strncpy(s->name, name, namelen);
284 s->name[namelen] = '\0';
285 s->flags = flags;
286 }
287
288 /*
289 * Convert an alignment value to the corresponding flags.
290 * An alignment value of 0 means no flags should be set.
291 */
292 static inline uint32_t coff_sectalign_flags(unsigned int align)
293 {
294 return (alignlog2_32(align) + 1) << 20;
295 }
296
297 /*
298 * Get the default section flags (based on section name)
299 */
300 static uint32_t coff_section_flags(char *name, uint32_t flags)
301 {
302 if (!flags) {
303 flags = TEXT_FLAGS;
304
305 if (!strcmp(name, ".data")) {
306 flags = DATA_FLAGS;
307 } else if (!strcmp(name, ".rdata")) {
308 flags = RDATA_FLAGS;
309 } else if (!strcmp(name, ".bss")) {
310 flags = BSS_FLAGS;
311 } else if (win64) {
312 if (!strcmp(name, ".pdata"))
313 flags = PDATA_FLAGS;
314 else if (!strcmp(name, ".xdata"))
315 flags = XDATA_FLAGS;
316 }
317 }
318
319 return flags;
320 }
321
322 static int32_t coff_section_names(char *name, int *bits)
323 {
324 char *p, *comdat_name;
325 uint32_t flags, align_flags;
326 int i, j;
327 int8_t comdat_selection;
328 int32_t comdat_associated;
329
330 /*
331 * Set default bits.
332 */
333 if (!name) {
334 if(win64)
335 *bits = 64;
336 else
337 *bits = 32;
338
339 return def_seg;
340 }
341
342 p = name;
343 while (*p && !nasm_isspace(*p))
344 p++;
345 if (*p)
346 *p++ = '\0';
347 if (strlen(name) > 8) {
348 if (!win32 && !win64) {
349 nasm_warn(WARN_OTHER, "COFF section names limited to 8 characters: truncating");
350 name[8] = '\0';
351 }
352 }
353 flags = align_flags = comdat_selection = comdat_associated = 0;
354 comdat_name = NULL;
355
356 while (*p && nasm_isspace(*p))
357 p++;
358 while (*p) {
359 char *q = p;
360 while (*p && !nasm_isspace(*p))
361 p++;
362 if (*p)
363 *p++ = '\0';
364 while (*p && nasm_isspace(*p))
365 p++;
366
367 if (!nasm_stricmp(q, "code") || !nasm_stricmp(q, "text")) {
368 flags = TEXT_FLAGS;
369 } else if (!nasm_stricmp(q, "data")) {
370 flags = DATA_FLAGS;
371 } else if (!nasm_stricmp(q, "rdata")) {
372 if (win32 | win64)
373 flags = RDATA_FLAGS;
374 else {
375 flags = DATA_FLAGS; /* gotta do something */
376 nasm_nonfatal("standard COFF does not support"
377 " read-only data sections");
378 }
379 } else if (!nasm_stricmp(q, "bss")) {
380 flags = BSS_FLAGS;
381 } else if (!nasm_stricmp(q, "info")) {
382 if (win32 | win64)
383 flags = INFO_FLAGS;
384 else {
385 flags = DATA_FLAGS; /* gotta do something */
386 nasm_nonfatal("standard COFF does not support"
387 " informational sections");
388 }
389 } else if (!nasm_strnicmp(q, "align=", 6)) {
390 if (q[6 + strspn(q + 6, "0123456789")])
391 nasm_nonfatal("argument to `align' is not numeric");
392 else {
393 unsigned int align = atoi(q + 6);
394 /* Allow align=0 meaning use default */
395 if (!align) {
396 align_flags = 0;
397 } else if (!is_power2(align)) {
398 nasm_nonfatal("argument to `align' is not a"
399 " power of two");
400 } else if (align > COFF_MAX_ALIGNMENT) {
401 nasm_nonfatal("maximum alignment in COFF is %d bytes",
402 COFF_MAX_ALIGNMENT);
403 } else {
404 align_flags = coff_sectalign_flags(align);
405 }
406 }
407 } else if (!nasm_strnicmp(q, "comdat=", 7)) {
408 /*
409 * Expected format: comdat=num:name]
410 * where
411 * num is a number: one of the IMAGE_COMDAT_SELECT_* constants
412 * name is a string: the "COMDAT name"
413 */
414 comdat_selection = strtoul(q + 7, &q, 10);
415 if (!comdat_selection)
416 nasm_nonfatal("invalid argument to `comdat'");
417 else if (*q != ':' || q[1] == '\0')
418 nasm_nonfatal("missing name in `comdat'");
419 else {
420 comdat_name = q + 1;
421 }
422 }
423 }
424
425 for (i = 0; i < coff_nsects; i++)
426 if (!strcmp(name, coff_sects[i]->name)) {
427 if (!comdat_name && !coff_sects[i]->comdat_name)
428 break;
429 else if (comdat_name && coff_sects[i]->comdat_name &&
430 !strcmp(comdat_name, coff_sects[i]->comdat_name)) {
431 /*
432 * For COMDAT, it makes sense to have multiple sections with
433 * the same name (different comdat name though)
434 */
435 if ((coff_sects[i]->comdat_selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE &&
436 comdat_selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE) ||
437 (coff_sects[i]->comdat_selection != IMAGE_COMDAT_SELECT_ASSOCIATIVE &&
438 comdat_selection != IMAGE_COMDAT_SELECT_ASSOCIATIVE)) {
439 /*
440 * Let's also allow an associative/other pair with the same name
441 */
442 break;
443 }
444 }
445 }
446 else if (comdat_name && coff_sects[i]->comdat_name &&
447 !coff_sects[i]->comdat_selection &&
448 !strcmp(comdat_name, coff_sects[i]->comdat_name) &&
449 comdat_selection != IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
450 /*
451 * This seems to be a "placeholder section" we've created before
452 * to be the associate of a previous comdat section.
453 * We'll just update the name and flags with the real ones now.
454 */
455 flags = coff_section_flags(name, flags);
456 coff_update_section(i, name, flags | IMAGE_SCN_LNK_COMDAT);
457 coff_sects[i]->comdat_selection = comdat_selection;
458 break;
459 }
460
461 if (i == coff_nsects) {
462 flags = coff_section_flags(name, flags);
463
464 if (comdat_name) {
465 flags |= IMAGE_SCN_LNK_COMDAT;
466
467 if (comdat_selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
468 /*
469 * Find an existing section with given comdat name
470 */
471 for (j = 0; j < coff_nsects; j++)
472 if (coff_sects[j]->comdat_name &&
473 !strcmp(coff_sects[j]->comdat_name, comdat_name))
474 break;
475
476 if (j == coff_nsects) {
477 /*
478 * The associated section doesn't exist (yet)
479 * Even though the specs don't enforce a particular order,
480 * VS (2019) linker doesn't accept .obj files where the
481 * target section is a later one (than the one with sel==5)
482 *
483 * So let's insert another section now (a placeholder),
484 * hoping it will be turned into the target section later.
485 */
486 j = coff_make_section(COMDAT_PLACEHOLDER_NAME, TEXT_FLAGS);
487 coff_sects[j]->comdat_name = nasm_strdup(comdat_name);
488 }
489
490 comdat_associated = j + 1;
491 }
492 }
493
494 i = coff_make_section(name, flags);
495 coff_sects[i]->align_flags = align_flags;
496
497 if (comdat_name) {
498 coff_sects[i]->comdat_selection = comdat_selection;
499 coff_sects[i]->comdat_associated = comdat_associated;
500 coff_sects[i]->comdat_name = nasm_strdup(comdat_name);
501 }
502 } else {
503 if (flags) {
504 if (comdat_name)
505 flags |= IMAGE_SCN_LNK_COMDAT;
506
507 /* Warn if non-alignment flags differ */
508 if (((flags ^ coff_sects[i]->flags) & ~IMAGE_SCN_ALIGN_MASK) &&
509 coff_sects[i]->pass_last_seen == pass_count()) {
510 nasm_warn(WARN_OTHER, "section attributes changed on"
511 " redeclaration of section `%s'", name);
512 }
513 }
514
515 /*
516 * Alignment can be increased, but never decreased. However,
517 * specifying a narrower alignment is permitted and ignored.
518 */
519 if (align_flags > coff_sects[i]->align_flags) {
520 coff_sects[i]->align_flags = align_flags;
521 }
522
523 if (comdat_name) {
524 if ((coff_sects[i]->comdat_selection != comdat_selection) &&
525 coff_sects[i]->pass_last_seen == pass_count()) {
526 nasm_warn(WARN_OTHER, "comdat selection changed on"
527 " redeclaration of name `%s'", comdat_name);
528 }
529 }
530 }
531
532 coff_sects[i]->pass_last_seen = pass_count();
533 return coff_sects[i]->index;
534 }
535
536 static void coff_deflabel(char *name, int32_t segment, int64_t offset,
537 int is_global, char *special)
538 {
539 int pos, section;
540 struct coff_Symbol *sym;
541
542 if (special)
543 nasm_nonfatal("COFF format does not support any"
544 " special symbol types");
545
546 if (name[0] == '.' && name[1] == '.' && name[2] != '@') {
547 if (strcmp(name,WRT_IMAGEBASE))
548 nasm_nonfatal("unrecognized special symbol `%s'", name);
549 return;
550 }
551
552 if (segment == NO_SEG)
553 section = -1; /* absolute symbol */
554 else {
555 int i;
556 section = 0;
557 for (i = 0; i < coff_nsects; i++)
558 if (segment == coff_sects[i]->index) {
559 section = i + 1;
560
561 if (coff_sects[i]->comdat_name && !coff_sects[i]->comdat_symbol) {
562 /*
563 * The "comdat symbol" must be the first one in symbol table
564 * So we'll insert/define it - before defining the other one
565 */
566 coff_sects[i]->comdat_symbol = 1;
567
568 if (coff_sects[i]->comdat_selection != IMAGE_COMDAT_SELECT_ASSOCIATIVE &&
569 0 != strcmp(coff_sects[i]->comdat_name, name)) {
570 coff_defcomdatname(coff_sects[i]->comdat_name, segment);
571 }
572 }
573 break;
574 }
575 }
576
577 pos = strslen + 4;
578 if (strlen(name) > 8) {
579 size_t nlen = strlen(name)+1;
580 saa_wbytes(coff_strs, name, nlen);
581 strslen += nlen;
582 } else
583 pos = -1;
584
585 sym = saa_wstruct(coff_syms);
586
587 sym->strpos = pos;
588 sym->namlen = strlen(name);
589 if (pos == -1)
590 strcpy(sym->name, name);
591 sym->is_global = !!is_global;
592 sym->type = 0; /* Default to T_NULL (no type) */
593 sym->section = section;
594 if (!sym->section)
595 sym->is_global = true;
596 if (is_global == 2)
597 sym->value = offset;
598 else
599 sym->value = (sym->section == 0 ? 0 : offset);
600
601 /*
602 * define the references from external-symbol segment numbers
603 * to these symbol records.
604 */
605 if (sym->section == 0)
606 bsym = raa_write(bsym, segment, coff_nsyms);
607
608 if (segment != NO_SEG)
609 symval = raa_write(symval, segment, sym->section ? 0 : sym->value);
610
611 coff_nsyms++;
612 }
613
614 static int32_t coff_add_reloc(struct coff_Section *sect, int32_t segment,
615 int16_t type)
616 {
617 struct coff_Reloc *r;
618
619 r = *sect->tail = nasm_malloc(sizeof(struct coff_Reloc));
620 sect->tail = &r->next;
621 r->next = NULL;
622
623 r->address = sect->len;
624 if (segment == NO_SEG) {
625 r->symbol = 0, r->symbase = ABS_SYMBOL;
626 } else {
627 int i;
628 r->symbase = REAL_SYMBOLS;
629 for (i = 0; i < coff_nsects; i++) {
630 if (segment == coff_sects[i]->index) {
631 r->symbol = i * 2;
632 r->symbase = SECT_SYMBOLS;
633 break;
634 }
635 }
636 if (r->symbase == REAL_SYMBOLS)
637 r->symbol = raa_read(bsym, segment);
638 }
639 r->type = type;
640
641 sect->nrelocs++;
642
643 /*
644 * Return the fixup for standard COFF common variables.
645 */
646 if (r->symbase == REAL_SYMBOLS && !(win32 | win64))
647 return raa_read(symval, segment);
648
649 return 0;
650 }
651
652 static void coff_out(const struct out_data *out)
653 {
654 OUT_LEGACY(out,segto,data,type,size,segment,wrt);
655 struct coff_Section *s;
656 uint8_t mydata[8], *p;
657 int i;
658
659 if (wrt != NO_SEG && !win64) {
660 wrt = NO_SEG; /* continue to do _something_ */
661 nasm_nonfatal("WRT not supported by COFF output formats");
662 }
663
664 s = NULL;
665 for (i = 0; i < coff_nsects; i++) {
666 if (segto == coff_sects[i]->index) {
667 s = coff_sects[i];
668 break;
669 }
670 }
671 if (!s) {
672 int tempint; /* ignored */
673 if (segto != coff_section_names(".text", &tempint))
674 nasm_panic("strange segment conditions in COFF driver");
675 else
676 s = coff_sects[coff_nsects - 1];
677 }
678
679 /* magically default to 'wrt ..imagebase' in .pdata and .xdata */
680 if (win64 && wrt == NO_SEG) {
681 if (!strcmp(s->name,".pdata") || !strcmp(s->name,".xdata"))
682 wrt = imagebase_sect;
683 }
684
685 if (!s->data && type != OUT_RESERVE) {
686 nasm_warn(WARN_OTHER, "attempt to initialize memory in"
687 " BSS section `%s': ignored", s->name);
688 s->len += realsize(type, size);
689 return;
690 }
691
692 memset(mydata, 0, sizeof(mydata));
693
694 if (dfmt && dfmt->debug_output) {
695 struct coff_DebugInfo dinfo;
696 dinfo.segto = segto;
697 dinfo.seg = segment;
698 dinfo.section = s;
699
700 if (type == OUT_ADDRESS)
701 dinfo.size = abs((int)size);
702 else
703 dinfo.size = realsize(type, size);
704
705 dfmt->debug_output(type, &dinfo);
706 }
707
708 if (type == OUT_RESERVE) {
709 if (s->data) {
710 nasm_warn(WARN_ZEROING, "uninitialised space declared in"
711 " non-BSS section `%s': zeroing", s->name);
712 coff_sect_write(s, NULL, size);
713 } else
714 s->len += size;
715 } else if (type == OUT_RAWDATA) {
716 coff_sect_write(s, data, size);
717 } else if (type == OUT_ADDRESS) {
718 int asize = abs((int)size);
719 if (!win64) {
720 if (asize != 4 && (segment != NO_SEG || wrt != NO_SEG)) {
721 nasm_nonfatal("COFF format does not support non-32-bit"
722 " relocations");
723 } else {
724 int32_t fix = 0;
725 if (segment != NO_SEG || wrt != NO_SEG) {
726 if (wrt != NO_SEG) {
727 nasm_nonfatal("COFF format does not support WRT types");
728 } else if (segment % 2) {
729 nasm_nonfatal("COFF format does not support"
730 " segment base references");
731 } else
732 fix = coff_add_reloc(s, segment, IMAGE_REL_I386_DIR32);
733 }
734 p = mydata;
735 WRITELONG(p, *(int64_t *)data + fix);
736 coff_sect_write(s, mydata, asize);
737 }
738 } else {
739 int32_t fix = 0;
740 p = mydata;
741 if (asize == 8) {
742 if (wrt == imagebase_sect) {
743 nasm_nonfatal("operand size mismatch: 'wrt "
744 WRT_IMAGEBASE "' is a 32-bit operand");
745 }
746 fix = coff_add_reloc(s, segment, IMAGE_REL_AMD64_ADDR64);
747 WRITEDLONG(p, *(int64_t *)data + fix);
748 coff_sect_write(s, mydata, asize);
749 } else {
750 fix = coff_add_reloc(s, segment,
751 wrt == imagebase_sect ? IMAGE_REL_AMD64_ADDR32NB:
752 IMAGE_REL_AMD64_ADDR32);
753 WRITELONG(p, *(int64_t *)data + fix);
754 coff_sect_write(s, mydata, asize);
755 }
756 }
757 } else if (type == OUT_REL2ADR) {
758 nasm_nonfatal("COFF format does not support 16-bit relocations");
759 } else if (type == OUT_REL4ADR) {
760 if (segment == segto && !(win64)) /* Acceptable for RIP-relative */
761 nasm_panic("intra-segment OUT_REL4ADR");
762 else if (segment == NO_SEG && win32)
763 nasm_nonfatal("Win32 COFF does not correctly support"
764 " relative references to absolute addresses");
765 else {
766 int32_t fix = 0;
767 if (segment != NO_SEG && segment % 2) {
768 nasm_nonfatal("COFF format does not support"
769 " segment base references");
770 } else
771 fix = coff_add_reloc(s, segment,
772 win64 ? IMAGE_REL_AMD64_REL32 : IMAGE_REL_I386_REL32);
773 p = mydata;
774 if (win32 | win64) {
775 WRITELONG(p, *(int64_t *)data + 4 - size + fix);
776 } else {
777 WRITELONG(p, *(int64_t *)data - (size + s->len) + fix);
778 }
779 coff_sect_write(s, mydata, 4L);
780 }
781
782 }
783 }
784
785 static void coff_sect_write(struct coff_Section *sect,
786 const uint8_t *data, uint32_t len)
787 {
788 saa_wbytes(sect->data, data, len);
789 sect->len += len;
790 }
791
792 typedef struct tagString {
793 struct tagString *next;
794 int len;
795 char *String;
796 } STRING;
797
798 #define EXPORT_SECTION_NAME ".drectve"
799 #define EXPORT_SECTION_FLAGS INFO_FLAGS
800 /*
801 * #define EXPORT_SECTION_NAME ".text"
802 * #define EXPORT_SECTION_FLAGS TEXT_FLAGS
803 */
804
805 static STRING *Exports = NULL;
806 static struct coff_Section *directive_sec;
807 static void AddExport(char *name)
808 {
809 STRING *rvp = Exports, *newS;
810
811 newS = (STRING *) nasm_malloc(sizeof(STRING));
812 newS->len = strlen(name);
813 newS->next = NULL;
814 newS->String = (char *)nasm_malloc(newS->len + 1);
815 strcpy(newS->String, name);
816 if (rvp == NULL) {
817 int i;
818
819 for (i = 0; i < coff_nsects; i++) {
820 if (!strcmp(EXPORT_SECTION_NAME, coff_sects[i]->name))
821 break;
822 }
823
824 if (i == coff_nsects)
825 i = coff_make_section(EXPORT_SECTION_NAME, EXPORT_SECTION_FLAGS);
826
827 directive_sec = coff_sects[i];
828 Exports = newS;
829 } else {
830 while (rvp->next) {
831 if (!strcmp(rvp->String, name))
832 return;
833 rvp = rvp->next;
834 }
835 rvp->next = newS;
836 }
837 }
838
839 static void BuildExportTable(STRING **rvp)
840 {
841 STRING *p, *t;
842
843 if (!rvp || !*rvp)
844 return;
845
846 list_for_each_safe(p, t, *rvp) {
847 coff_sect_write(directive_sec, (uint8_t *)"-export:", 8);
848 coff_sect_write(directive_sec, (uint8_t *)p->String, p->len);
849 coff_sect_write(directive_sec, (uint8_t *)" ", 1);
850 nasm_free(p->String);
851 nasm_free(p);
852 }
853
854 *rvp = NULL;
855 }
856
857 static void coff_defcomdatname(char *name, int32_t segment)
858 {
859 coff_deflabel(name, segment, 0, 1, NULL);
860 }
861
862 static enum directive_result
863 coff_directives(enum directive directive, char *value)
864 {
865 switch (directive) {
866 case D_EXPORT:
867 {
868 char *q, *name;
869
870 /*
871 * XXX: pass_first() is really wrong here, but AddExport()
872 * needs to be modified to handle duplicate calls for the
873 * same value in order to change that. The right thing to do
874 * is probably to mark a label as an export in the label
875 * structure, in case the label doesn't actually exist.
876 */
877 if (!value || !pass_first())
878 return DIRR_OK; /* ignore in pass two */
879 name = q = value;
880 while (*q && !nasm_isspace(*q))
881 q++;
882 if (nasm_isspace(*q)) {
883 *q++ = '\0';
884 while (*q && nasm_isspace(*q))
885 q++;
886 }
887
888 if (!*name) {
889 nasm_nonfatal("`export' directive requires export name");
890 return DIRR_ERROR;
891 }
892 if (*q) {
893 nasm_nonfatal("unrecognized export qualifier `%s'", q);
894 return DIRR_ERROR;
895 }
896 AddExport(name);
897 return DIRR_OK;
898 }
899 case D_SAFESEH:
900 {
901 static int sxseg=-1;
902 int i;
903
904 if (!win32) /* Only applicable for -f win32 */
905 return DIRR_UNKNOWN;
906
907 if (!value)
908 return DIRR_OK;
909
910 if (sxseg == -1) {
911 for (i = 0; i < coff_nsects; i++)
912 if (!strcmp(".sxdata",coff_sects[i]->name))
913 break;
914 if (i == coff_nsects)
915 sxseg = coff_make_section(".sxdata", IMAGE_SCN_LNK_INFO);
916 else
917 sxseg = i;
918 }
919 /*
920 * pass_final() is the only time when the full set of symbols are
921 * guaranteed to be present as it is the final output pass.
922 */
923 if (pass_final()) {
924 uint32_t n;
925 saa_rewind(coff_syms);
926 for (n = 0; n < coff_nsyms; n++) {
927 struct coff_Symbol *sym = saa_rstruct(coff_syms);
928 bool equals;
929
930 /*
931 * sym->strpos is biased by 4, because symbol
932 * table is prefixed with table length
933 */
934 if (sym->strpos >=4) {
935 char *name = nasm_malloc(sym->namlen+1);
936 saa_fread(coff_strs, sym->strpos-4, name, sym->namlen);
937 name[sym->namlen] = '\0';
938 equals = !strcmp(value,name);
939 nasm_free(name);
940 } else {
941 equals = !strcmp(value,sym->name);
942 }
943
944 if (equals) {
945 /*
946 * this value arithmetic effectively reflects
947 * initsym in coff_write(): 2 for file, 1 for
948 * .absolute and two per each section
949 */
950 unsigned char value[4],*p=value;
951 WRITELONG(p,n + 2 + 1 + coff_nsects*2);
952 coff_sect_write(coff_sects[sxseg],value,4);
953 sym->type = 0x20;
954 break;
955 }
956 }
957 if (n == coff_nsyms) {
958 nasm_nonfatal("`safeseh' directive requires valid symbol");
959 return DIRR_ERROR;
960 }
961 }
962 return DIRR_OK;
963 }
964 default:
965 return DIRR_UNKNOWN;
966 }
967 }
968
969 /* handle relocations storm, valid for win32/64 only */
970 static inline void coff_adjust_relocs(struct coff_Section *s)
971 {
972 if (s->nrelocs < IMAGE_SCN_MAX_RELOC)
973 return;
974 #ifdef OF_COFF
975 else
976 {
977 if (ofmt == &of_coff)
978 nasm_fatal("Too many relocations (%d) for section `%s'",
979 s->nrelocs, s->name);
980 }
981 #endif
982
983 s->flags |= IMAGE_SCN_LNK_NRELOC_OVFL;
984 s->nrelocs++;
985 }
986
987 /*
988 * Make sure we satisfy all section alignment requirements and put the
989 * resulting alignment flags into the flags value in the header. If
990 * no user-specified alignment is given, use the default for the
991 * section type; then either way round up to alignment specified by
992 * sectalign directives.
993 */
994 static inline void coff_adjust_alignment(struct coff_Section *s)
995 {
996 uint32_t align_flags = s->align_flags;
997
998 if (!align_flags) {
999 /* No user-specified alignment, use default for partition type */
1000 align_flags = s->flags & IMAGE_SCN_ALIGN_MASK;
1001 }
1002
1003 if (align_flags < s->sectalign_flags)
1004 align_flags = s->sectalign_flags;
1005
1006 s->flags = (s->flags & ~IMAGE_SCN_ALIGN_MASK) | align_flags;
1007 }
1008
1009 static void coff_write(void)
1010 {
1011 int32_t pos, sympos, vsize;
1012 int i;
1013
1014 /* fill in the .drectve section with -export's */
1015 BuildExportTable(&Exports);
1016
1017 if (win32) {
1018 /* add default value for @feat.00, this allows to 'link /safeseh' */
1019 uint32_t n;
1020
1021 saa_rewind(coff_syms);
1022 for (n = 0; n < coff_nsyms; n++) {
1023 struct coff_Symbol *sym = saa_rstruct(coff_syms);
1024 if (sym->strpos == -1 && !strcmp("@feat.00",sym->name))
1025 break;
1026 }
1027 if (n == coff_nsyms)
1028 coff_deflabel("@feat.00", NO_SEG, 1, 0, NULL);
1029 }
1030
1031 /*
1032 * Check all comdat sections
1033 */
1034 for (i = 0; i < coff_nsects; i++)
1035 if (coff_sects[i]->comdat_name) {
1036 if (!coff_sects[i]->comdat_symbol &&
1037 coff_sects[i]->comdat_selection != IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
1038 /*
1039 * This section doesn't have its comdat symbol defined; do it
1040 */
1041 coff_defcomdatname(coff_sects[i]->comdat_name, coff_sects[i]->index);
1042 }
1043 if (!coff_sects[i]->comdat_selection) {
1044 /*
1045 * This is a placeholder section that wasn't properly defined
1046 */
1047 nasm_nonfatal("`comdat' associate with symbol `%s` wasn't defined",
1048 coff_sects[i]->comdat_name);
1049 }
1050 }
1051
1052 /*
1053 * Work out how big the file will get.
1054 * Calculate the start of the `real' symbols at the same time.
1055 * Check for massive relocations.
1056 */
1057 pos = 0x14 + 0x28 * coff_nsects;
1058 initsym = 3; /* two for the file, one absolute */
1059 for (i = 0; i < coff_nsects; i++) {
1060 coff_adjust_alignment(coff_sects[i]);
1061 if (coff_sects[i]->data) {
1062 coff_adjust_relocs(coff_sects[i]);
1063 coff_sects[i]->pos = pos;
1064 pos += coff_sects[i]->len;
1065 coff_sects[i]->relpos = pos;
1066 pos += 10 * coff_sects[i]->nrelocs;
1067 } else
1068 coff_sects[i]->pos = coff_sects[i]->relpos = 0L;
1069 initsym += 2; /* two for each section */
1070 }
1071 sympos = pos;
1072
1073 /*
1074 * Output the COFF header.
1075 */
1076 if (win64)
1077 i = IMAGE_FILE_MACHINE_AMD64;
1078 else
1079 i = IMAGE_FILE_MACHINE_I386;
1080 fwriteint16_t(i, ofile); /* machine type */
1081 fwriteint16_t(coff_nsects, ofile); /* number of sections */
1082 fwriteint32_t(posix_timestamp(), ofile); /* timestamp */
1083 fwriteint32_t(sympos, ofile);
1084 fwriteint32_t(coff_nsyms + initsym, ofile);
1085 fwriteint16_t(0, ofile); /* no optional header */
1086 /* Flags: 32-bit, no line numbers. Win32 doesn't even bother with them. */
1087 fwriteint16_t((win32 | win64) ? 0 : 0x104, ofile);
1088
1089 /*
1090 * Output the section headers.
1091 */
1092 vsize = 0L;
1093 for (i = 0; i < coff_nsects; i++) {
1094 coff_section_header(coff_sects[i]->name, coff_sects[i]->namepos, vsize, coff_sects[i]->len,
1095 coff_sects[i]->pos, coff_sects[i]->relpos,
1096 coff_sects[i]->nrelocs, coff_sects[i]->flags);
1097 vsize += coff_sects[i]->len;
1098 }
1099
1100 /*
1101 * Output the sections and their relocations.
1102 */
1103 for (i = 0; i < coff_nsects; i++)
1104 if (coff_sects[i]->data) {
1105 saa_fpwrite(coff_sects[i]->data, ofile);
1106 coff_write_relocs(coff_sects[i]);
1107
1108 if (coff_sects[i]->flags & IMAGE_SCN_LNK_COMDAT) {
1109 /*
1110 * Checksum the section data
1111 */
1112 uint32_t checksum = 0;
1113 const char *data;
1114 size_t len;
1115
1116 saa_rewind(coff_sects[i]->data);
1117 while (len = coff_sects[i]->data->datalen,
1118 (data = saa_rbytes(coff_sects[i]->data, &len)) != NULL)
1119 checksum = crc32b(checksum, data, len);
1120
1121 coff_sects[i]->checksum = checksum;
1122 }
1123 }
1124
1125 /*
1126 * Output the symbol and string tables.
1127 */
1128 coff_write_symbols();
1129 fwriteint32_t(strslen + 4, ofile); /* length includes length count */
1130 saa_fpwrite(coff_strs, ofile);
1131 }
1132
1133 static void coff_section_header(char *name, int32_t namepos, int32_t vsize,
1134 int32_t datalen, int32_t datapos,
1135 int32_t relpos, int nrelocs, int32_t flags)
1136 {
1137 char padname[8];
1138
1139 (void)vsize;
1140
1141 if (namepos == -1) {
1142 strncpy(padname, name, 8);
1143 nasm_write(padname, 8, ofile);
1144 } else {
1145 /*
1146 * If name is longer than 8 bytes, write '/' followed
1147 * by offset into the strings table represented as
1148 * decimal number.
1149 */
1150 namepos = namepos % 100000000;
1151 padname[0] = '/';
1152 padname[1] = '0' + (namepos / 1000000);
1153 namepos = namepos % 1000000;
1154 padname[2] = '0' + (namepos / 100000);
1155 namepos = namepos % 100000;
1156 padname[3] = '0' + (namepos / 10000);
1157 namepos = namepos % 10000;
1158 padname[4] = '0' + (namepos / 1000);
1159 namepos = namepos % 1000;
1160 padname[5] = '0' + (namepos / 100);
1161 namepos = namepos % 100;
1162 padname[6] = '0' + (namepos / 10);
1163 namepos = namepos % 10;
1164 padname[7] = '0' + (namepos);
1165 nasm_write(padname, 8, ofile);
1166 }
1167
1168 fwriteint32_t(0, ofile); /* Virtual size field - set to 0 or vsize */
1169 fwriteint32_t(0L, ofile); /* RVA/offset - we ignore */
1170 fwriteint32_t(datalen, ofile);
1171 fwriteint32_t(datapos, ofile);
1172 fwriteint32_t(relpos, ofile);
1173 fwriteint32_t(0L, ofile); /* no line numbers - we don't do 'em */
1174
1175 /*
1176 * a special case -- if there are too many relocs
1177 * we have to put IMAGE_SCN_MAX_RELOC here and write
1178 * the real relocs number into VirtualAddress of first
1179 * relocation
1180 */
1181 if (flags & IMAGE_SCN_LNK_NRELOC_OVFL)
1182 fwriteint16_t(IMAGE_SCN_MAX_RELOC, ofile);
1183 else
1184 fwriteint16_t(nrelocs, ofile);
1185
1186 fwriteint16_t(0, ofile); /* again, no line numbers */
1187 fwriteint32_t(flags, ofile);
1188 }
1189
1190 static void coff_write_relocs(struct coff_Section *s)
1191 {
1192 struct coff_Reloc *r;
1193
1194 /* a real number of relocations if needed */
1195 if (s->flags & IMAGE_SCN_LNK_NRELOC_OVFL) {
1196 fwriteint32_t(s->nrelocs, ofile);
1197 fwriteint32_t(0, ofile);
1198 fwriteint16_t(0, ofile);
1199 }
1200
1201 for (r = s->head; r; r = r->next) {
1202 fwriteint32_t(r->address, ofile);
1203 fwriteint32_t(r->symbol + (r->symbase == REAL_SYMBOLS ? initsym :
1204 r->symbase == ABS_SYMBOL ? initsym - 1 :
1205 r->symbase == SECT_SYMBOLS ? 2 : 0),
1206 ofile);
1207 fwriteint16_t(r->type, ofile);
1208 }
1209 }
1210
1211 static void coff_symbol(char *name, int32_t strpos, int32_t value,
1212 int section, int type, int storageclass, int aux)
1213 {
1214 char padname[8];
1215
1216 if (name) {
1217 strncpy(padname, name, 8);
1218 nasm_write(padname, 8, ofile);
1219 } else {
1220 fwriteint32_t(0, ofile);
1221 fwriteint32_t(strpos, ofile);
1222 }
1223
1224 fwriteint32_t(value, ofile);
1225 fwriteint16_t(section, ofile);
1226 fwriteint16_t(type, ofile);
1227
1228 fputc(storageclass, ofile);
1229 fputc(aux, ofile);
1230 }
1231
1232 static void coff_write_symbols(void)
1233 {
1234 char filename[18];
1235 uint32_t i;
1236
1237 /*
1238 * The `.file' record, and the file name auxiliary record.
1239 */
1240 coff_symbol(".file", 0L, 0L, -2, 0, 0x67, 1);
1241 if (reproducible)
1242 memset(filename, 0, 18);
1243 else
1244 strncpy(filename, inname, 18);
1245 nasm_write(filename, 18, ofile);
1246
1247 /*
1248 * The section records, with their auxiliaries.
1249 */
1250 memset(filename, 0, 18); /* useful zeroed buffer */
1251
1252 for (i = 0; i < (uint32_t) coff_nsects; i++) {
1253 coff_symbol(coff_sects[i]->name, 0L, 0L, i + 1, 0, 3, 1);
1254 fwriteint32_t(coff_sects[i]->len, ofile);
1255 fwriteint16_t(coff_sects[i]->nrelocs,ofile);
1256 if (coff_sects[i]->flags & IMAGE_SCN_LNK_COMDAT) {
1257 fwriteint16_t(0, ofile);
1258 fwriteint32_t(coff_sects[i]->checksum, ofile);
1259 fwriteint16_t(coff_sects[i]->comdat_associated, ofile);
1260 fputc(coff_sects[i]->comdat_selection, ofile);
1261 nasm_write(filename, 3, ofile);
1262 }
1263 else
1264 nasm_write(filename, 12, ofile);
1265 }
1266
1267 /*
1268 * The absolute symbol, for relative-to-absolute relocations.
1269 */
1270 coff_symbol(".absolut", 0L, 0L, -1, 0, 3, 0);
1271
1272 /*
1273 * The real symbols.
1274 */
1275 saa_rewind(coff_syms);
1276 for (i = 0; i < coff_nsyms; i++) {
1277 struct coff_Symbol *sym = saa_rstruct(coff_syms);
1278 coff_symbol(sym->strpos == -1 ? sym->name : NULL,
1279 sym->strpos, sym->value, sym->section,
1280 sym->type, sym->is_global ? 2 : 3, 0);
1281 }
1282 }
1283
1284 static void coff_sectalign(int32_t seg, unsigned int value)
1285 {
1286 struct coff_Section *s = NULL;
1287 uint32_t flags;
1288 int i;
1289
1290 for (i = 0; i < coff_nsects; i++) {
1291 if (coff_sects[i]->index == seg) {
1292 s = coff_sects[i];
1293 break;
1294 }
1295 }
1296
1297 if (!s || !is_power2(value))
1298 return;
1299
1300 if (value > COFF_MAX_ALIGNMENT)
1301 value = COFF_MAX_ALIGNMENT; /* Do our best... */
1302
1303 flags = coff_sectalign_flags(value);
1304 if (flags > s->sectalign_flags)
1305 s->sectalign_flags = flags;
1306 }
1307
1308 extern macros_t coff_stdmac[];
1309
1310 #endif /* defined(OF_COFF) || defined(OF_WIN32) */
1311
1312 #ifdef OF_COFF
1313
1314 static const struct pragma_facility coff_pragma_list[] = {
1315 { "coff", NULL },
1316 { NULL, NULL }
1317 };
1318
1319 const struct ofmt of_coff = {
1320 "COFF (i386) (DJGPP, some Unix variants)",
1321 "coff",
1322 ".o",
1323 0,
1324 32,
1325 null_debug_arr,
1326 &null_debug_form,
1327 coff_stdmac,
1328 coff_std_init,
1329 null_reset,
1330 coff_out,
1331 coff_deflabel,
1332 coff_section_names,
1333 NULL,
1334 coff_sectalign,
1335 null_segbase,
1336 coff_directives,
1337 coff_cleanup,
1338 coff_pragma_list
1339 };
1340
1341 #endif
1342
1343
1344 #ifdef OF_WIN32
1345
1346 static const struct pragma_facility coff_win_pragma_list[] = {
1347 { "win", NULL },
1348 { "coff", NULL },
1349 { NULL, NULL }
1350 };
1351
1352 extern const struct dfmt df_cv8;
1353 static const struct dfmt * const win32_debug_arr[2] = { &df_cv8, NULL };
1354
1355 const struct ofmt of_win32 = {
1356 "Microsoft extended COFF for Win32 (i386)",
1357 "win32",
1358 ".obj",
1359 0,
1360 32,
1361 win32_debug_arr,
1362 &df_cv8,
1363 coff_stdmac,
1364 coff_win32_init,
1365 null_reset,
1366 coff_out,
1367 coff_deflabel,
1368 coff_section_names,
1369 NULL,
1370 coff_sectalign,
1371 null_segbase,
1372 coff_directives,
1373 coff_cleanup,
1374 coff_win_pragma_list
1375 };
1376
1377 #endif
1378
1379 #ifdef OF_WIN64
1380
1381 static const struct dfmt * const win64_debug_arr[2] = { &df_cv8, NULL };
1382
1383 const struct ofmt of_win64 = {
1384 "Microsoft extended COFF for Win64 (x86-64)",
1385 "win64",
1386 ".obj",
1387 0,
1388 64,
1389 win64_debug_arr,
1390 &df_cv8,
1391 coff_stdmac,
1392 coff_win64_init,
1393 null_reset,
1394 coff_out,
1395 coff_deflabel,
1396 coff_section_names,
1397 NULL,
1398 coff_sectalign,
1399 null_segbase,
1400 coff_directives,
1401 coff_cleanup,
1402 coff_win_pragma_list
1403 };
1404
1405 #endif