NASM 0.95
[platform/upstream/nasm.git] / outcoff.c
1 /* outcoff.c    output routines for the Netwide Assembler to produce
2  *              COFF object files (for DJGPP and Win32)
3  *
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  */
9
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <ctype.h>
14 #include <time.h>
15
16 #include "nasm.h"
17 #include "nasmlib.h"
18 #include "outform.h"
19
20 #if defined(OF_COFF) || defined(OF_WIN32)
21
22 /*
23  * Notes on COFF:
24  *
25  * (0) When I say `standard COFF' below, I mean `COFF as output and
26  * used by DJGPP'. I assume DJGPP gets it right.
27  *
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.
36  *
37  * (2) Win32 doesn't bother putting any flags in the header flags
38  * field (at offset 0x12 into the file).
39  *
40  * (3) Win32 puts some weird flags into the section header table.
41  * It uses flags 0x80000000 (writable), 0x40000000 (readable) and
42  * 0x20000000 (executable) in the expected combinations, which
43  * standard COFF doesn't seem to bother with, but it also does
44  * something else strange: it also flags code sections as
45  * 0x00500000 and data/bss as 0x00300000. Even Microsoft's
46  * documentation doesn't explain what these things mean. I just go
47  * ahead and use them anyway - it seems to work.
48  *
49  * (4) Both standard COFF and Win32 COFF seem to use the DWORD
50  * field directly after the section name in the section header
51  * table for something strange: they store what the address of the
52  * section start point _would_ be, if you laid all the sections end
53  * to end starting at zero. Dunno why. Microsoft's documentation
54  * lists this field as "Virtual Size of Section", which doesn't
55  * seem to fit at all. In fact, Win32 even includes non-linked
56  * sections such as .drectve in this calculation. Not that I can be
57  * bothered with those things anyway.
58  *
59  * (5) Standard COFF does something very strange to common
60  * variables: the relocation point for a common variable is as far
61  * _before_ the variable as its size stretches out _after_ it. So
62  * we must fix up common variable references. Win32 seems to be
63  * sensible on this one.
64  */
65
66 /* Flag which version of COFF we are currently outputting. */
67 static int win32;
68
69 struct Reloc {
70     struct Reloc *next;
71     long address;                      /* relative to _start_ of section */
72     long symbol;                       /* symbol number */
73     enum {
74         SECT_SYMBOLS,
75         ABS_SYMBOL,
76         REAL_SYMBOLS
77     } symbase;                         /* relocation for symbol number :) */
78     int relative;                      /* TRUE or FALSE */
79 };
80
81 struct Symbol {
82     char name[9];
83     long strpos;                       /* string table position of name */
84     int section;                       /* section number where it's defined
85                                         * - in COFF codes, not NASM codes */
86     int is_global;                     /* is it a global symbol or not? */
87     long value;                        /* address, or COMMON variable size */
88 };
89
90 static FILE *coffp;
91 static efunc error;
92 static char coff_infile[FILENAME_MAX];
93
94 struct Section {
95     struct SAA *data;
96     unsigned long len;
97     int nrelocs;
98     long index;
99     struct Reloc *head, **tail;
100     unsigned long flags;               /* section flags */
101     char name[9];
102     long pos, relpos;
103 };
104
105 #define TEXT_FLAGS (win32 ? 0x60500020L : 0x20L)
106 #define DATA_FLAGS (win32 ? 0xC0300040L : 0x40L)
107 #define BSS_FLAGS (win32 ? 0xC0300080L : 0x80L)
108 #define INFO_FLAGS 0x00100A00L
109
110 #define SECT_DELTA 32
111 static struct Section **sects;
112 static int nsects, sectlen;
113
114 static struct SAA *syms;
115 static unsigned long nsyms;
116
117 static long def_seg;
118
119 static int initsym;
120
121 static struct RAA *bsym, *symval;
122
123 static struct SAA *strs;
124 static unsigned long strslen;
125
126 static void coff_gen_init(FILE *, efunc);
127 static void coff_sect_write (struct Section *, unsigned char *,
128                              unsigned long);
129 static void coff_write (void);
130 static void coff_section_header (char *, long, long, long, long, int, long);
131 static void coff_write_relocs (struct Section *);
132 static void coff_write_symbols (void);
133
134 static void coff_win32_init(FILE *fp, efunc errfunc, ldfunc ldef) {
135     win32 = TRUE;
136     (void) ldef;                       /* placate optimisers */
137     coff_gen_init(fp, errfunc);
138 }
139
140 static void coff_std_init(FILE *fp, efunc errfunc, ldfunc ldef) {
141     win32 = FALSE;
142     (void) ldef;                       /* placate optimisers */
143     coff_gen_init(fp, errfunc);
144 }
145
146 static void coff_gen_init(FILE *fp, efunc errfunc) {
147     coffp = fp;
148     error = errfunc;
149     sects = NULL;
150     nsects = sectlen = 0;
151     syms = saa_init((long)sizeof(struct Symbol));
152     nsyms = 0;
153     bsym = raa_init();
154     symval = raa_init();
155     strs = saa_init(1L);
156     strslen = 0;
157     def_seg = seg_alloc();
158 }
159
160 static void coff_cleanup(void) {
161     struct Reloc *r;
162     int i;
163
164     coff_write();
165     fclose (coffp);
166     for (i=0; i<nsects; i++) {
167         if (sects[i]->data)
168             saa_free (sects[i]->data);
169         while (sects[i]->head) {
170             r = sects[i]->head;
171             sects[i]->head = sects[i]->head->next;
172             nasm_free (r);
173         }
174     }
175     nasm_free (sects);
176     saa_free (syms);
177     raa_free (bsym);
178     raa_free (symval);
179     saa_free (strs);
180 }
181
182 static int coff_make_section (char *name, unsigned long flags) {
183     struct Section *s;
184
185     s = nasm_malloc (sizeof(*s));
186
187     if (flags != BSS_FLAGS)
188         s->data = saa_init (1L);
189     else
190         s->data = NULL;
191     s->head = NULL;
192     s->tail = &s->head;
193     s->len = 0;
194     s->nrelocs = 0;
195     if (!strcmp(name, ".text"))
196         s->index = def_seg;
197     else
198         s->index = seg_alloc();
199     strncpy (s->name, name, 8);
200     s->name[8] = '\0';
201     s->flags = flags;
202
203     if (nsects >= sectlen)
204         sects = nasm_realloc (sects, (sectlen += SECT_DELTA)*sizeof(*sects));
205     sects[nsects++] = s;
206
207     return nsects-1;
208 }
209
210 static long coff_section_names (char *name, int pass, int *bits) {
211     char *p;
212     unsigned long flags;
213     int i;
214
215     /*
216      * Default is 32 bits.
217      */
218     if (!name)
219         *bits = 32;
220
221     if (!name)
222         return def_seg;
223
224     p = name;
225     while (*p && !isspace(*p)) p++;
226     if (*p) *p++ = '\0';
227     if (strlen(p) > 8) {
228         error (ERR_WARNING, "COFF section names limited to 8 characters:"
229                " truncating");
230         p[8] = '\0';
231     }
232     flags = 0;
233
234     while (*p && isspace(*p)) p++;
235     while (*p) {
236         char *q = p;
237         while (*p && !isspace(*p)) p++;
238         if (*p) *p++ = '\0';
239         while (*p && isspace(*p)) p++;
240         
241         if (!nasm_stricmp(q, "code") || !nasm_stricmp(q, "text")) {
242             flags = TEXT_FLAGS;
243         } else if (!nasm_stricmp(q, "data")) {
244             flags = DATA_FLAGS;
245         } else if (!nasm_stricmp(q, "bss")) {
246             flags = BSS_FLAGS;
247         } else if (!nasm_stricmp(q, "info")) {
248             if (win32)
249                 flags = INFO_FLAGS;
250             else {
251                 flags = DATA_FLAGS;    /* gotta do something */
252                 error (ERR_NONFATAL, "standard COFF does not support"
253                        " informational sections");
254             }
255         }
256     }
257
258     for (i=0; i<nsects; i++)
259         if (!strcmp(name, sects[i]->name))
260             break;
261     if (i == nsects) {
262         if (!strcmp(name, ".text") && !flags)
263             i = coff_make_section (name, TEXT_FLAGS);
264         else if (!strcmp(name, ".data") && !flags)
265             i = coff_make_section (name, DATA_FLAGS);
266         else if (!strcmp(name, ".bss") && !flags)
267             i = coff_make_section (name, BSS_FLAGS);
268         else if (flags)
269             i = coff_make_section (name, flags);
270         else
271             i = coff_make_section (name, TEXT_FLAGS);
272         if (flags)
273             sects[i]->flags = flags;
274     } else if (pass == 1) {
275         if (flags)
276             error (ERR_WARNING, "section attributes ignored on"
277                    " redeclaration of section `%s'", name);
278     }
279
280     return sects[i]->index;
281 }
282
283 static void coff_deflabel (char *name, long segment, long offset,
284                            int is_global) {
285     int pos = strslen+4;
286     struct Symbol *sym;
287
288     if (name[0] == '.' && name[1] == '.' && name[2] != '@') {
289         error (ERR_NONFATAL, "unrecognised special symbol `%s'", name);
290         return;
291     }
292
293     if (strlen(name) > 8) {
294         saa_wbytes (strs, name, (long)(1+strlen(name)));
295         strslen += 1+strlen(name);
296     } else
297         pos = -1;
298
299     sym = saa_wstruct (syms);
300
301     sym->strpos = pos;
302     if (pos == -1)
303         strcpy (sym->name, name);
304     sym->is_global = !!is_global;
305     if (segment == NO_SEG)
306         sym->section = -1;      /* absolute symbol */
307     else {
308         int i;
309         sym->section = 0;
310         for (i=0; i<nsects; i++)
311             if (segment == sects[i]->index) {
312                 sym->section = i+1;
313                 break;
314             }
315         if (!sym->section)
316             sym->is_global = TRUE;
317     }
318     if (is_global == 2)
319         sym->value = offset;
320     else
321         sym->value = (sym->section == 0 ? 0 : offset);
322
323     /*
324      * define the references from external-symbol segment numbers
325      * to these symbol records.
326      */
327     if (sym->section == 0)
328         bsym = raa_write (bsym, segment, nsyms);
329
330     if (segment != NO_SEG)
331         symval = raa_write (symval, segment, sym->section ? 0 : sym->value);
332
333     nsyms++;
334 }
335
336 static long coff_add_reloc (struct Section *sect, long segment,
337                             int relative) {
338     struct Reloc *r;
339
340     r = *sect->tail = nasm_malloc(sizeof(struct Reloc));
341     sect->tail = &r->next;
342     r->next = NULL;
343
344     r->address = sect->len;
345     if (segment == NO_SEG)
346         r->symbol = 0, r->symbase = ABS_SYMBOL;
347     else {
348         int i;
349         r->symbase = REAL_SYMBOLS;
350         for (i=0; i<nsects; i++)
351             if (segment == sects[i]->index) {
352                 r->symbol = i*2;
353                 r->symbase = SECT_SYMBOLS;
354                 break;
355             }
356         if (r->symbase == REAL_SYMBOLS)
357             r->symbol = raa_read (bsym, segment);
358     }
359     r->relative = relative;
360
361     sect->nrelocs++;
362
363     /*
364      * Return the fixup for standard COFF common variables.
365      */
366     if (r->symbase == REAL_SYMBOLS && !win32)
367         return raa_read (symval, segment);
368     else
369         return 0;
370 }
371
372 static void coff_out (long segto, void *data, unsigned long type,
373                       long segment, long wrt) {
374     struct Section *s;
375     long realbytes = type & OUT_SIZMASK;
376     unsigned char mydata[4], *p;
377     int i;
378
379     if (wrt != NO_SEG) {
380         wrt = NO_SEG;                  /* continue to do _something_ */
381         error (ERR_NONFATAL, "WRT not supported by COFF output formats");
382     }
383
384     type &= OUT_TYPMASK;
385
386     /*
387      * handle absolute-assembly (structure definitions)
388      */
389     if (segto == NO_SEG) {
390         if (type != OUT_RESERVE)
391             error (ERR_NONFATAL, "attempt to assemble code in [ABSOLUTE]"
392                    " space");
393         return;
394     }
395
396     s = NULL;
397     for (i=0; i<nsects; i++)
398         if (segto == sects[i]->index) {
399             s = sects[i];
400             break;
401         }
402     if (!s) {
403         int tempint;                   /* ignored */
404         if (segto != coff_section_names (".text", 2, &tempint))
405             error (ERR_PANIC, "strange segment conditions in COFF driver");
406         else
407             s = sects[nsects-1];
408     }
409
410     if (!s->data && type != OUT_RESERVE) {
411         error(ERR_WARNING, "attempt to initialise memory in"
412               " BSS section `%s': ignored", s->name);
413         if (type == OUT_REL2ADR)
414             realbytes = 2;
415         else if (type == OUT_REL4ADR)
416             realbytes = 4;
417         s->len += realbytes;
418         return;
419     }
420
421     if (type == OUT_RESERVE) {
422         if (s->data) {
423             error(ERR_WARNING, "uninitialised space declared in"
424                   " non-BSS section `%s': zeroing", s->name);
425             coff_sect_write (s, NULL, realbytes);
426         } else
427             s->len += realbytes;
428     } else if (type == OUT_RAWDATA) {
429         if (segment != NO_SEG)
430             error(ERR_PANIC, "OUT_RAWDATA with other than NO_SEG");
431         coff_sect_write (s, data, realbytes);
432     } else if (type == OUT_ADDRESS) {
433         if (realbytes == 2 && (segment != NO_SEG || wrt != NO_SEG))
434             error(ERR_NONFATAL, "COFF format does not support 16-bit"
435                   " relocations");
436         else {
437             long fix = 0;
438             if (segment != NO_SEG || wrt != NO_SEG) {
439                 if (wrt != NO_SEG) {
440                     error(ERR_NONFATAL, "COFF format does not support"
441                           " WRT types");
442                 } else if (segment % 2) {
443                     error(ERR_NONFATAL, "COFF format does not support"
444                           " segment base references");
445                 } else
446                     fix = coff_add_reloc (s, segment, FALSE);
447             }
448             p = mydata;
449             WRITELONG (p, *(long *)data + fix);
450             coff_sect_write (s, mydata, realbytes);
451         }
452     } else if (type == OUT_REL2ADR) {
453         error(ERR_NONFATAL, "COFF format does not support 16-bit"
454               " relocations");
455     } else if (type == OUT_REL4ADR) {
456         if (segment == segto)
457             error(ERR_PANIC, "intra-segment OUT_REL4ADR");
458         else if (segment == NO_SEG && win32)
459             error(ERR_NONFATAL, "Win32 COFF does not correctly support"
460                   " relative references to absolute addresses");
461         else {
462             long fix = 0;
463             if (segment != NO_SEG && segment % 2) {
464                 error(ERR_NONFATAL, "COFF format does not support"
465                       " segment base references");
466             } else
467                 fix = coff_add_reloc (s, segment, TRUE);
468             p = mydata;
469             if (win32) {
470                 WRITELONG (p, *(long*)data + 4 - realbytes + fix);
471             } else {
472                 WRITELONG (p, *(long*)data-(realbytes + s->len) + fix);
473             }
474             coff_sect_write (s, mydata, 4L);
475         }
476     }
477 }
478
479 static void coff_sect_write (struct Section *sect,
480                              unsigned char *data, unsigned long len) {
481     saa_wbytes (sect->data, data, len);
482     sect->len += len;
483 }
484
485 static int coff_directives (char *directive, char *value, int pass) {
486     return 0;
487 }
488
489 static void coff_write (void) {
490     long pos, sympos, vsize;
491     int i;
492
493     /*
494      * Work out how big the file will get. Calculate the start of
495      * the `real' symbols at the same time.
496      */
497     pos = 0x14 + 0x28 * nsects;
498     initsym = 3;                       /* two for the file, one absolute */
499     for (i=0; i<nsects; i++) {
500         if (sects[i]->data) {
501             sects[i]->pos = pos;
502             pos += sects[i]->len;
503             sects[i]->relpos = pos;
504             pos += 10 * sects[i]->nrelocs;
505         } else
506             sects[i]->pos = sects[i]->relpos = 0L;
507         initsym += 2;                  /* two for each section */
508     }
509     sympos = pos;
510
511     /*
512      * Output the COFF header.
513      */
514     fwriteshort (0x14C, coffp);        /* MACHINE_i386 */
515     fwriteshort (nsects, coffp);       /* number of sections */
516     fwritelong (time(NULL), coffp);    /* time stamp */
517     fwritelong (sympos, coffp);
518     fwritelong (nsyms + initsym, coffp);
519     fwriteshort (0, coffp);            /* no optional header */
520     /* Flags: 32-bit, no line numbers. Win32 doesn't even bother with them. */
521     fwriteshort (win32 ? 0 : 0x104, coffp);
522
523     /*
524      * Output the section headers.
525      */
526     vsize = 0L;
527     for (i=0; i<nsects; i++) {
528         coff_section_header (sects[i]->name, vsize, sects[i]->len,
529                              sects[i]->pos, sects[i]->relpos,
530                              sects[i]->nrelocs, sects[i]->flags);
531         vsize += sects[i]->len;
532     }
533
534     /*
535      * Output the sections and their relocations.
536      */
537     for (i=0; i<nsects; i++)
538         if (sects[i]->data) {
539             saa_fpwrite (sects[i]->data, coffp);
540             coff_write_relocs (sects[i]);
541         }
542
543     /*
544      * Output the symbol and string tables.
545      */
546     coff_write_symbols();
547     fwritelong (strslen+4, coffp);     /* length includes length count */
548     saa_fpwrite (strs, coffp);
549 }
550
551 static void coff_section_header (char *name, long vsize,
552                                  long datalen, long datapos,
553                                  long relpos, int nrelocs, long flags) {
554     char padname[8];
555
556     memset (padname, 0, 8);
557     strncpy (padname, name, 8);
558     fwrite (padname, 8, 1, coffp);
559     fwritelong (vsize, coffp);
560     fwritelong (0L, coffp);            /* RVA/offset - we ignore */
561     fwritelong (datalen, coffp);
562     fwritelong (datapos, coffp);
563     fwritelong (relpos, coffp);
564     fwritelong (0L, coffp);            /* no line numbers - we don't do 'em */
565     fwriteshort (nrelocs, coffp);
566     fwriteshort (0, coffp);            /* again, no line numbers */
567     fwritelong (flags, coffp);
568 }
569
570 static void coff_write_relocs (struct Section *s) {
571     struct Reloc *r;
572
573     for (r = s->head; r; r = r->next) {
574         fwritelong (r->address, coffp);
575         fwritelong (r->symbol + (r->symbase == REAL_SYMBOLS ? initsym :
576                                  r->symbase == ABS_SYMBOL ? initsym-1 :
577                                  r->symbase == SECT_SYMBOLS ? 2 : 0), coffp);
578         /*
579          * Strange: Microsoft's COFF documentation says 0x03 for an
580          * absolute relocation, but both Visual C++ and DJGPP agree
581          * that in fact it's 0x06. I'll use 0x06 until someone
582          * argues.
583          */
584         fwriteshort (r->relative ? 0x14 : 0x06, coffp);
585     }
586 }
587
588 static void coff_symbol (char *name, long strpos, long value,
589                          int section, int type, int aux) {
590     char padname[8];
591
592     if (name) {
593         memset (padname, 0, 8);
594         strncpy (padname, name, 8);
595         fwrite (padname, 8, 1, coffp);
596     } else {
597         fwritelong (0L, coffp);
598         fwritelong (strpos, coffp);
599     }
600     fwritelong (value, coffp);
601     fwriteshort (section, coffp);
602     fwriteshort (0, coffp);
603     fputc (type, coffp);
604     fputc (aux, coffp);
605 }
606
607 static void coff_write_symbols (void) {
608     char filename[18];
609     int i;
610
611     /*
612      * The `.file' record, and the file name auxiliary record.
613      */
614     coff_symbol (".file", 0L, 0L, -2, 0x67, 1);
615     memset (filename, 0, 18);
616     strncpy (filename, coff_infile, 18);
617     fwrite (filename, 18, 1, coffp);
618
619     /*
620      * The section records, with their auxiliaries.
621      */
622     memset (filename, 0, 18);          /* useful zeroed buffer */
623
624     for (i=0; i<nsects; i++) {
625         coff_symbol (sects[i]->name, 0L, 0L, i+1, 3, 1);
626         fwritelong (sects[i]->len, coffp);
627         fwriteshort (sects[i]->nrelocs, coffp);
628         fwrite (filename, 12, 1, coffp);
629     }
630
631     /*
632      * The absolute symbol, for relative-to-absolute relocations.
633      */
634     coff_symbol (".absolut", 0L, 0L, -1, 3, 0);
635
636     /*
637      * The real symbols.
638      */
639     saa_rewind (syms);
640     for (i=0; i<nsyms; i++) {
641         struct Symbol *sym = saa_rstruct (syms);
642         coff_symbol (sym->strpos == -1 ? sym->name : NULL,
643                      sym->strpos, sym->value, sym->section,
644                      sym->is_global ? 2 : 3, 0);
645     }
646 }
647
648 static long coff_segbase (long segment) {
649     return segment;
650 }
651
652 static void coff_std_filename (char *inname, char *outname, efunc error) {
653     strcpy(coff_infile, inname);
654     standard_extension (inname, outname, ".o", error);
655 }
656
657 static void coff_win32_filename (char *inname, char *outname, efunc error) {
658     strcpy(coff_infile, inname);
659     standard_extension (inname, outname, ".obj", error);
660 }
661
662 #endif /* defined(OF_COFF) || defined(OF_WIN32) */
663
664 #ifdef OF_COFF
665
666 struct ofmt of_coff = {
667     "COFF (i386) object files (e.g. DJGPP for DOS)",
668     "coff",
669     coff_std_init,
670     coff_out,
671     coff_deflabel,
672     coff_section_names,
673     coff_segbase,
674     coff_directives,
675     coff_std_filename,
676     coff_cleanup
677 };
678
679 #endif
680
681 #ifdef OF_WIN32
682
683 struct ofmt of_win32 = {
684     "Microsoft Win32 (i386) object files",
685     "win32",
686     coff_win32_init,
687     coff_out,
688     coff_deflabel,
689     coff_section_names,
690     coff_segbase,
691     coff_directives,
692     coff_win32_filename,
693     coff_cleanup
694 };
695
696 #endif