NASM 0.97
[nasm.git] / outcoff.c
blob09e886ceb93f7956d64b3e5135cc80f0b9bc3280
1 /* outcoff.c output routines for the Netwide Assembler to produce
2 * COFF object files (for DJGPP and Win32)
4 * The Netwide Assembler is copyright (C) 1996 Simon Tatham and
5 * Julian Hall. All rights reserved. The software is
6 * redistributable under the licence given in the file "Licence"
7 * distributed in the NASM archive.
8 */
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <ctype.h>
14 #include <time.h>
16 #include "nasm.h"
17 #include "nasmlib.h"
18 #include "outform.h"
20 #if defined(OF_COFF) || defined(OF_WIN32)
23 * Notes on COFF:
25 * (0) When I say `standard COFF' below, I mean `COFF as output and
26 * used by DJGPP'. I assume DJGPP gets it right.
28 * (1) Win32 appears to interpret the term `relative relocation'
29 * differently from standard COFF. Standard COFF understands a
30 * relative relocation to mean that during relocation you add the
31 * address of the symbol you're referencing, and subtract the base
32 * address of the section you're in. Win32 COFF, by contrast, seems
33 * to add the address of the symbol and then subtract the address
34 * of THE BYTE AFTER THE RELOCATED DWORD. Hence the two formats are
35 * subtly incompatible.
37 * (2) Win32 doesn't bother putting any flags in the header flags
38 * field (at offset 0x12 into the file).
40 * (3) Win32 uses some extra flags into the section header table:
41 * it defines flags 0x80000000 (writable), 0x40000000 (readable)
42 * and 0x20000000 (executable), and uses them in the expected
43 * combinations. It also defines 0x00100000 through 0x00700000 for
44 * section alignments of 1 through 64 bytes.
46 * (4) Both standard COFF and Win32 COFF seem to use the DWORD
47 * field directly after the section name in the section header
48 * table for something strange: they store what the address of the
49 * section start point _would_ be, if you laid all the sections end
50 * to end starting at zero. Dunno why. Microsoft's documentation
51 * lists this field as "Virtual Size of Section", which doesn't
52 * seem to fit at all. In fact, Win32 even includes non-linked
53 * sections such as .drectve in this calculation.
55 * (5) Standard COFF does something very strange to common
56 * variables: the relocation point for a common variable is as far
57 * _before_ the variable as its size stretches out _after_ it. So
58 * we must fix up common variable references. Win32 seems to be
59 * sensible on this one.
62 /* Flag which version of COFF we are currently outputting. */
63 static int win32;
65 struct Reloc {
66 struct Reloc *next;
67 long address; /* relative to _start_ of section */
68 long symbol; /* symbol number */
69 enum {
70 SECT_SYMBOLS,
71 ABS_SYMBOL,
72 REAL_SYMBOLS
73 } symbase; /* relocation for symbol number :) */
74 int relative; /* TRUE or FALSE */
77 struct Symbol {
78 char name[9];
79 long strpos; /* string table position of name */
80 int section; /* section number where it's defined
81 * - in COFF codes, not NASM codes */
82 int is_global; /* is it a global symbol or not? */
83 long value; /* address, or COMMON variable size */
86 static FILE *coffp;
87 static efunc error;
88 static char coff_infile[FILENAME_MAX];
90 struct Section {
91 struct SAA *data;
92 unsigned long len;
93 int nrelocs;
94 long index;
95 struct Reloc *head, **tail;
96 unsigned long flags; /* section flags */
97 char name[9];
98 long pos, relpos;
101 #define TEXT_FLAGS (win32 ? 0x60500020L : 0x20L)
102 #define DATA_FLAGS (win32 ? 0xC0300040L : 0x40L)
103 #define BSS_FLAGS (win32 ? 0xC0300080L : 0x80L)
104 #define INFO_FLAGS 0x00100A00L
106 #define SECT_DELTA 32
107 static struct Section **sects;
108 static int nsects, sectlen;
110 static struct SAA *syms;
111 static unsigned long nsyms;
113 static long def_seg;
115 static int initsym;
117 static struct RAA *bsym, *symval;
119 static struct SAA *strs;
120 static unsigned long strslen;
122 static void coff_gen_init(FILE *, efunc);
123 static void coff_sect_write (struct Section *, unsigned char *,
124 unsigned long);
125 static void coff_write (void);
126 static void coff_section_header (char *, long, long, long, long, int, long);
127 static void coff_write_relocs (struct Section *);
128 static void coff_write_symbols (void);
130 static void coff_win32_init(FILE *fp, efunc errfunc,
131 ldfunc ldef, evalfunc eval) {
132 win32 = TRUE;
133 (void) ldef; /* placate optimisers */
134 coff_gen_init(fp, errfunc);
137 static void coff_std_init(FILE *fp, efunc errfunc,
138 ldfunc ldef, evalfunc eval) {
139 win32 = FALSE;
140 (void) ldef; /* placate optimisers */
141 coff_gen_init(fp, errfunc);
144 static void coff_gen_init(FILE *fp, efunc errfunc) {
145 coffp = fp;
146 error = errfunc;
147 sects = NULL;
148 nsects = sectlen = 0;
149 syms = saa_init((long)sizeof(struct Symbol));
150 nsyms = 0;
151 bsym = raa_init();
152 symval = raa_init();
153 strs = saa_init(1L);
154 strslen = 0;
155 def_seg = seg_alloc();
158 static void coff_cleanup(void) {
159 struct Reloc *r;
160 int i;
162 coff_write();
163 fclose (coffp);
164 for (i=0; i<nsects; i++) {
165 if (sects[i]->data)
166 saa_free (sects[i]->data);
167 while (sects[i]->head) {
168 r = sects[i]->head;
169 sects[i]->head = sects[i]->head->next;
170 nasm_free (r);
173 nasm_free (sects);
174 saa_free (syms);
175 raa_free (bsym);
176 raa_free (symval);
177 saa_free (strs);
180 static int coff_make_section (char *name, unsigned long flags) {
181 struct Section *s;
183 s = nasm_malloc (sizeof(*s));
185 if (flags != BSS_FLAGS)
186 s->data = saa_init (1L);
187 else
188 s->data = NULL;
189 s->head = NULL;
190 s->tail = &s->head;
191 s->len = 0;
192 s->nrelocs = 0;
193 if (!strcmp(name, ".text"))
194 s->index = def_seg;
195 else
196 s->index = seg_alloc();
197 strncpy (s->name, name, 8);
198 s->name[8] = '\0';
199 s->flags = flags;
201 if (nsects >= sectlen)
202 sects = nasm_realloc (sects, (sectlen += SECT_DELTA)*sizeof(*sects));
203 sects[nsects++] = s;
205 return nsects-1;
208 static long coff_section_names (char *name, int pass, int *bits) {
209 char *p;
210 unsigned long flags, align_and = ~0L, align_or = 0L;
211 int i;
214 * Default is 32 bits.
216 if (!name)
217 *bits = 32;
219 if (!name)
220 return def_seg;
222 p = name;
223 while (*p && !isspace(*p)) p++;
224 if (*p) *p++ = '\0';
225 if (strlen(name) > 8) {
226 error (ERR_WARNING, "COFF section names limited to 8 characters:"
227 " truncating");
228 p[8] = '\0';
230 flags = 0;
232 while (*p && isspace(*p)) p++;
233 while (*p) {
234 char *q = p;
235 while (*p && !isspace(*p)) p++;
236 if (*p) *p++ = '\0';
237 while (*p && isspace(*p)) p++;
239 if (!nasm_stricmp(q, "code") || !nasm_stricmp(q, "text")) {
240 flags = TEXT_FLAGS;
241 } else if (!nasm_stricmp(q, "data")) {
242 flags = DATA_FLAGS;
243 } else if (!nasm_stricmp(q, "bss")) {
244 flags = BSS_FLAGS;
245 } else if (!nasm_stricmp(q, "info")) {
246 if (win32)
247 flags = INFO_FLAGS;
248 else {
249 flags = DATA_FLAGS; /* gotta do something */
250 error (ERR_NONFATAL, "standard COFF does not support"
251 " informational sections");
253 } else if (!nasm_strnicmp(q,"align=",6)) {
254 if (!win32)
255 error (ERR_NONFATAL, "standard COFF does not support"
256 " section alignment specification");
257 else {
258 if (q[6+strspn(q+6,"0123456789")])
259 error(ERR_NONFATAL, "argument to `align' is not numeric");
260 else {
261 unsigned int align = atoi(q+6);
262 if (!align || ((align-1) & align))
263 error(ERR_NONFATAL, "argument to `align' is not a"
264 " power of two");
265 else if (align > 64)
266 error(ERR_NONFATAL, "Win32 cannot align sections"
267 " to better than 64-byte boundaries");
268 else {
269 align_and = ~0x00F00000L;
270 align_or = (align == 1 ? 0x00100000L :
271 align == 2 ? 0x00200000L :
272 align == 4 ? 0x00300000L :
273 align == 8 ? 0x00400000L :
274 align == 16 ? 0x00500000L :
275 align == 32 ? 0x00600000L : 0x00700000L);
282 for (i=0; i<nsects; i++)
283 if (!strcmp(name, sects[i]->name))
284 break;
285 if (i == nsects) {
286 if (!flags) {
287 if (!strcmp(name, ".data"))
288 flags = DATA_FLAGS;
289 else if (!strcmp(name, ".bss"))
290 flags = BSS_FLAGS;
291 else
292 flags = TEXT_FLAGS;
294 i = coff_make_section (name, flags);
295 if (flags)
296 sects[i]->flags = flags;
297 sects[i]->flags &= align_and;
298 sects[i]->flags |= align_or;
299 } else if (pass == 1) {
300 if (flags)
301 error (ERR_WARNING, "section attributes ignored on"
302 " redeclaration of section `%s'", name);
305 return sects[i]->index;
308 static void coff_deflabel (char *name, long segment, long offset,
309 int is_global, char *special) {
310 int pos = strslen+4;
311 struct Symbol *sym;
313 if (special)
314 error (ERR_NONFATAL, "binary format does not support any"
315 " special symbol types");
317 if (name[0] == '.' && name[1] == '.' && name[2] != '@') {
318 error (ERR_NONFATAL, "unrecognised special symbol `%s'", name);
319 return;
322 if (strlen(name) > 8) {
323 saa_wbytes (strs, name, (long)(1+strlen(name)));
324 strslen += 1+strlen(name);
325 } else
326 pos = -1;
328 sym = saa_wstruct (syms);
330 sym->strpos = pos;
331 if (pos == -1)
332 strcpy (sym->name, name);
333 sym->is_global = !!is_global;
334 if (segment == NO_SEG)
335 sym->section = -1; /* absolute symbol */
336 else {
337 int i;
338 sym->section = 0;
339 for (i=0; i<nsects; i++)
340 if (segment == sects[i]->index) {
341 sym->section = i+1;
342 break;
344 if (!sym->section)
345 sym->is_global = TRUE;
347 if (is_global == 2)
348 sym->value = offset;
349 else
350 sym->value = (sym->section == 0 ? 0 : offset);
353 * define the references from external-symbol segment numbers
354 * to these symbol records.
356 if (sym->section == 0)
357 bsym = raa_write (bsym, segment, nsyms);
359 if (segment != NO_SEG)
360 symval = raa_write (symval, segment, sym->section ? 0 : sym->value);
362 nsyms++;
365 static long coff_add_reloc (struct Section *sect, long segment,
366 int relative) {
367 struct Reloc *r;
369 r = *sect->tail = nasm_malloc(sizeof(struct Reloc));
370 sect->tail = &r->next;
371 r->next = NULL;
373 r->address = sect->len;
374 if (segment == NO_SEG)
375 r->symbol = 0, r->symbase = ABS_SYMBOL;
376 else {
377 int i;
378 r->symbase = REAL_SYMBOLS;
379 for (i=0; i<nsects; i++)
380 if (segment == sects[i]->index) {
381 r->symbol = i*2;
382 r->symbase = SECT_SYMBOLS;
383 break;
385 if (r->symbase == REAL_SYMBOLS)
386 r->symbol = raa_read (bsym, segment);
388 r->relative = relative;
390 sect->nrelocs++;
393 * Return the fixup for standard COFF common variables.
395 if (r->symbase == REAL_SYMBOLS && !win32)
396 return raa_read (symval, segment);
397 else
398 return 0;
401 static void coff_out (long segto, void *data, unsigned long type,
402 long segment, long wrt) {
403 struct Section *s;
404 long realbytes = type & OUT_SIZMASK;
405 unsigned char mydata[4], *p;
406 int i;
408 if (wrt != NO_SEG) {
409 wrt = NO_SEG; /* continue to do _something_ */
410 error (ERR_NONFATAL, "WRT not supported by COFF output formats");
413 type &= OUT_TYPMASK;
416 * handle absolute-assembly (structure definitions)
418 if (segto == NO_SEG) {
419 if (type != OUT_RESERVE)
420 error (ERR_NONFATAL, "attempt to assemble code in [ABSOLUTE]"
421 " space");
422 return;
425 s = NULL;
426 for (i=0; i<nsects; i++)
427 if (segto == sects[i]->index) {
428 s = sects[i];
429 break;
431 if (!s) {
432 int tempint; /* ignored */
433 if (segto != coff_section_names (".text", 2, &tempint))
434 error (ERR_PANIC, "strange segment conditions in COFF driver");
435 else
436 s = sects[nsects-1];
439 if (!s->data && type != OUT_RESERVE) {
440 error(ERR_WARNING, "attempt to initialise memory in"
441 " BSS section `%s': ignored", s->name);
442 if (type == OUT_REL2ADR)
443 realbytes = 2;
444 else if (type == OUT_REL4ADR)
445 realbytes = 4;
446 s->len += realbytes;
447 return;
450 if (type == OUT_RESERVE) {
451 if (s->data) {
452 error(ERR_WARNING, "uninitialised space declared in"
453 " non-BSS section `%s': zeroing", s->name);
454 coff_sect_write (s, NULL, realbytes);
455 } else
456 s->len += realbytes;
457 } else if (type == OUT_RAWDATA) {
458 if (segment != NO_SEG)
459 error(ERR_PANIC, "OUT_RAWDATA with other than NO_SEG");
460 coff_sect_write (s, data, realbytes);
461 } else if (type == OUT_ADDRESS) {
462 if (realbytes != 4 && (segment != NO_SEG || wrt != NO_SEG))
463 error(ERR_NONFATAL, "COFF format does not support non-32-bit"
464 " relocations");
465 else {
466 long fix = 0;
467 if (segment != NO_SEG || wrt != NO_SEG) {
468 if (wrt != NO_SEG) {
469 error(ERR_NONFATAL, "COFF format does not support"
470 " WRT types");
471 } else if (segment % 2) {
472 error(ERR_NONFATAL, "COFF format does not support"
473 " segment base references");
474 } else
475 fix = coff_add_reloc (s, segment, FALSE);
477 p = mydata;
478 WRITELONG (p, *(long *)data + fix);
479 coff_sect_write (s, mydata, realbytes);
481 } else if (type == OUT_REL2ADR) {
482 error(ERR_NONFATAL, "COFF format does not support 16-bit"
483 " relocations");
484 } else if (type == OUT_REL4ADR) {
485 if (segment == segto)
486 error(ERR_PANIC, "intra-segment OUT_REL4ADR");
487 else if (segment == NO_SEG && win32)
488 error(ERR_NONFATAL, "Win32 COFF does not correctly support"
489 " relative references to absolute addresses");
490 else {
491 long fix = 0;
492 if (segment != NO_SEG && segment % 2) {
493 error(ERR_NONFATAL, "COFF format does not support"
494 " segment base references");
495 } else
496 fix = coff_add_reloc (s, segment, TRUE);
497 p = mydata;
498 if (win32) {
499 WRITELONG (p, *(long*)data + 4 - realbytes + fix);
500 } else {
501 WRITELONG (p, *(long*)data-(realbytes + s->len) + fix);
503 coff_sect_write (s, mydata, 4L);
508 static void coff_sect_write (struct Section *sect,
509 unsigned char *data, unsigned long len) {
510 saa_wbytes (sect->data, data, len);
511 sect->len += len;
514 static int coff_directives (char *directive, char *value, int pass) {
515 return 0;
518 static void coff_write (void) {
519 long pos, sympos, vsize;
520 int i;
523 * Work out how big the file will get. Calculate the start of
524 * the `real' symbols at the same time.
526 pos = 0x14 + 0x28 * nsects;
527 initsym = 3; /* two for the file, one absolute */
528 for (i=0; i<nsects; i++) {
529 if (sects[i]->data) {
530 sects[i]->pos = pos;
531 pos += sects[i]->len;
532 sects[i]->relpos = pos;
533 pos += 10 * sects[i]->nrelocs;
534 } else
535 sects[i]->pos = sects[i]->relpos = 0L;
536 initsym += 2; /* two for each section */
538 sympos = pos;
541 * Output the COFF header.
543 fwriteshort (0x14C, coffp); /* MACHINE_i386 */
544 fwriteshort (nsects, coffp); /* number of sections */
545 fwritelong (time(NULL), coffp); /* time stamp */
546 fwritelong (sympos, coffp);
547 fwritelong (nsyms + initsym, coffp);
548 fwriteshort (0, coffp); /* no optional header */
549 /* Flags: 32-bit, no line numbers. Win32 doesn't even bother with them. */
550 fwriteshort (win32 ? 0 : 0x104, coffp);
553 * Output the section headers.
555 vsize = 0L;
556 for (i=0; i<nsects; i++) {
557 coff_section_header (sects[i]->name, vsize, sects[i]->len,
558 sects[i]->pos, sects[i]->relpos,
559 sects[i]->nrelocs, sects[i]->flags);
560 vsize += sects[i]->len;
564 * Output the sections and their relocations.
566 for (i=0; i<nsects; i++)
567 if (sects[i]->data) {
568 saa_fpwrite (sects[i]->data, coffp);
569 coff_write_relocs (sects[i]);
573 * Output the symbol and string tables.
575 coff_write_symbols();
576 fwritelong (strslen+4, coffp); /* length includes length count */
577 saa_fpwrite (strs, coffp);
580 static void coff_section_header (char *name, long vsize,
581 long datalen, long datapos,
582 long relpos, int nrelocs, long flags) {
583 char padname[8];
585 memset (padname, 0, 8);
586 strncpy (padname, name, 8);
587 fwrite (padname, 8, 1, coffp);
588 fwritelong (vsize, coffp);
589 fwritelong (0L, coffp); /* RVA/offset - we ignore */
590 fwritelong (datalen, coffp);
591 fwritelong (datapos, coffp);
592 fwritelong (relpos, coffp);
593 fwritelong (0L, coffp); /* no line numbers - we don't do 'em */
594 fwriteshort (nrelocs, coffp);
595 fwriteshort (0, coffp); /* again, no line numbers */
596 fwritelong (flags, coffp);
599 static void coff_write_relocs (struct Section *s) {
600 struct Reloc *r;
602 for (r = s->head; r; r = r->next) {
603 fwritelong (r->address, coffp);
604 fwritelong (r->symbol + (r->symbase == REAL_SYMBOLS ? initsym :
605 r->symbase == ABS_SYMBOL ? initsym-1 :
606 r->symbase == SECT_SYMBOLS ? 2 : 0), coffp);
608 * Strange: Microsoft's COFF documentation says 0x03 for an
609 * absolute relocation, but both Visual C++ and DJGPP agree
610 * that in fact it's 0x06. I'll use 0x06 until someone
611 * argues.
613 fwriteshort (r->relative ? 0x14 : 0x06, coffp);
617 static void coff_symbol (char *name, long strpos, long value,
618 int section, int type, int aux) {
619 char padname[8];
621 if (name) {
622 memset (padname, 0, 8);
623 strncpy (padname, name, 8);
624 fwrite (padname, 8, 1, coffp);
625 } else {
626 fwritelong (0L, coffp);
627 fwritelong (strpos, coffp);
629 fwritelong (value, coffp);
630 fwriteshort (section, coffp);
631 fwriteshort (0, coffp);
632 fputc (type, coffp);
633 fputc (aux, coffp);
636 static void coff_write_symbols (void) {
637 char filename[18];
638 int i;
641 * The `.file' record, and the file name auxiliary record.
643 coff_symbol (".file", 0L, 0L, -2, 0x67, 1);
644 memset (filename, 0, 18);
645 strncpy (filename, coff_infile, 18);
646 fwrite (filename, 18, 1, coffp);
649 * The section records, with their auxiliaries.
651 memset (filename, 0, 18); /* useful zeroed buffer */
653 for (i=0; i<nsects; i++) {
654 coff_symbol (sects[i]->name, 0L, 0L, i+1, 3, 1);
655 fwritelong (sects[i]->len, coffp);
656 fwriteshort (sects[i]->nrelocs, coffp);
657 fwrite (filename, 12, 1, coffp);
661 * The absolute symbol, for relative-to-absolute relocations.
663 coff_symbol (".absolut", 0L, 0L, -1, 3, 0);
666 * The real symbols.
668 saa_rewind (syms);
669 for (i=0; i<nsyms; i++) {
670 struct Symbol *sym = saa_rstruct (syms);
671 coff_symbol (sym->strpos == -1 ? sym->name : NULL,
672 sym->strpos, sym->value, sym->section,
673 sym->is_global ? 2 : 3, 0);
677 static long coff_segbase (long segment) {
678 return segment;
681 static void coff_std_filename (char *inname, char *outname, efunc error) {
682 strcpy(coff_infile, inname);
683 standard_extension (inname, outname, ".o", error);
686 static void coff_win32_filename (char *inname, char *outname, efunc error) {
687 strcpy(coff_infile, inname);
688 standard_extension (inname, outname, ".obj", error);
691 #endif /* defined(OF_COFF) || defined(OF_WIN32) */
693 static char *coff_stdmac[] = {
694 "%define __SECT__ [section .text]",
695 NULL
698 #ifdef OF_COFF
700 struct ofmt of_coff = {
701 "COFF (i386) object files (e.g. DJGPP for DOS)",
702 "coff",
703 coff_stdmac,
704 coff_std_init,
705 coff_out,
706 coff_deflabel,
707 coff_section_names,
708 coff_segbase,
709 coff_directives,
710 coff_std_filename,
711 coff_cleanup
714 #endif
716 #ifdef OF_WIN32
718 struct ofmt of_win32 = {
719 "Microsoft Win32 (i386) object files",
720 "win32",
721 coff_stdmac,
722 coff_win32_init,
723 coff_out,
724 coff_deflabel,
725 coff_section_names,
726 coff_segbase,
727 coff_directives,
728 coff_win32_filename,
729 coff_cleanup
732 #endif